Set constructor/destructor priority to 1000
[platform/upstream/glibc.git] / elf / dl-load.c
1 /* Map in a shared object's segments from the file.
2    Copyright (C) 1995-2012 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 Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the 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    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, see
17    <http://www.gnu.org/licenses/>.  */
18
19 #include <elf.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <libintl.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <ldsodefs.h>
28 #include <bits/wordsize.h>
29 #include <sys/mman.h>
30 #include <sys/param.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include "dynamic-link.h"
34 #include <abi-tag.h>
35 #include <stackinfo.h>
36 #include <caller.h>
37 #include <sysdep.h>
38 #include <stap-probe.h>
39
40 #include <dl-dst.h>
41
42 /* On some systems, no flag bits are given to specify file mapping.  */
43 #ifndef MAP_FILE
44 # define MAP_FILE       0
45 #endif
46
47 /* The right way to map in the shared library files is MAP_COPY, which
48    makes a virtual copy of the data at the time of the mmap call; this
49    guarantees the mapped pages will be consistent even if the file is
50    overwritten.  Some losing VM systems like Linux's lack MAP_COPY.  All we
51    get is MAP_PRIVATE, which copies each page when it is modified; this
52    means if the file is overwritten, we may at some point get some pages
53    from the new version after starting with pages from the old version.
54
55    To make up for the lack and avoid the overwriting problem,
56    what Linux does have is MAP_DENYWRITE.  This prevents anyone
57    from modifying the file while we have it mapped.  */
58 #ifndef MAP_COPY
59 # ifdef MAP_DENYWRITE
60 #  define MAP_COPY      (MAP_PRIVATE | MAP_DENYWRITE)
61 # else
62 #  define MAP_COPY      MAP_PRIVATE
63 # endif
64 #endif
65
66 /* Some systems link their relocatable objects for another base address
67    than 0.  We want to know the base address for these such that we can
68    subtract this address from the segment addresses during mapping.
69    This results in a more efficient address space usage.  Defaults to
70    zero for almost all systems.  */
71 #ifndef MAP_BASE_ADDR
72 # define MAP_BASE_ADDR(l)       0
73 #endif
74
75
76 #include <endian.h>
77 #if BYTE_ORDER == BIG_ENDIAN
78 # define byteorder ELFDATA2MSB
79 #elif BYTE_ORDER == LITTLE_ENDIAN
80 # define byteorder ELFDATA2LSB
81 #else
82 # error "Unknown BYTE_ORDER " BYTE_ORDER
83 # define byteorder ELFDATANONE
84 #endif
85
86 #define STRING(x) __STRING (x)
87
88 /* Handle situations where we have a preferred location in memory for
89    the shared objects.  */
90 #ifdef ELF_PREFERRED_ADDRESS_DATA
91 ELF_PREFERRED_ADDRESS_DATA;
92 #endif
93 #ifndef ELF_PREFERRED_ADDRESS
94 # define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
95 #endif
96 #ifndef ELF_FIXED_ADDRESS
97 # define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
98 #endif
99
100
101 int __stack_prot attribute_hidden attribute_relro
102 #if _STACK_GROWS_DOWN && defined PROT_GROWSDOWN
103   = PROT_GROWSDOWN;
104 #elif _STACK_GROWS_UP && defined PROT_GROWSUP
105   = PROT_GROWSUP;
106 #else
107   = 0;
108 #endif
109
110
111 /* Type for the buffer we put the ELF header and hopefully the program
112    header.  This buffer does not really have to be too large.  In most
113    cases the program header follows the ELF header directly.  If this
114    is not the case all bets are off and we can make the header
115    arbitrarily large and still won't get it read.  This means the only
116    question is how large are the ELF and program header combined.  The
117    ELF header 32-bit files is 52 bytes long and in 64-bit files is 64
118    bytes long.  Each program header entry is again 32 and 56 bytes
119    long respectively.  I.e., even with a file which has 10 program
120    header entries we only have to read 372B/624B respectively.  Add to
121    this a bit of margin for program notes and reading 512B and 832B
122    for 32-bit and 64-bit files respecitvely is enough.  If this
123    heuristic should really fail for some file the code in
124    `_dl_map_object_from_fd' knows how to recover.  */
125 struct filebuf
126 {
127   ssize_t len;
128 #if __WORDSIZE == 32
129 # define FILEBUF_SIZE 512
130 #else
131 # define FILEBUF_SIZE 832
132 #endif
133   char buf[FILEBUF_SIZE] __attribute__ ((aligned (__alignof (ElfW(Ehdr)))));
134 };
135
136 /* This is the decomposed LD_LIBRARY_PATH search path.  */
137 static struct r_search_path_struct env_path_list attribute_relro;
138
139 /* List of the hardware capabilities we might end up using.  */
140 static const struct r_strlenpair *capstr attribute_relro;
141 static size_t ncapstr attribute_relro;
142 static size_t max_capstrlen attribute_relro;
143
144
145 /* Get the generated information about the trusted directories.  */
146 #include "trusted-dirs.h"
147
148 static const char system_dirs[] = SYSTEM_DIRS;
149 static const size_t system_dirs_len[] =
150 {
151   SYSTEM_DIRS_LEN
152 };
153 #define nsystem_dirs_len \
154   (sizeof (system_dirs_len) / sizeof (system_dirs_len[0]))
155
156
157 /* Local version of `strdup' function.  */
158 static char *
159 local_strdup (const char *s)
160 {
161   size_t len = strlen (s) + 1;
162   void *new = malloc (len);
163
164   if (new == NULL)
165     return NULL;
166
167   return (char *) memcpy (new, s, len);
168 }
169
170
171 static bool
172 is_trusted_path (const char *path, size_t len)
173 {
174   const char *trun = system_dirs;
175
176   for (size_t idx = 0; idx < nsystem_dirs_len; ++idx)
177     {
178       if (len == system_dirs_len[idx] && memcmp (trun, path, len) == 0)
179         /* Found it.  */
180         return true;
181
182       trun += system_dirs_len[idx] + 1;
183     }
184
185   return false;
186 }
187
188
189 static bool
190 is_trusted_path_normalize (const char *path, size_t len)
191 {
192   if (len == 0)
193     return false;
194
195   if (*path == ':')
196     {
197       ++path;
198       --len;
199     }
200
201   char *npath = (char *) alloca (len + 2);
202   char *wnp = npath;
203   while (*path != '\0')
204     {
205       if (path[0] == '/')
206         {
207           if (path[1] == '.')
208             {
209               if (path[2] == '.' && (path[3] == '/' || path[3] == '\0'))
210                 {
211                   while (wnp > npath && *--wnp != '/')
212                     ;
213                   path += 3;
214                   continue;
215                 }
216               else if (path[2] == '/' || path[2] == '\0')
217                 {
218                   path += 2;
219                   continue;
220                 }
221             }
222
223           if (wnp > npath && wnp[-1] == '/')
224             {
225               ++path;
226               continue;
227             }
228         }
229
230       *wnp++ = *path++;
231     }
232
233   if (wnp == npath || wnp[-1] != '/')
234     *wnp++ = '/';
235
236   const char *trun = system_dirs;
237
238   for (size_t idx = 0; idx < nsystem_dirs_len; ++idx)
239     {
240       if (wnp - npath >= system_dirs_len[idx]
241           && memcmp (trun, npath, system_dirs_len[idx]) == 0)
242         /* Found it.  */
243         return true;
244
245       trun += system_dirs_len[idx] + 1;
246     }
247
248   return false;
249 }
250
251
252 static size_t
253 is_dst (const char *start, const char *name, const char *str,
254         int is_path, int secure)
255 {
256   size_t len;
257   bool is_curly = false;
258
259   if (name[0] == '{')
260     {
261       is_curly = true;
262       ++name;
263     }
264
265   len = 0;
266   while (name[len] == str[len] && name[len] != '\0')
267     ++len;
268
269   if (is_curly)
270     {
271       if (name[len] != '}')
272         return 0;
273
274       /* Point again at the beginning of the name.  */
275       --name;
276       /* Skip over closing curly brace and adjust for the --name.  */
277       len += 2;
278     }
279   else if (name[len] != '\0' && name[len] != '/'
280            && (!is_path || name[len] != ':'))
281     return 0;
282
283   if (__builtin_expect (secure, 0)
284       && ((name[len] != '\0' && name[len] != '/'
285            && (!is_path || name[len] != ':'))
286           || (name != start + 1 && (!is_path || name[-2] != ':'))))
287     return 0;
288
289   return len;
290 }
291
292
293 size_t
294 _dl_dst_count (const char *name, int is_path)
295 {
296   const char *const start = name;
297   size_t cnt = 0;
298
299   do
300     {
301       size_t len;
302
303       /* $ORIGIN is not expanded for SUID/GUID programs (except if it
304          is $ORIGIN alone) and it must always appear first in path.  */
305       ++name;
306       if ((len = is_dst (start, name, "ORIGIN", is_path,
307                          INTUSE(__libc_enable_secure))) != 0
308           || (len = is_dst (start, name, "PLATFORM", is_path, 0)) != 0
309           || (len = is_dst (start, name, "LIB", is_path, 0)) != 0)
310         ++cnt;
311
312       name = strchr (name + len, '$');
313     }
314   while (name != NULL);
315
316   return cnt;
317 }
318
319
320 char *
321 _dl_dst_substitute (struct link_map *l, const char *name, char *result,
322                     int is_path)
323 {
324   const char *const start = name;
325
326   /* Now fill the result path.  While copying over the string we keep
327      track of the start of the last path element.  When we come accross
328      a DST we copy over the value or (if the value is not available)
329      leave the entire path element out.  */
330   char *wp = result;
331   char *last_elem = result;
332   bool check_for_trusted = false;
333
334   do
335     {
336       if (__builtin_expect (*name == '$', 0))
337         {
338           const char *repl = NULL;
339           size_t len;
340
341           ++name;
342           if ((len = is_dst (start, name, "ORIGIN", is_path,
343                              INTUSE(__libc_enable_secure))) != 0)
344             {
345 #ifndef SHARED
346               if (l == NULL)
347                 repl = _dl_get_origin ();
348               else
349 #endif
350                 repl = l->l_origin;
351
352               check_for_trusted = (INTUSE(__libc_enable_secure)
353                                    && l->l_type == lt_executable);
354             }
355           else if ((len = is_dst (start, name, "PLATFORM", is_path, 0)) != 0)
356             repl = GLRO(dl_platform);
357           else if ((len = is_dst (start, name, "LIB", is_path, 0)) != 0)
358             repl = DL_DST_LIB;
359
360           if (repl != NULL && repl != (const char *) -1)
361             {
362               wp = __stpcpy (wp, repl);
363               name += len;
364             }
365           else if (len > 1)
366             {
367               /* We cannot use this path element, the value of the
368                  replacement is unknown.  */
369               wp = last_elem;
370               name += len;
371               while (*name != '\0' && (!is_path || *name != ':'))
372                 ++name;
373               /* Also skip following colon if this is the first rpath
374                  element, but keep an empty element at the end.  */
375               if (wp == result && is_path && *name == ':' && name[1] != '\0')
376                 ++name;
377             }
378           else
379             /* No DST we recognize.  */
380             *wp++ = '$';
381         }
382       else
383         {
384           *wp++ = *name++;
385           if (is_path && *name == ':')
386             {
387               /* In SUID/SGID programs, after $ORIGIN expansion the
388                  normalized path must be rooted in one of the trusted
389                  directories.  */
390               if (__builtin_expect (check_for_trusted, false)
391                   && !is_trusted_path_normalize (last_elem, wp - last_elem))
392                 wp = last_elem;
393               else
394                 last_elem = wp;
395
396               check_for_trusted = false;
397             }
398         }
399     }
400   while (*name != '\0');
401
402   /* In SUID/SGID programs, after $ORIGIN expansion the normalized
403      path must be rooted in one of the trusted directories.  */
404   if (__builtin_expect (check_for_trusted, false)
405       && !is_trusted_path_normalize (last_elem, wp - last_elem))
406     wp = last_elem;
407
408   *wp = '\0';
409
410   return result;
411 }
412
413
414 /* Return copy of argument with all recognized dynamic string tokens
415    ($ORIGIN and $PLATFORM for now) replaced.  On some platforms it
416    might not be possible to determine the path from which the object
417    belonging to the map is loaded.  In this case the path element
418    containing $ORIGIN is left out.  */
419 static char *
420 expand_dynamic_string_token (struct link_map *l, const char *s, int is_path)
421 {
422   /* We make two runs over the string.  First we determine how large the
423      resulting string is and then we copy it over.  Since this is no
424      frequently executed operation we are looking here not for performance
425      but rather for code size.  */
426   size_t cnt;
427   size_t total;
428   char *result;
429
430   /* Determine the number of DST elements.  */
431   cnt = DL_DST_COUNT (s, is_path);
432
433   /* If we do not have to replace anything simply copy the string.  */
434   if (__builtin_expect (cnt, 0) == 0)
435     return local_strdup (s);
436
437   /* Determine the length of the substituted string.  */
438   total = DL_DST_REQUIRED (l, s, strlen (s), cnt);
439
440   /* Allocate the necessary memory.  */
441   result = (char *) malloc (total + 1);
442   if (result == NULL)
443     return NULL;
444
445   return _dl_dst_substitute (l, s, result, is_path);
446 }
447
448
449 /* Add `name' to the list of names for a particular shared object.
450    `name' is expected to have been allocated with malloc and will
451    be freed if the shared object already has this name.
452    Returns false if the object already had this name.  */
453 static void
454 internal_function
455 add_name_to_object (struct link_map *l, const char *name)
456 {
457   struct libname_list *lnp, *lastp;
458   struct libname_list *newname;
459   size_t name_len;
460
461   lastp = NULL;
462   for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
463     if (strcmp (name, lnp->name) == 0)
464       return;
465
466   name_len = strlen (name) + 1;
467   newname = (struct libname_list *) malloc (sizeof *newname + name_len);
468   if (newname == NULL)
469     {
470       /* No more memory.  */
471       _dl_signal_error (ENOMEM, name, NULL, N_("cannot allocate name record"));
472       return;
473     }
474   /* The object should have a libname set from _dl_new_object.  */
475   assert (lastp != NULL);
476
477   newname->name = memcpy (newname + 1, name, name_len);
478   newname->next = NULL;
479   newname->dont_free = 0;
480   lastp->next = newname;
481 }
482
483 /* Standard search directories.  */
484 static struct r_search_path_struct rtld_search_dirs attribute_relro;
485
486 static size_t max_dirnamelen;
487
488 static struct r_search_path_elem **
489 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
490               int check_trusted, const char *what, const char *where)
491 {
492   char *cp;
493   size_t nelems = 0;
494
495   while ((cp = __strsep (&rpath, sep)) != NULL)
496     {
497       struct r_search_path_elem *dirp;
498       size_t len = strlen (cp);
499
500       /* `strsep' can pass an empty string.  This has to be
501          interpreted as `use the current directory'. */
502       if (len == 0)
503         {
504           static const char curwd[] = "./";
505           cp = (char *) curwd;
506         }
507
508       /* Remove trailing slashes (except for "/").  */
509       while (len > 1 && cp[len - 1] == '/')
510         --len;
511
512       /* Now add one if there is none so far.  */
513       if (len > 0 && cp[len - 1] != '/')
514         cp[len++] = '/';
515
516       /* Make sure we don't use untrusted directories if we run SUID.  */
517       if (__builtin_expect (check_trusted, 0) && !is_trusted_path (cp, len))
518         continue;
519
520       /* See if this directory is already known.  */
521       for (dirp = GL(dl_all_dirs); dirp != NULL; dirp = dirp->next)
522         if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
523           break;
524
525       if (dirp != NULL)
526         {
527           /* It is available, see whether it's on our own list.  */
528           size_t cnt;
529           for (cnt = 0; cnt < nelems; ++cnt)
530             if (result[cnt] == dirp)
531               break;
532
533           if (cnt == nelems)
534             result[nelems++] = dirp;
535         }
536       else
537         {
538           size_t cnt;
539           enum r_dir_status init_val;
540           size_t where_len = where ? strlen (where) + 1 : 0;
541
542           /* It's a new directory.  Create an entry and add it.  */
543           dirp = (struct r_search_path_elem *)
544             malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status)
545                     + where_len + len + 1);
546           if (dirp == NULL)
547             _dl_signal_error (ENOMEM, NULL, NULL,
548                               N_("cannot create cache for search path"));
549
550           dirp->dirname = ((char *) dirp + sizeof (*dirp)
551                            + ncapstr * sizeof (enum r_dir_status));
552           *((char *) __mempcpy ((char *) dirp->dirname, cp, len)) = '\0';
553           dirp->dirnamelen = len;
554
555           if (len > max_dirnamelen)
556             max_dirnamelen = len;
557
558           /* We have to make sure all the relative directories are
559              never ignored.  The current directory might change and
560              all our saved information would be void.  */
561           init_val = cp[0] != '/' ? existing : unknown;
562           for (cnt = 0; cnt < ncapstr; ++cnt)
563             dirp->status[cnt] = init_val;
564
565           dirp->what = what;
566           if (__builtin_expect (where != NULL, 1))
567             dirp->where = memcpy ((char *) dirp + sizeof (*dirp) + len + 1
568                                   + (ncapstr * sizeof (enum r_dir_status)),
569                                   where, where_len);
570           else
571             dirp->where = NULL;
572
573           dirp->next = GL(dl_all_dirs);
574           GL(dl_all_dirs) = dirp;
575
576           /* Put it in the result array.  */
577           result[nelems++] = dirp;
578         }
579     }
580
581   /* Terminate the array.  */
582   result[nelems] = NULL;
583
584   return result;
585 }
586
587
588 static bool
589 internal_function
590 decompose_rpath (struct r_search_path_struct *sps,
591                  const char *rpath, struct link_map *l, const char *what)
592 {
593   /* Make a copy we can work with.  */
594   const char *where = l->l_name;
595   char *copy;
596   char *cp;
597   struct r_search_path_elem **result;
598   size_t nelems;
599   /* Initialize to please the compiler.  */
600   const char *errstring = NULL;
601
602   /* First see whether we must forget the RUNPATH and RPATH from this
603      object.  */
604   if (__builtin_expect (GLRO(dl_inhibit_rpath) != NULL, 0)
605       && !INTUSE(__libc_enable_secure))
606     {
607       const char *inhp = GLRO(dl_inhibit_rpath);
608
609       do
610         {
611           const char *wp = where;
612
613           while (*inhp == *wp && *wp != '\0')
614             {
615               ++inhp;
616               ++wp;
617             }
618
619           if (*wp == '\0' && (*inhp == '\0' || *inhp == ':'))
620             {
621               /* This object is on the list of objects for which the
622                  RUNPATH and RPATH must not be used.  */
623               sps->dirs = (void *) -1;
624               return false;
625             }
626
627           while (*inhp != '\0')
628             if (*inhp++ == ':')
629               break;
630         }
631       while (*inhp != '\0');
632     }
633
634   /* Make a writable copy.  At the same time expand possible dynamic
635      string tokens.  */
636   copy = expand_dynamic_string_token (l, rpath, 1);
637   if (copy == NULL)
638     {
639       errstring = N_("cannot create RUNPATH/RPATH copy");
640       goto signal_error;
641     }
642
643   /* Ignore empty rpaths.  */
644   if (*copy == 0)
645     {
646       free (copy);
647       sps->dirs = (struct r_search_path_elem **) -1;
648       return false;
649     }
650
651   /* Count the number of necessary elements in the result array.  */
652   nelems = 0;
653   for (cp = copy; *cp != '\0'; ++cp)
654     if (*cp == ':')
655       ++nelems;
656
657   /* Allocate room for the result.  NELEMS + 1 is an upper limit for the
658      number of necessary entries.  */
659   result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
660                                                   * sizeof (*result));
661   if (result == NULL)
662     {
663       free (copy);
664       errstring = N_("cannot create cache for search path");
665     signal_error:
666       _dl_signal_error (ENOMEM, NULL, NULL, errstring);
667     }
668
669   fillin_rpath (copy, result, ":", 0, what, where);
670
671   /* Free the copied RPATH string.  `fillin_rpath' make own copies if
672      necessary.  */
673   free (copy);
674
675   sps->dirs = result;
676   /* The caller will change this value if we haven't used a real malloc.  */
677   sps->malloced = 1;
678   return true;
679 }
680
681 /* Make sure cached path information is stored in *SP
682    and return true if there are any paths to search there.  */
683 static bool
684 cache_rpath (struct link_map *l,
685              struct r_search_path_struct *sp,
686              int tag,
687              const char *what)
688 {
689   if (sp->dirs == (void *) -1)
690     return false;
691
692   if (sp->dirs != NULL)
693     return true;
694
695   if (l->l_info[tag] == NULL)
696     {
697       /* There is no path.  */
698       sp->dirs = (void *) -1;
699       return false;
700     }
701
702   /* Make sure the cache information is available.  */
703   return decompose_rpath (sp, (const char *) (D_PTR (l, l_info[DT_STRTAB])
704                                               + l->l_info[tag]->d_un.d_val),
705                           l, what);
706 }
707
708
709 void
710 internal_function
711 _dl_init_paths (const char *llp)
712 {
713   size_t idx;
714   const char *strp;
715   struct r_search_path_elem *pelem, **aelem;
716   size_t round_size;
717 #ifdef SHARED
718   struct link_map *l;
719 #endif
720   /* Initialize to please the compiler.  */
721   const char *errstring = NULL;
722
723   /* Fill in the information about the application's RPATH and the
724      directories addressed by the LD_LIBRARY_PATH environment variable.  */
725
726   /* Get the capabilities.  */
727   capstr = _dl_important_hwcaps (GLRO(dl_platform), GLRO(dl_platformlen),
728                                  &ncapstr, &max_capstrlen);
729
730   /* First set up the rest of the default search directory entries.  */
731   aelem = rtld_search_dirs.dirs = (struct r_search_path_elem **)
732     malloc ((nsystem_dirs_len + 1) * sizeof (struct r_search_path_elem *));
733   if (rtld_search_dirs.dirs == NULL)
734     {
735       errstring = N_("cannot create search path array");
736     signal_error:
737       _dl_signal_error (ENOMEM, NULL, NULL, errstring);
738     }
739
740   round_size = ((2 * sizeof (struct r_search_path_elem) - 1
741                  + ncapstr * sizeof (enum r_dir_status))
742                 / sizeof (struct r_search_path_elem));
743
744   rtld_search_dirs.dirs[0] = (struct r_search_path_elem *)
745     malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]))
746             * round_size * sizeof (struct r_search_path_elem));
747   if (rtld_search_dirs.dirs[0] == NULL)
748     {
749       errstring = N_("cannot create cache for search path");
750       goto signal_error;
751     }
752
753   rtld_search_dirs.malloced = 0;
754   pelem = GL(dl_all_dirs) = rtld_search_dirs.dirs[0];
755   strp = system_dirs;
756   idx = 0;
757
758   do
759     {
760       size_t cnt;
761
762       *aelem++ = pelem;
763
764       pelem->what = "system search path";
765       pelem->where = NULL;
766
767       pelem->dirname = strp;
768       pelem->dirnamelen = system_dirs_len[idx];
769       strp += system_dirs_len[idx] + 1;
770
771       /* System paths must be absolute.  */
772       assert (pelem->dirname[0] == '/');
773       for (cnt = 0; cnt < ncapstr; ++cnt)
774         pelem->status[cnt] = unknown;
775
776       pelem->next = (++idx == nsystem_dirs_len ? NULL : (pelem + round_size));
777
778       pelem += round_size;
779     }
780   while (idx < nsystem_dirs_len);
781
782   max_dirnamelen = SYSTEM_DIRS_MAX_LEN;
783   *aelem = NULL;
784
785 #ifdef SHARED
786   /* This points to the map of the main object.  */
787   l = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
788   if (l != NULL)
789     {
790       assert (l->l_type != lt_loaded);
791
792       if (l->l_info[DT_RUNPATH])
793         {
794           /* Allocate room for the search path and fill in information
795              from RUNPATH.  */
796           decompose_rpath (&l->l_runpath_dirs,
797                            (const void *) (D_PTR (l, l_info[DT_STRTAB])
798                                            + l->l_info[DT_RUNPATH]->d_un.d_val),
799                            l, "RUNPATH");
800
801           /* The RPATH is ignored.  */
802           l->l_rpath_dirs.dirs = (void *) -1;
803         }
804       else
805         {
806           l->l_runpath_dirs.dirs = (void *) -1;
807
808           if (l->l_info[DT_RPATH])
809             {
810               /* Allocate room for the search path and fill in information
811                  from RPATH.  */
812               decompose_rpath (&l->l_rpath_dirs,
813                                (const void *) (D_PTR (l, l_info[DT_STRTAB])
814                                                + l->l_info[DT_RPATH]->d_un.d_val),
815                                l, "RPATH");
816               l->l_rpath_dirs.malloced = 0;
817             }
818           else
819             l->l_rpath_dirs.dirs = (void *) -1;
820         }
821     }
822 #endif  /* SHARED */
823
824   if (llp != NULL && *llp != '\0')
825     {
826       size_t nllp;
827       const char *cp = llp;
828       char *llp_tmp;
829
830 #ifdef SHARED
831       /* Expand DSTs.  */
832       size_t cnt = DL_DST_COUNT (llp, 1);
833       if (__builtin_expect (cnt == 0, 1))
834         llp_tmp = strdupa (llp);
835       else
836         {
837           /* Determine the length of the substituted string.  */
838           size_t total = DL_DST_REQUIRED (l, llp, strlen (llp), cnt);
839
840           /* Allocate the necessary memory.  */
841           llp_tmp = (char *) alloca (total + 1);
842           llp_tmp = _dl_dst_substitute (l, llp, llp_tmp, 1);
843         }
844 #else
845       llp_tmp = strdupa (llp);
846 #endif
847
848       /* Decompose the LD_LIBRARY_PATH contents.  First determine how many
849          elements it has.  */
850       nllp = 1;
851       while (*cp)
852         {
853           if (*cp == ':' || *cp == ';')
854             ++nllp;
855           ++cp;
856         }
857
858       env_path_list.dirs = (struct r_search_path_elem **)
859         malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
860       if (env_path_list.dirs == NULL)
861         {
862           errstring = N_("cannot create cache for search path");
863           goto signal_error;
864         }
865
866       (void) fillin_rpath (llp_tmp, env_path_list.dirs, ":;",
867                            INTUSE(__libc_enable_secure), "LD_LIBRARY_PATH",
868                            NULL);
869
870       if (env_path_list.dirs[0] == NULL)
871         {
872           free (env_path_list.dirs);
873           env_path_list.dirs = (void *) -1;
874         }
875
876       env_path_list.malloced = 0;
877     }
878   else
879     env_path_list.dirs = (void *) -1;
880 }
881
882
883 static void
884 __attribute__ ((noreturn, noinline))
885 lose (int code, int fd, const char *name, char *realname, struct link_map *l,
886       const char *msg, struct r_debug *r, Lmid_t nsid)
887 {
888   /* The file might already be closed.  */
889   if (fd != -1)
890     (void) __close (fd);
891   if (l != NULL && l->l_origin != (char *) -1l)
892     free ((char *) l->l_origin);
893   free (l);
894   free (realname);
895
896   if (r != NULL)
897     {
898       r->r_state = RT_CONSISTENT;
899       _dl_debug_state ();
900       LIBC_PROBE (map_failed, 2, nsid, r);
901     }
902
903   _dl_signal_error (code, name, NULL, msg);
904 }
905
906
907 /* Map in the shared object NAME, actually located in REALNAME, and already
908    opened on FD.  */
909
910 #ifndef EXTERNAL_MAP_FROM_FD
911 static
912 #endif
913 struct link_map *
914 _dl_map_object_from_fd (const char *name, int fd, struct filebuf *fbp,
915                         char *realname, struct link_map *loader, int l_type,
916                         int mode, void **stack_endp, Lmid_t nsid)
917 {
918   struct link_map *l = NULL;
919   const ElfW(Ehdr) *header;
920   const ElfW(Phdr) *phdr;
921   const ElfW(Phdr) *ph;
922   size_t maplength;
923   int type;
924   struct stat64 st;
925   /* Initialize to keep the compiler happy.  */
926   const char *errstring = NULL;
927   int errval = 0;
928   struct r_debug *r = _dl_debug_initialize (0, nsid);
929   bool make_consistent = false;
930
931   /* Get file information.  */
932   if (__builtin_expect (__fxstat64 (_STAT_VER, fd, &st) < 0, 0))
933     {
934       errstring = N_("cannot stat shared object");
935     call_lose_errno:
936       errval = errno;
937     call_lose:
938       lose (errval, fd, name, realname, l, errstring,
939             make_consistent ? r : NULL, nsid);
940     }
941
942   /* Look again to see if the real name matched another already loaded.  */
943   for (l = GL(dl_ns)[nsid]._ns_loaded; l; l = l->l_next)
944     if (l->l_removed == 0 && l->l_ino == st.st_ino && l->l_dev == st.st_dev)
945       {
946         /* The object is already loaded.
947            Just bump its reference count and return it.  */
948         __close (fd);
949
950         /* If the name is not in the list of names for this object add
951            it.  */
952         free (realname);
953         add_name_to_object (l, name);
954
955         return l;
956       }
957
958 #ifdef SHARED
959   /* When loading into a namespace other than the base one we must
960      avoid loading ld.so since there can only be one copy.  Ever.  */
961   if (__builtin_expect (nsid != LM_ID_BASE, 0)
962       && ((st.st_ino == GL(dl_rtld_map).l_ino
963            && st.st_dev == GL(dl_rtld_map).l_dev)
964           || _dl_name_match_p (name, &GL(dl_rtld_map))))
965     {
966       /* This is indeed ld.so.  Create a new link_map which refers to
967          the real one for almost everything.  */
968       l = _dl_new_object (realname, name, l_type, loader, mode, nsid);
969       if (l == NULL)
970         goto fail_new;
971
972       /* Refer to the real descriptor.  */
973       l->l_real = &GL(dl_rtld_map);
974
975       /* No need to bump the refcount of the real object, ld.so will
976          never be unloaded.  */
977       __close (fd);
978
979       /* Add the map for the mirrored object to the object list.  */
980       _dl_add_to_namespace_list (l, nsid);
981
982       return l;
983     }
984 #endif
985
986   if (mode & RTLD_NOLOAD)
987     {
988       /* We are not supposed to load the object unless it is already
989          loaded.  So return now.  */
990       free (realname);
991       __close (fd);
992       return NULL;
993     }
994
995   /* Print debugging message.  */
996   if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
997     _dl_debug_printf ("file=%s [%lu];  generating link map\n", name, nsid);
998
999   /* This is the ELF header.  We read it in `open_verify'.  */
1000   header = (void *) fbp->buf;
1001
1002 #ifndef MAP_ANON
1003 # define MAP_ANON 0
1004   if (_dl_zerofd == -1)
1005     {
1006       _dl_zerofd = _dl_sysdep_open_zero_fill ();
1007       if (_dl_zerofd == -1)
1008         {
1009           free (realname);
1010           __close (fd);
1011           _dl_signal_error (errno, NULL, NULL,
1012                             N_("cannot open zero fill device"));
1013         }
1014     }
1015 #endif
1016
1017   /* Signal that we are going to add new objects.  */
1018   if (r->r_state == RT_CONSISTENT)
1019     {
1020 #ifdef SHARED
1021       /* Auditing checkpoint: we are going to add new objects.  */
1022       if ((mode & __RTLD_AUDIT) == 0
1023           && __builtin_expect (GLRO(dl_naudit) > 0, 0))
1024         {
1025           struct link_map *head = GL(dl_ns)[nsid]._ns_loaded;
1026           /* Do not call the functions for any auditing object.  */
1027           if (head->l_auditing == 0)
1028             {
1029               struct audit_ifaces *afct = GLRO(dl_audit);
1030               for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1031                 {
1032                   if (afct->activity != NULL)
1033                     afct->activity (&head->l_audit[cnt].cookie, LA_ACT_ADD);
1034
1035                   afct = afct->next;
1036                 }
1037             }
1038         }
1039 #endif
1040
1041       /* Notify the debugger we have added some objects.  We need to
1042          call _dl_debug_initialize in a static program in case dynamic
1043          linking has not been used before.  */
1044       r->r_state = RT_ADD;
1045       _dl_debug_state ();
1046       LIBC_PROBE (map_start, 2, nsid, r);
1047       make_consistent = true;
1048     }
1049   else
1050     assert (r->r_state == RT_ADD);
1051
1052   /* Enter the new object in the list of loaded objects.  */
1053   l = _dl_new_object (realname, name, l_type, loader, mode, nsid);
1054   if (__builtin_expect (l == NULL, 0))
1055     {
1056 #ifdef SHARED
1057     fail_new:
1058 #endif
1059       errstring = N_("cannot create shared object descriptor");
1060       goto call_lose_errno;
1061     }
1062
1063   /* Extract the remaining details we need from the ELF header
1064      and then read in the program header table.  */
1065   l->l_entry = header->e_entry;
1066   type = header->e_type;
1067   l->l_phnum = header->e_phnum;
1068
1069   maplength = header->e_phnum * sizeof (ElfW(Phdr));
1070   if (header->e_phoff + maplength <= (size_t) fbp->len)
1071     phdr = (void *) (fbp->buf + header->e_phoff);
1072   else
1073     {
1074       phdr = alloca (maplength);
1075       __lseek (fd, header->e_phoff, SEEK_SET);
1076       if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
1077         {
1078           errstring = N_("cannot read file data");
1079           goto call_lose_errno;
1080         }
1081     }
1082
1083    /* On most platforms presume that PT_GNU_STACK is absent and the stack is
1084     * executable.  Other platforms default to a nonexecutable stack and don't
1085     * need PT_GNU_STACK to do so.  */
1086    uint_fast16_t stack_flags = DEFAULT_STACK_PERMS;
1087
1088   {
1089     /* Scan the program header table, collecting its load commands.  */
1090     struct loadcmd
1091       {
1092         ElfW(Addr) mapstart, mapend, dataend, allocend;
1093         ElfW(Off) mapoff;
1094         int prot;
1095       } loadcmds[l->l_phnum], *c;
1096     size_t nloadcmds = 0;
1097     bool has_holes = false;
1098
1099     /* The struct is initialized to zero so this is not necessary:
1100     l->l_ld = 0;
1101     l->l_phdr = 0;
1102     l->l_addr = 0; */
1103     for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
1104       switch (ph->p_type)
1105         {
1106           /* These entries tell us where to find things once the file's
1107              segments are mapped in.  We record the addresses it says
1108              verbatim, and later correct for the run-time load address.  */
1109         case PT_DYNAMIC:
1110           l->l_ld = (void *) ph->p_vaddr;
1111           l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1112           break;
1113
1114         case PT_PHDR:
1115           l->l_phdr = (void *) ph->p_vaddr;
1116           break;
1117
1118         case PT_LOAD:
1119           /* A load command tells us to map in part of the file.
1120              We record the load commands and process them all later.  */
1121           if (__builtin_expect ((ph->p_align & (GLRO(dl_pagesize) - 1)) != 0,
1122                                 0))
1123             {
1124               errstring = N_("ELF load command alignment not page-aligned");
1125               goto call_lose;
1126             }
1127           if (__builtin_expect (((ph->p_vaddr - ph->p_offset)
1128                                  & (ph->p_align - 1)) != 0, 0))
1129             {
1130               errstring
1131                 = N_("ELF load command address/offset not properly aligned");
1132               goto call_lose;
1133             }
1134
1135           c = &loadcmds[nloadcmds++];
1136           c->mapstart = ph->p_vaddr & ~(GLRO(dl_pagesize) - 1);
1137           c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1)
1138                        & ~(GLRO(dl_pagesize) - 1));
1139           c->dataend = ph->p_vaddr + ph->p_filesz;
1140           c->allocend = ph->p_vaddr + ph->p_memsz;
1141           c->mapoff = ph->p_offset & ~(GLRO(dl_pagesize) - 1);
1142
1143           /* Determine whether there is a gap between the last segment
1144              and this one.  */
1145           if (nloadcmds > 1 && c[-1].mapend != c->mapstart)
1146             has_holes = true;
1147
1148           /* Optimize a common case.  */
1149 #if (PF_R | PF_W | PF_X) == 7 && (PROT_READ | PROT_WRITE | PROT_EXEC) == 7
1150           c->prot = (PF_TO_PROT
1151                      >> ((ph->p_flags & (PF_R | PF_W | PF_X)) * 4)) & 0xf;
1152 #else
1153           c->prot = 0;
1154           if (ph->p_flags & PF_R)
1155             c->prot |= PROT_READ;
1156           if (ph->p_flags & PF_W)
1157             c->prot |= PROT_WRITE;
1158           if (ph->p_flags & PF_X)
1159             c->prot |= PROT_EXEC;
1160 #endif
1161           break;
1162
1163         case PT_TLS:
1164           if (ph->p_memsz == 0)
1165             /* Nothing to do for an empty segment.  */
1166             break;
1167
1168           l->l_tls_blocksize = ph->p_memsz;
1169           l->l_tls_align = ph->p_align;
1170           if (ph->p_align == 0)
1171             l->l_tls_firstbyte_offset = 0;
1172           else
1173             l->l_tls_firstbyte_offset = ph->p_vaddr & (ph->p_align - 1);
1174           l->l_tls_initimage_size = ph->p_filesz;
1175           /* Since we don't know the load address yet only store the
1176              offset.  We will adjust it later.  */
1177           l->l_tls_initimage = (void *) ph->p_vaddr;
1178
1179           /* If not loading the initial set of shared libraries,
1180              check whether we should permit loading a TLS segment.  */
1181           if (__builtin_expect (l->l_type == lt_library, 1)
1182               /* If GL(dl_tls_dtv_slotinfo_list) == NULL, then rtld.c did
1183                  not set up TLS data structures, so don't use them now.  */
1184               || __builtin_expect (GL(dl_tls_dtv_slotinfo_list) != NULL, 1))
1185             {
1186               /* Assign the next available module ID.  */
1187               l->l_tls_modid = _dl_next_tls_modid ();
1188               break;
1189             }
1190
1191 #ifdef SHARED
1192           if (l->l_prev == NULL || (mode & __RTLD_AUDIT) != 0)
1193             /* We are loading the executable itself when the dynamic linker
1194                was executed directly.  The setup will happen later.  */
1195             break;
1196
1197 # ifdef _LIBC_REENTRANT
1198           /* In a static binary there is no way to tell if we dynamically
1199              loaded libpthread.  */
1200           if (GL(dl_error_catch_tsd) == &_dl_initial_error_catch_tsd)
1201 # endif
1202 #endif
1203             {
1204               /* We have not yet loaded libpthread.
1205                  We can do the TLS setup right now!  */
1206
1207               void *tcb;
1208
1209               /* The first call allocates TLS bookkeeping data structures.
1210                  Then we allocate the TCB for the initial thread.  */
1211               if (__builtin_expect (_dl_tls_setup (), 0)
1212                   || __builtin_expect ((tcb = _dl_allocate_tls (NULL)) == NULL,
1213                                        0))
1214                 {
1215                   errval = ENOMEM;
1216                   errstring = N_("\
1217 cannot allocate TLS data structures for initial thread");
1218                   goto call_lose;
1219                 }
1220
1221               /* Now we install the TCB in the thread register.  */
1222               errstring = TLS_INIT_TP (tcb, 0);
1223               if (__builtin_expect (errstring == NULL, 1))
1224                 {
1225                   /* Now we are all good.  */
1226                   l->l_tls_modid = ++GL(dl_tls_max_dtv_idx);
1227                   break;
1228                 }
1229
1230               /* The kernel is too old or somesuch.  */
1231               errval = 0;
1232               _dl_deallocate_tls (tcb, 1);
1233               goto call_lose;
1234             }
1235
1236           /* Uh-oh, the binary expects TLS support but we cannot
1237              provide it.  */
1238           errval = 0;
1239           errstring = N_("cannot handle TLS data");
1240           goto call_lose;
1241           break;
1242
1243         case PT_GNU_STACK:
1244           stack_flags = ph->p_flags;
1245           break;
1246
1247         case PT_GNU_RELRO:
1248           l->l_relro_addr = ph->p_vaddr;
1249           l->l_relro_size = ph->p_memsz;
1250           break;
1251         }
1252
1253     if (__builtin_expect (nloadcmds == 0, 0))
1254       {
1255         /* This only happens for a bogus object that will be caught with
1256            another error below.  But we don't want to go through the
1257            calculations below using NLOADCMDS - 1.  */
1258         errstring = N_("object file has no loadable segments");
1259         goto call_lose;
1260       }
1261
1262     /* Now process the load commands and map segments into memory.  */
1263     c = loadcmds;
1264
1265     /* Length of the sections to be loaded.  */
1266     maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
1267
1268     if (__builtin_expect (type, ET_DYN) == ET_DYN)
1269       {
1270         /* This is a position-independent shared object.  We can let the
1271            kernel map it anywhere it likes, but we must have space for all
1272            the segments in their specified positions relative to the first.
1273            So we map the first segment without MAP_FIXED, but with its
1274            extent increased to cover all the segments.  Then we remove
1275            access from excess portion, and there is known sufficient space
1276            there to remap from the later segments.
1277
1278            As a refinement, sometimes we have an address that we would
1279            prefer to map such objects at; but this is only a preference,
1280            the OS can do whatever it likes. */
1281         ElfW(Addr) mappref;
1282         mappref = (ELF_PREFERRED_ADDRESS (loader, maplength,
1283                                           c->mapstart & GLRO(dl_use_load_bias))
1284                    - MAP_BASE_ADDR (l));
1285
1286         /* Remember which part of the address space this object uses.  */
1287         l->l_map_start = (ElfW(Addr)) __mmap ((void *) mappref, maplength,
1288                                               c->prot,
1289                                               MAP_COPY|MAP_FILE,
1290                                               fd, c->mapoff);
1291         if (__builtin_expect ((void *) l->l_map_start == MAP_FAILED, 0))
1292           {
1293           map_error:
1294             errstring = N_("failed to map segment from shared object");
1295             goto call_lose_errno;
1296           }
1297
1298         l->l_map_end = l->l_map_start + maplength;
1299         l->l_addr = l->l_map_start - c->mapstart;
1300
1301         if (has_holes)
1302           /* Change protection on the excess portion to disallow all access;
1303              the portions we do not remap later will be inaccessible as if
1304              unallocated.  Then jump into the normal segment-mapping loop to
1305              handle the portion of the segment past the end of the file
1306              mapping.  */
1307           __mprotect ((caddr_t) (l->l_addr + c->mapend),
1308                       loadcmds[nloadcmds - 1].mapstart - c->mapend,
1309                       PROT_NONE);
1310
1311         l->l_contiguous = 1;
1312
1313         goto postmap;
1314       }
1315
1316     /* This object is loaded at a fixed address.  This must never
1317        happen for objects loaded with dlopen().  */
1318     if (__builtin_expect ((mode & __RTLD_OPENEXEC) == 0, 0))
1319       {
1320         errstring = N_("cannot dynamically load executable");
1321         goto call_lose;
1322       }
1323
1324     /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
1325        fixed.  */
1326     ELF_FIXED_ADDRESS (loader, c->mapstart);
1327
1328
1329     /* Remember which part of the address space this object uses.  */
1330     l->l_map_start = c->mapstart + l->l_addr;
1331     l->l_map_end = l->l_map_start + maplength;
1332     l->l_contiguous = !has_holes;
1333
1334     while (c < &loadcmds[nloadcmds])
1335       {
1336         if (c->mapend > c->mapstart
1337             /* Map the segment contents from the file.  */
1338             && (__mmap ((void *) (l->l_addr + c->mapstart),
1339                         c->mapend - c->mapstart, c->prot,
1340                         MAP_FIXED|MAP_COPY|MAP_FILE,
1341                         fd, c->mapoff)
1342                 == MAP_FAILED))
1343           goto map_error;
1344
1345       postmap:
1346         if (c->prot & PROT_EXEC)
1347           l->l_text_end = l->l_addr + c->mapend;
1348
1349         if (l->l_phdr == 0
1350             && c->mapoff <= header->e_phoff
1351             && ((size_t) (c->mapend - c->mapstart + c->mapoff)
1352                 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
1353           /* Found the program header in this segment.  */
1354           l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff);
1355
1356         if (c->allocend > c->dataend)
1357           {
1358             /* Extra zero pages should appear at the end of this segment,
1359                after the data mapped from the file.   */
1360             ElfW(Addr) zero, zeroend, zeropage;
1361
1362             zero = l->l_addr + c->dataend;
1363             zeroend = l->l_addr + c->allocend;
1364             zeropage = ((zero + GLRO(dl_pagesize) - 1)
1365                         & ~(GLRO(dl_pagesize) - 1));
1366
1367             if (zeroend < zeropage)
1368               /* All the extra data is in the last page of the segment.
1369                  We can just zero it.  */
1370               zeropage = zeroend;
1371
1372             if (zeropage > zero)
1373               {
1374                 /* Zero the final part of the last page of the segment.  */
1375                 if (__builtin_expect ((c->prot & PROT_WRITE) == 0, 0))
1376                   {
1377                     /* Dag nab it.  */
1378                     if (__mprotect ((caddr_t) (zero
1379                                                & ~(GLRO(dl_pagesize) - 1)),
1380                                     GLRO(dl_pagesize), c->prot|PROT_WRITE) < 0)
1381                       {
1382                         errstring = N_("cannot change memory protections");
1383                         goto call_lose_errno;
1384                       }
1385                   }
1386                 memset ((void *) zero, '\0', zeropage - zero);
1387                 if (__builtin_expect ((c->prot & PROT_WRITE) == 0, 0))
1388                   __mprotect ((caddr_t) (zero & ~(GLRO(dl_pagesize) - 1)),
1389                               GLRO(dl_pagesize), c->prot);
1390               }
1391
1392             if (zeroend > zeropage)
1393               {
1394                 /* Map the remaining zero pages in from the zero fill FD.  */
1395                 caddr_t mapat;
1396                 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
1397                                 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
1398                                 -1, 0);
1399                 if (__builtin_expect (mapat == MAP_FAILED, 0))
1400                   {
1401                     errstring = N_("cannot map zero-fill pages");
1402                     goto call_lose_errno;
1403                   }
1404               }
1405           }
1406
1407         ++c;
1408       }
1409   }
1410
1411   if (l->l_ld == 0)
1412     {
1413       if (__builtin_expect (type == ET_DYN, 0))
1414         {
1415           errstring = N_("object file has no dynamic section");
1416           goto call_lose;
1417         }
1418     }
1419   else
1420     l->l_ld = (ElfW(Dyn) *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1421
1422   elf_get_dynamic_info (l, NULL);
1423
1424   /* Make sure we are not dlopen'ing an object that has the
1425      DF_1_NOOPEN flag set.  */
1426   if (__builtin_expect (l->l_flags_1 & DF_1_NOOPEN, 0)
1427       && (mode & __RTLD_DLOPEN))
1428     {
1429       /* We are not supposed to load this object.  Free all resources.  */
1430       __munmap ((void *) l->l_map_start, l->l_map_end - l->l_map_start);
1431
1432       if (!l->l_libname->dont_free)
1433         free (l->l_libname);
1434
1435       if (l->l_phdr_allocated)
1436         free ((void *) l->l_phdr);
1437
1438       errstring = N_("shared object cannot be dlopen()ed");
1439       goto call_lose;
1440     }
1441
1442   if (l->l_phdr == NULL)
1443     {
1444       /* The program header is not contained in any of the segments.
1445          We have to allocate memory ourself and copy it over from out
1446          temporary place.  */
1447       ElfW(Phdr) *newp = (ElfW(Phdr) *) malloc (header->e_phnum
1448                                                 * sizeof (ElfW(Phdr)));
1449       if (newp == NULL)
1450         {
1451           errstring = N_("cannot allocate memory for program header");
1452           goto call_lose_errno;
1453         }
1454
1455       l->l_phdr = memcpy (newp, phdr,
1456                           (header->e_phnum * sizeof (ElfW(Phdr))));
1457       l->l_phdr_allocated = 1;
1458     }
1459   else
1460     /* Adjust the PT_PHDR value by the runtime load address.  */
1461     l->l_phdr = (ElfW(Phdr) *) ((ElfW(Addr)) l->l_phdr + l->l_addr);
1462
1463   if (__builtin_expect ((stack_flags &~ GL(dl_stack_flags)) & PF_X, 0))
1464     {
1465       if (__builtin_expect (__check_caller (RETURN_ADDRESS (0), allow_ldso),
1466                             0) != 0)
1467         {
1468           errstring = N_("invalid caller");
1469           goto call_lose;
1470         }
1471
1472       /* The stack is presently not executable, but this module
1473          requires that it be executable.  We must change the
1474          protection of the variable which contains the flags used in
1475          the mprotect calls.  */
1476 #ifdef SHARED
1477       if ((mode & (__RTLD_DLOPEN | __RTLD_AUDIT)) == __RTLD_DLOPEN)
1478         {
1479           const uintptr_t p = (uintptr_t) &__stack_prot & -GLRO(dl_pagesize);
1480           const size_t s = (uintptr_t) (&__stack_prot + 1) - p;
1481
1482           struct link_map *const m = &GL(dl_rtld_map);
1483           const uintptr_t relro_end = ((m->l_addr + m->l_relro_addr
1484                                         + m->l_relro_size)
1485                                        & -GLRO(dl_pagesize));
1486           if (__builtin_expect (p + s <= relro_end, 1))
1487             {
1488               /* The variable lies in the region protected by RELRO.  */
1489               __mprotect ((void *) p, s, PROT_READ|PROT_WRITE);
1490               __stack_prot |= PROT_READ|PROT_WRITE|PROT_EXEC;
1491               __mprotect ((void *) p, s, PROT_READ);
1492             }
1493           else
1494             __stack_prot |= PROT_READ|PROT_WRITE|PROT_EXEC;
1495         }
1496       else
1497 #endif
1498         __stack_prot |= PROT_READ|PROT_WRITE|PROT_EXEC;
1499
1500 #ifdef check_consistency
1501       check_consistency ();
1502 #endif
1503
1504       errval = (*GL(dl_make_stack_executable_hook)) (stack_endp);
1505       if (errval)
1506         {
1507           errstring = N_("\
1508 cannot enable executable stack as shared object requires");
1509           goto call_lose;
1510         }
1511     }
1512
1513   /* Adjust the address of the TLS initialization image.  */
1514   if (l->l_tls_initimage != NULL)
1515     l->l_tls_initimage = (char *) l->l_tls_initimage + l->l_addr;
1516
1517   /* We are done mapping in the file.  We no longer need the descriptor.  */
1518   if (__builtin_expect (__close (fd) != 0, 0))
1519     {
1520       errstring = N_("cannot close file descriptor");
1521       goto call_lose_errno;
1522     }
1523   /* Signal that we closed the file.  */
1524   fd = -1;
1525
1526   if (l->l_type == lt_library && type == ET_EXEC)
1527     l->l_type = lt_executable;
1528
1529   l->l_entry += l->l_addr;
1530
1531   if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
1532     _dl_debug_printf ("\
1533   dynamic: 0x%0*lx  base: 0x%0*lx   size: 0x%0*Zx\n\
1534     entry: 0x%0*lx  phdr: 0x%0*lx  phnum:   %*u\n\n",
1535                            (int) sizeof (void *) * 2,
1536                            (unsigned long int) l->l_ld,
1537                            (int) sizeof (void *) * 2,
1538                            (unsigned long int) l->l_addr,
1539                            (int) sizeof (void *) * 2, maplength,
1540                            (int) sizeof (void *) * 2,
1541                            (unsigned long int) l->l_entry,
1542                            (int) sizeof (void *) * 2,
1543                            (unsigned long int) l->l_phdr,
1544                            (int) sizeof (void *) * 2, l->l_phnum);
1545
1546   /* Set up the symbol hash table.  */
1547   _dl_setup_hash (l);
1548
1549   /* If this object has DT_SYMBOLIC set modify now its scope.  We don't
1550      have to do this for the main map.  */
1551   if ((mode & RTLD_DEEPBIND) == 0
1552       && __builtin_expect (l->l_info[DT_SYMBOLIC] != NULL, 0)
1553       && &l->l_searchlist != l->l_scope[0])
1554     {
1555       /* Create an appropriate searchlist.  It contains only this map.
1556          This is the definition of DT_SYMBOLIC in SysVr4.  */
1557       l->l_symbolic_searchlist.r_list[0] = l;
1558       l->l_symbolic_searchlist.r_nlist = 1;
1559
1560       /* Now move the existing entries one back.  */
1561       memmove (&l->l_scope[1], &l->l_scope[0],
1562                (l->l_scope_max - 1) * sizeof (l->l_scope[0]));
1563
1564       /* Now add the new entry.  */
1565       l->l_scope[0] = &l->l_symbolic_searchlist;
1566     }
1567
1568   /* Remember whether this object must be initialized first.  */
1569   if (l->l_flags_1 & DF_1_INITFIRST)
1570     GL(dl_initfirst) = l;
1571
1572   /* Finally the file information.  */
1573   l->l_dev = st.st_dev;
1574   l->l_ino = st.st_ino;
1575
1576   /* When we profile the SONAME might be needed for something else but
1577      loading.  Add it right away.  */
1578   if (__builtin_expect (GLRO(dl_profile) != NULL, 0)
1579       && l->l_info[DT_SONAME] != NULL)
1580     add_name_to_object (l, ((const char *) D_PTR (l, l_info[DT_STRTAB])
1581                             + l->l_info[DT_SONAME]->d_un.d_val));
1582
1583 #ifdef DL_AFTER_LOAD
1584   DL_AFTER_LOAD (l);
1585 #endif
1586
1587   /* Now that the object is fully initialized add it to the object list.  */
1588   _dl_add_to_namespace_list (l, nsid);
1589
1590 #ifdef SHARED
1591   /* Auditing checkpoint: we have a new object.  */
1592   if (__builtin_expect (GLRO(dl_naudit) > 0, 0)
1593       && !GL(dl_ns)[l->l_ns]._ns_loaded->l_auditing)
1594     {
1595       struct audit_ifaces *afct = GLRO(dl_audit);
1596       for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1597         {
1598           if (afct->objopen != NULL)
1599             {
1600               l->l_audit[cnt].bindflags
1601                 = afct->objopen (l, nsid, &l->l_audit[cnt].cookie);
1602
1603               l->l_audit_any_plt |= l->l_audit[cnt].bindflags != 0;
1604             }
1605
1606           afct = afct->next;
1607         }
1608     }
1609 #endif
1610
1611   return l;
1612 }
1613 \f
1614 /* Print search path.  */
1615 static void
1616 print_search_path (struct r_search_path_elem **list,
1617                    const char *what, const char *name)
1618 {
1619   char buf[max_dirnamelen + max_capstrlen];
1620   int first = 1;
1621
1622   _dl_debug_printf (" search path=");
1623
1624   while (*list != NULL && (*list)->what == what) /* Yes, ==.  */
1625     {
1626       char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
1627       size_t cnt;
1628
1629       for (cnt = 0; cnt < ncapstr; ++cnt)
1630         if ((*list)->status[cnt] != nonexisting)
1631           {
1632             char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
1633             if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
1634               cp[0] = '\0';
1635             else
1636               cp[-1] = '\0';
1637
1638             _dl_debug_printf_c (first ? "%s" : ":%s", buf);
1639             first = 0;
1640           }
1641
1642       ++list;
1643     }
1644
1645   if (name != NULL)
1646     _dl_debug_printf_c ("\t\t(%s from file %s)\n", what,
1647                         name[0] ? name : rtld_progname);
1648   else
1649     _dl_debug_printf_c ("\t\t(%s)\n", what);
1650 }
1651 \f
1652 /* Open a file and verify it is an ELF file for this architecture.  We
1653    ignore only ELF files for other architectures.  Non-ELF files and
1654    ELF files with different header information cause fatal errors since
1655    this could mean there is something wrong in the installation and the
1656    user might want to know about this.  */
1657 static int
1658 open_verify (const char *name, struct filebuf *fbp, struct link_map *loader,
1659              int whatcode, bool *found_other_class, bool free_name)
1660 {
1661   /* This is the expected ELF header.  */
1662 #define ELF32_CLASS ELFCLASS32
1663 #define ELF64_CLASS ELFCLASS64
1664 #ifndef VALID_ELF_HEADER
1665 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
1666 # define VALID_ELF_OSABI(osabi)         (osabi == ELFOSABI_SYSV)
1667 # define VALID_ELF_ABIVERSION(osabi,ver) (ver == 0)
1668 #elif defined MORE_ELF_HEADER_DATA
1669   MORE_ELF_HEADER_DATA;
1670 #endif
1671   static const unsigned char expected[EI_NIDENT] =
1672   {
1673     [EI_MAG0] = ELFMAG0,
1674     [EI_MAG1] = ELFMAG1,
1675     [EI_MAG2] = ELFMAG2,
1676     [EI_MAG3] = ELFMAG3,
1677     [EI_CLASS] = ELFW(CLASS),
1678     [EI_DATA] = byteorder,
1679     [EI_VERSION] = EV_CURRENT,
1680     [EI_OSABI] = ELFOSABI_SYSV,
1681     [EI_ABIVERSION] = 0
1682   };
1683   static const struct
1684   {
1685     ElfW(Word) vendorlen;
1686     ElfW(Word) datalen;
1687     ElfW(Word) type;
1688     char vendor[4];
1689   } expected_note = { 4, 16, 1, "GNU" };
1690   /* Initialize it to make the compiler happy.  */
1691   const char *errstring = NULL;
1692   int errval = 0;
1693
1694 #ifdef SHARED
1695   /* Give the auditing libraries a chance.  */
1696   if (__builtin_expect (GLRO(dl_naudit) > 0, 0) && whatcode != 0
1697       && loader->l_auditing == 0)
1698     {
1699       struct audit_ifaces *afct = GLRO(dl_audit);
1700       for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1701         {
1702           if (afct->objsearch != NULL)
1703             {
1704               name = afct->objsearch (name, &loader->l_audit[cnt].cookie,
1705                                       whatcode);
1706               if (name == NULL)
1707                 /* Ignore the path.  */
1708                 return -1;
1709             }
1710
1711           afct = afct->next;
1712         }
1713     }
1714 #endif
1715
1716   /* Open the file.  We always open files read-only.  */
1717   int fd = __open (name, O_RDONLY | O_CLOEXEC);
1718   if (fd != -1)
1719     {
1720       ElfW(Ehdr) *ehdr;
1721       ElfW(Phdr) *phdr, *ph;
1722       ElfW(Word) *abi_note;
1723       unsigned int osversion;
1724       size_t maplength;
1725
1726       /* We successfully openened the file.  Now verify it is a file
1727          we can use.  */
1728       __set_errno (0);
1729       fbp->len = 0;
1730       assert (sizeof (fbp->buf) > sizeof (ElfW(Ehdr)));
1731       /* Read in the header.  */
1732       do
1733         {
1734           ssize_t retlen = __libc_read (fd, fbp->buf + fbp->len,
1735                                         sizeof (fbp->buf) - fbp->len);
1736           if (retlen <= 0)
1737             break;
1738           fbp->len += retlen;
1739         }
1740       while (__builtin_expect (fbp->len < sizeof (ElfW(Ehdr)), 0));
1741
1742       /* This is where the ELF header is loaded.  */
1743       ehdr = (ElfW(Ehdr) *) fbp->buf;
1744
1745       /* Now run the tests.  */
1746       if (__builtin_expect (fbp->len < (ssize_t) sizeof (ElfW(Ehdr)), 0))
1747         {
1748           errval = errno;
1749           errstring = (errval == 0
1750                        ? N_("file too short") : N_("cannot read file data"));
1751         call_lose:
1752           if (free_name)
1753             {
1754               char *realname = (char *) name;
1755               name = strdupa (realname);
1756               free (realname);
1757             }
1758           lose (errval, fd, name, NULL, NULL, errstring, NULL, 0);
1759         }
1760
1761       /* See whether the ELF header is what we expect.  */
1762       if (__builtin_expect (! VALID_ELF_HEADER (ehdr->e_ident, expected,
1763                                                 EI_ABIVERSION)
1764                             || !VALID_ELF_ABIVERSION (ehdr->e_ident[EI_OSABI],
1765                                                       ehdr->e_ident[EI_ABIVERSION])
1766                             || memcmp (&ehdr->e_ident[EI_PAD],
1767                                        &expected[EI_PAD],
1768                                        EI_NIDENT - EI_PAD) != 0,
1769                             0))
1770         {
1771           /* Something is wrong.  */
1772           const Elf32_Word *magp = (const void *) ehdr->e_ident;
1773           if (*magp !=
1774 #if BYTE_ORDER == LITTLE_ENDIAN
1775               ((ELFMAG0 << (EI_MAG0 * 8)) |
1776                (ELFMAG1 << (EI_MAG1 * 8)) |
1777                (ELFMAG2 << (EI_MAG2 * 8)) |
1778                (ELFMAG3 << (EI_MAG3 * 8)))
1779 #else
1780               ((ELFMAG0 << (EI_MAG3 * 8)) |
1781                (ELFMAG1 << (EI_MAG2 * 8)) |
1782                (ELFMAG2 << (EI_MAG1 * 8)) |
1783                (ELFMAG3 << (EI_MAG0 * 8)))
1784 #endif
1785               )
1786             errstring = N_("invalid ELF header");
1787           else if (ehdr->e_ident[EI_CLASS] != ELFW(CLASS))
1788             {
1789               /* This is not a fatal error.  On architectures where
1790                  32-bit and 64-bit binaries can be run this might
1791                  happen.  */
1792               *found_other_class = true;
1793               goto close_and_out;
1794             }
1795           else if (ehdr->e_ident[EI_DATA] != byteorder)
1796             {
1797               if (BYTE_ORDER == BIG_ENDIAN)
1798                 errstring = N_("ELF file data encoding not big-endian");
1799               else
1800                 errstring = N_("ELF file data encoding not little-endian");
1801             }
1802           else if (ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1803             errstring
1804               = N_("ELF file version ident does not match current one");
1805           /* XXX We should be able so set system specific versions which are
1806              allowed here.  */
1807           else if (!VALID_ELF_OSABI (ehdr->e_ident[EI_OSABI]))
1808             errstring = N_("ELF file OS ABI invalid");
1809           else if (!VALID_ELF_ABIVERSION (ehdr->e_ident[EI_OSABI],
1810                                           ehdr->e_ident[EI_ABIVERSION]))
1811             errstring = N_("ELF file ABI version invalid");
1812           else if (memcmp (&ehdr->e_ident[EI_PAD], &expected[EI_PAD],
1813                            EI_NIDENT - EI_PAD) != 0)
1814             errstring = N_("nonzero padding in e_ident");
1815           else
1816             /* Otherwise we don't know what went wrong.  */
1817             errstring = N_("internal error");
1818
1819           goto call_lose;
1820         }
1821
1822       if (__builtin_expect (ehdr->e_version, EV_CURRENT) != EV_CURRENT)
1823         {
1824           errstring = N_("ELF file version does not match current one");
1825           goto call_lose;
1826         }
1827       if (! __builtin_expect (elf_machine_matches_host (ehdr), 1))
1828         goto close_and_out;
1829       else if (__builtin_expect (ehdr->e_type, ET_DYN) != ET_DYN
1830                && __builtin_expect (ehdr->e_type, ET_EXEC) != ET_EXEC)
1831         {
1832           errstring = N_("only ET_DYN and ET_EXEC can be loaded");
1833           goto call_lose;
1834         }
1835       else if (__builtin_expect (ehdr->e_phentsize, sizeof (ElfW(Phdr)))
1836                != sizeof (ElfW(Phdr)))
1837         {
1838           errstring = N_("ELF file's phentsize not the expected size");
1839           goto call_lose;
1840         }
1841
1842       maplength = ehdr->e_phnum * sizeof (ElfW(Phdr));
1843       if (ehdr->e_phoff + maplength <= (size_t) fbp->len)
1844         phdr = (void *) (fbp->buf + ehdr->e_phoff);
1845       else
1846         {
1847           phdr = alloca (maplength);
1848           __lseek (fd, ehdr->e_phoff, SEEK_SET);
1849           if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
1850             {
1851             read_error:
1852               errval = errno;
1853               errstring = N_("cannot read file data");
1854               goto call_lose;
1855             }
1856         }
1857
1858       /* Check .note.ABI-tag if present.  */
1859       for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph)
1860         if (ph->p_type == PT_NOTE && ph->p_filesz >= 32 && ph->p_align >= 4)
1861           {
1862             ElfW(Addr) size = ph->p_filesz;
1863
1864             if (ph->p_offset + size <= (size_t) fbp->len)
1865               abi_note = (void *) (fbp->buf + ph->p_offset);
1866             else
1867               {
1868                 abi_note = alloca (size);
1869                 __lseek (fd, ph->p_offset, SEEK_SET);
1870                 if (__libc_read (fd, (void *) abi_note, size) != size)
1871                   goto read_error;
1872               }
1873
1874             while (memcmp (abi_note, &expected_note, sizeof (expected_note)))
1875               {
1876 #define ROUND(len) (((len) + sizeof (ElfW(Word)) - 1) & -sizeof (ElfW(Word)))
1877                 ElfW(Addr) note_size = 3 * sizeof (ElfW(Word))
1878                                        + ROUND (abi_note[0])
1879                                        + ROUND (abi_note[1]);
1880
1881                 if (size - 32 < note_size)
1882                   {
1883                     size = 0;
1884                     break;
1885                   }
1886                 size -= note_size;
1887                 abi_note = (void *) abi_note + note_size;
1888               }
1889
1890             if (size == 0)
1891               continue;
1892
1893             osversion = (abi_note[5] & 0xff) * 65536
1894                         + (abi_note[6] & 0xff) * 256
1895                         + (abi_note[7] & 0xff);
1896             if (abi_note[4] != __ABI_TAG_OS
1897                 || (GLRO(dl_osversion) && GLRO(dl_osversion) < osversion))
1898               {
1899               close_and_out:
1900                 __close (fd);
1901                 __set_errno (ENOENT);
1902                 fd = -1;
1903               }
1904
1905             break;
1906           }
1907     }
1908
1909   return fd;
1910 }
1911 \f
1912 /* Try to open NAME in one of the directories in *DIRSP.
1913    Return the fd, or -1.  If successful, fill in *REALNAME
1914    with the malloc'd full directory name.  If it turns out
1915    that none of the directories in *DIRSP exists, *DIRSP is
1916    replaced with (void *) -1, and the old value is free()d
1917    if MAY_FREE_DIRS is true.  */
1918
1919 static int
1920 open_path (const char *name, size_t namelen, int secure,
1921            struct r_search_path_struct *sps, char **realname,
1922            struct filebuf *fbp, struct link_map *loader, int whatcode,
1923            bool *found_other_class)
1924 {
1925   struct r_search_path_elem **dirs = sps->dirs;
1926   char *buf;
1927   int fd = -1;
1928   const char *current_what = NULL;
1929   int any = 0;
1930
1931   if (__builtin_expect (dirs == NULL, 0))
1932     /* We're called before _dl_init_paths when loading the main executable
1933        given on the command line when rtld is run directly.  */
1934     return -1;
1935
1936   buf = alloca (max_dirnamelen + max_capstrlen + namelen);
1937   do
1938     {
1939       struct r_search_path_elem *this_dir = *dirs;
1940       size_t buflen = 0;
1941       size_t cnt;
1942       char *edp;
1943       int here_any = 0;
1944       int err;
1945
1946       /* If we are debugging the search for libraries print the path
1947          now if it hasn't happened now.  */
1948       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0)
1949           && current_what != this_dir->what)
1950         {
1951           current_what = this_dir->what;
1952           print_search_path (dirs, current_what, this_dir->where);
1953         }
1954
1955       edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1956       for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1957         {
1958           /* Skip this directory if we know it does not exist.  */
1959           if (this_dir->status[cnt] == nonexisting)
1960             continue;
1961
1962           buflen =
1963             ((char *) __mempcpy (__mempcpy (edp, capstr[cnt].str,
1964                                             capstr[cnt].len),
1965                                  name, namelen)
1966              - buf);
1967
1968           /* Print name we try if this is wanted.  */
1969           if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1970             _dl_debug_printf ("  trying file=%s\n", buf);
1971
1972           fd = open_verify (buf, fbp, loader, whatcode, found_other_class,
1973                             false);
1974           if (this_dir->status[cnt] == unknown)
1975             {
1976               if (fd != -1)
1977                 this_dir->status[cnt] = existing;
1978               /* Do not update the directory information when loading
1979                  auditing code.  We must try to disturb the program as
1980                  little as possible.  */
1981               else if (loader == NULL
1982                        || GL(dl_ns)[loader->l_ns]._ns_loaded->l_auditing == 0)
1983                 {
1984                   /* We failed to open machine dependent library.  Let's
1985                      test whether there is any directory at all.  */
1986                   struct stat64 st;
1987
1988                   buf[buflen - namelen - 1] = '\0';
1989
1990                   if (__xstat64 (_STAT_VER, buf, &st) != 0
1991                       || ! S_ISDIR (st.st_mode))
1992                     /* The directory does not exist or it is no directory.  */
1993                     this_dir->status[cnt] = nonexisting;
1994                   else
1995                     this_dir->status[cnt] = existing;
1996                 }
1997             }
1998
1999           /* Remember whether we found any existing directory.  */
2000           here_any |= this_dir->status[cnt] != nonexisting;
2001
2002           if (fd != -1 && __builtin_expect (secure, 0)
2003               && INTUSE(__libc_enable_secure))
2004             {
2005               /* This is an extra security effort to make sure nobody can
2006                  preload broken shared objects which are in the trusted
2007                  directories and so exploit the bugs.  */
2008               struct stat64 st;
2009
2010               if (__fxstat64 (_STAT_VER, fd, &st) != 0
2011                   || (st.st_mode & S_ISUID) == 0)
2012                 {
2013                   /* The shared object cannot be tested for being SUID
2014                      or this bit is not set.  In this case we must not
2015                      use this object.  */
2016                   __close (fd);
2017                   fd = -1;
2018                   /* We simply ignore the file, signal this by setting
2019                      the error value which would have been set by `open'.  */
2020                   errno = ENOENT;
2021                 }
2022             }
2023         }
2024
2025       if (fd != -1)
2026         {
2027           *realname = (char *) malloc (buflen);
2028           if (*realname != NULL)
2029             {
2030               memcpy (*realname, buf, buflen);
2031               return fd;
2032             }
2033           else
2034             {
2035               /* No memory for the name, we certainly won't be able
2036                  to load and link it.  */
2037               __close (fd);
2038               return -1;
2039             }
2040         }
2041       if (here_any && (err = errno) != ENOENT && err != EACCES)
2042         /* The file exists and is readable, but something went wrong.  */
2043         return -1;
2044
2045       /* Remember whether we found anything.  */
2046       any |= here_any;
2047     }
2048   while (*++dirs != NULL);
2049
2050   /* Remove the whole path if none of the directories exists.  */
2051   if (__builtin_expect (! any, 0))
2052     {
2053       /* Paths which were allocated using the minimal malloc() in ld.so
2054          must not be freed using the general free() in libc.  */
2055       if (sps->malloced)
2056         free (sps->dirs);
2057
2058       /* rtld_search_dirs is attribute_relro, therefore avoid writing
2059          into it.  */
2060       if (sps != &rtld_search_dirs)
2061         sps->dirs = (void *) -1;
2062     }
2063
2064   return -1;
2065 }
2066
2067 /* Map in the shared object file NAME.  */
2068
2069 struct link_map *
2070 internal_function
2071 _dl_map_object (struct link_map *loader, const char *name,
2072                 int type, int trace_mode, int mode, Lmid_t nsid)
2073 {
2074   int fd;
2075   char *realname;
2076   char *name_copy;
2077   struct link_map *l;
2078   struct filebuf fb;
2079
2080   assert (nsid >= 0);
2081   assert (nsid < GL(dl_nns));
2082
2083   /* Look for this name among those already loaded.  */
2084   for (l = GL(dl_ns)[nsid]._ns_loaded; l; l = l->l_next)
2085     {
2086       /* If the requested name matches the soname of a loaded object,
2087          use that object.  Elide this check for names that have not
2088          yet been opened.  */
2089       if (__builtin_expect (l->l_faked, 0) != 0
2090           || __builtin_expect (l->l_removed, 0) != 0)
2091         continue;
2092       if (!_dl_name_match_p (name, l))
2093         {
2094           const char *soname;
2095
2096           if (__builtin_expect (l->l_soname_added, 1)
2097               || l->l_info[DT_SONAME] == NULL)
2098             continue;
2099
2100           soname = ((const char *) D_PTR (l, l_info[DT_STRTAB])
2101                     + l->l_info[DT_SONAME]->d_un.d_val);
2102           if (strcmp (name, soname) != 0)
2103             continue;
2104
2105           /* We have a match on a new name -- cache it.  */
2106           add_name_to_object (l, soname);
2107           l->l_soname_added = 1;
2108         }
2109
2110       /* We have a match.  */
2111       return l;
2112     }
2113
2114   /* Display information if we are debugging.  */
2115   if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0)
2116       && loader != NULL)
2117     _dl_debug_printf ((mode & __RTLD_CALLMAP) == 0
2118                       ? "\nfile=%s [%lu];  needed by %s [%lu]\n"
2119                       : "\nfile=%s [%lu];  dynamically loaded by %s [%lu]\n",
2120                       name, nsid, loader->l_name[0]
2121                       ? loader->l_name : rtld_progname, loader->l_ns);
2122
2123 #ifdef SHARED
2124   /* Give the auditing libraries a chance to change the name before we
2125      try anything.  */
2126   if (__builtin_expect (GLRO(dl_naudit) > 0, 0)
2127       && (loader == NULL || loader->l_auditing == 0))
2128     {
2129       struct audit_ifaces *afct = GLRO(dl_audit);
2130       for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2131         {
2132           if (afct->objsearch != NULL)
2133             {
2134               name = afct->objsearch (name, &loader->l_audit[cnt].cookie,
2135                                       LA_SER_ORIG);
2136               if (name == NULL)
2137                 {
2138                   /* Do not try anything further.  */
2139                   fd = -1;
2140                   goto no_file;
2141                 }
2142             }
2143
2144           afct = afct->next;
2145         }
2146     }
2147 #endif
2148
2149   /* Will be true if we found a DSO which is of the other ELF class.  */
2150   bool found_other_class = false;
2151
2152   if (strchr (name, '/') == NULL)
2153     {
2154       /* Search for NAME in several places.  */
2155
2156       size_t namelen = strlen (name) + 1;
2157
2158       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2159         _dl_debug_printf ("find library=%s [%lu]; searching\n", name, nsid);
2160
2161       fd = -1;
2162
2163       /* When the object has the RUNPATH information we don't use any
2164          RPATHs.  */
2165       if (loader == NULL || loader->l_info[DT_RUNPATH] == NULL)
2166         {
2167           /* This is the executable's map (if there is one).  Make sure that
2168              we do not look at it twice.  */
2169           struct link_map *main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2170           bool did_main_map = false;
2171
2172           /* First try the DT_RPATH of the dependent object that caused NAME
2173              to be loaded.  Then that object's dependent, and on up.  */
2174           for (l = loader; l; l = l->l_loader)
2175             if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2176               {
2177                 fd = open_path (name, namelen, mode & __RTLD_SECURE,
2178                                 &l->l_rpath_dirs,
2179                                 &realname, &fb, loader, LA_SER_RUNPATH,
2180                                 &found_other_class);
2181                 if (fd != -1)
2182                   break;
2183
2184                 did_main_map |= l == main_map;
2185               }
2186
2187           /* If dynamically linked, try the DT_RPATH of the executable
2188              itself.  NB: we do this for lookups in any namespace.  */
2189           if (fd == -1 && !did_main_map
2190               && main_map != NULL && main_map->l_type != lt_loaded
2191               && cache_rpath (main_map, &main_map->l_rpath_dirs, DT_RPATH,
2192                               "RPATH"))
2193             fd = open_path (name, namelen, mode & __RTLD_SECURE,
2194                             &main_map->l_rpath_dirs,
2195                             &realname, &fb, loader ?: main_map, LA_SER_RUNPATH,
2196                             &found_other_class);
2197         }
2198
2199       /* Try the LD_LIBRARY_PATH environment variable.  */
2200       if (fd == -1 && env_path_list.dirs != (void *) -1)
2201         fd = open_path (name, namelen, mode & __RTLD_SECURE, &env_path_list,
2202                         &realname, &fb,
2203                         loader ?: GL(dl_ns)[LM_ID_BASE]._ns_loaded,
2204                         LA_SER_LIBPATH, &found_other_class);
2205
2206       /* Look at the RUNPATH information for this binary.  */
2207       if (fd == -1 && loader != NULL
2208           && cache_rpath (loader, &loader->l_runpath_dirs,
2209                           DT_RUNPATH, "RUNPATH"))
2210         fd = open_path (name, namelen, mode & __RTLD_SECURE,
2211                         &loader->l_runpath_dirs, &realname, &fb, loader,
2212                         LA_SER_RUNPATH, &found_other_class);
2213
2214 #ifdef USE_LDCONFIG
2215       if (fd == -1
2216           && (__builtin_expect (! (mode & __RTLD_SECURE), 1)
2217               || ! INTUSE(__libc_enable_secure))
2218           && __builtin_expect (GLRO(dl_inhibit_cache) == 0, 1))
2219         {
2220           /* Check the list of libraries in the file /etc/ld.so.cache,
2221              for compatibility with Linux's ldconfig program.  */
2222           const char *cached = _dl_load_cache_lookup (name);
2223
2224           if (cached != NULL)
2225             {
2226 # ifdef SHARED
2227               // XXX Correct to unconditionally default to namespace 0?
2228               l = (loader
2229                    ?: GL(dl_ns)[LM_ID_BASE]._ns_loaded
2230                    ?: &GL(dl_rtld_map));
2231 # else
2232               l = loader;
2233 # endif
2234
2235               /* If the loader has the DF_1_NODEFLIB flag set we must not
2236                  use a cache entry from any of these directories.  */
2237               if (
2238 # ifndef SHARED
2239                   /* 'l' is always != NULL for dynamically linked objects.  */
2240                   l != NULL &&
2241 # endif
2242                   __builtin_expect (l->l_flags_1 & DF_1_NODEFLIB, 0))
2243                 {
2244                   const char *dirp = system_dirs;
2245                   unsigned int cnt = 0;
2246
2247                   do
2248                     {
2249                       if (memcmp (cached, dirp, system_dirs_len[cnt]) == 0)
2250                         {
2251                           /* The prefix matches.  Don't use the entry.  */
2252                           cached = NULL;
2253                           break;
2254                         }
2255
2256                       dirp += system_dirs_len[cnt] + 1;
2257                       ++cnt;
2258                     }
2259                   while (cnt < nsystem_dirs_len);
2260                 }
2261
2262               if (cached != NULL)
2263                 {
2264                   fd = open_verify (cached,
2265                                     &fb, loader ?: GL(dl_ns)[nsid]._ns_loaded,
2266                                     LA_SER_CONFIG, &found_other_class, false);
2267                   if (__builtin_expect (fd != -1, 1))
2268                     {
2269                       realname = local_strdup (cached);
2270                       if (realname == NULL)
2271                         {
2272                           __close (fd);
2273                           fd = -1;
2274                         }
2275                     }
2276                 }
2277             }
2278         }
2279 #endif
2280
2281       /* Finally, try the default path.  */
2282       if (fd == -1
2283           && ((l = loader ?: GL(dl_ns)[nsid]._ns_loaded) == NULL
2284               || __builtin_expect (!(l->l_flags_1 & DF_1_NODEFLIB), 1))
2285           && rtld_search_dirs.dirs != (void *) -1)
2286         fd = open_path (name, namelen, mode & __RTLD_SECURE, &rtld_search_dirs,
2287                         &realname, &fb, l, LA_SER_DEFAULT, &found_other_class);
2288
2289       /* Add another newline when we are tracing the library loading.  */
2290       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2291         _dl_debug_printf ("\n");
2292     }
2293   else
2294     {
2295       /* The path may contain dynamic string tokens.  */
2296       realname = (loader
2297                   ? expand_dynamic_string_token (loader, name, 0)
2298                   : local_strdup (name));
2299       if (realname == NULL)
2300         fd = -1;
2301       else
2302         {
2303           fd = open_verify (realname, &fb,
2304                             loader ?: GL(dl_ns)[nsid]._ns_loaded, 0,
2305                             &found_other_class, true);
2306           if (__builtin_expect (fd, 0) == -1)
2307             free (realname);
2308         }
2309     }
2310
2311 #ifdef SHARED
2312  no_file:
2313 #endif
2314   /* In case the LOADER information has only been provided to get to
2315      the appropriate RUNPATH/RPATH information we do not need it
2316      anymore.  */
2317   if (mode & __RTLD_CALLMAP)
2318     loader = NULL;
2319
2320   if (__builtin_expect (fd, 0) == -1)
2321     {
2322       if (trace_mode
2323           && __builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK, 0) == 0)
2324         {
2325           /* We haven't found an appropriate library.  But since we
2326              are only interested in the list of libraries this isn't
2327              so severe.  Fake an entry with all the information we
2328              have.  */
2329           static const Elf_Symndx dummy_bucket = STN_UNDEF;
2330
2331           /* Allocate a new object map.  */
2332           if ((name_copy = local_strdup (name)) == NULL
2333               || (l = _dl_new_object (name_copy, name, type, loader,
2334                                       mode, nsid)) == NULL)
2335             {
2336               free (name_copy);
2337               _dl_signal_error (ENOMEM, name, NULL,
2338                                 N_("cannot create shared object descriptor"));
2339             }
2340           /* Signal that this is a faked entry.  */
2341           l->l_faked = 1;
2342           /* Since the descriptor is initialized with zero we do not
2343              have do this here.
2344           l->l_reserved = 0; */
2345           l->l_buckets = &dummy_bucket;
2346           l->l_nbuckets = 1;
2347           l->l_relocated = 1;
2348
2349           /* Enter the object in the object list.  */
2350           _dl_add_to_namespace_list (l, nsid);
2351
2352           return l;
2353         }
2354       else if (found_other_class)
2355         _dl_signal_error (0, name, NULL,
2356                           ELFW(CLASS) == ELFCLASS32
2357                           ? N_("wrong ELF class: ELFCLASS64")
2358                           : N_("wrong ELF class: ELFCLASS32"));
2359       else
2360         _dl_signal_error (errno, name, NULL,
2361                           N_("cannot open shared object file"));
2362     }
2363
2364   void *stack_end = __libc_stack_end;
2365   return _dl_map_object_from_fd (name, fd, &fb, realname, loader, type, mode,
2366                                  &stack_end, nsid);
2367 }
2368
2369
2370 void
2371 internal_function
2372 _dl_rtld_di_serinfo (struct link_map *loader, Dl_serinfo *si, bool counting)
2373 {
2374   if (counting)
2375     {
2376       si->dls_cnt = 0;
2377       si->dls_size = 0;
2378     }
2379
2380   unsigned int idx = 0;
2381   char *allocptr = (char *) &si->dls_serpath[si->dls_cnt];
2382   void add_path (const struct r_search_path_struct *sps, unsigned int flags)
2383 # define add_path(sps, flags) add_path(sps, 0) /* XXX */
2384     {
2385       if (sps->dirs != (void *) -1)
2386         {
2387           struct r_search_path_elem **dirs = sps->dirs;
2388           do
2389             {
2390               const struct r_search_path_elem *const r = *dirs++;
2391               if (counting)
2392                 {
2393                   si->dls_cnt++;
2394                   si->dls_size += MAX (2, r->dirnamelen);
2395                 }
2396               else
2397                 {
2398                   Dl_serpath *const sp = &si->dls_serpath[idx++];
2399                   sp->dls_name = allocptr;
2400                   if (r->dirnamelen < 2)
2401                     *allocptr++ = r->dirnamelen ? '/' : '.';
2402                   else
2403                     allocptr = __mempcpy (allocptr,
2404                                           r->dirname, r->dirnamelen - 1);
2405                   *allocptr++ = '\0';
2406                   sp->dls_flags = flags;
2407                 }
2408             }
2409           while (*dirs != NULL);
2410         }
2411     }
2412
2413   /* When the object has the RUNPATH information we don't use any RPATHs.  */
2414   if (loader->l_info[DT_RUNPATH] == NULL)
2415     {
2416       /* First try the DT_RPATH of the dependent object that caused NAME
2417          to be loaded.  Then that object's dependent, and on up.  */
2418
2419       struct link_map *l = loader;
2420       do
2421         {
2422           if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2423             add_path (&l->l_rpath_dirs, XXX_RPATH);
2424           l = l->l_loader;
2425         }
2426       while (l != NULL);
2427
2428       /* If dynamically linked, try the DT_RPATH of the executable itself.  */
2429       if (loader->l_ns == LM_ID_BASE)
2430         {
2431           l = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2432           if (l != NULL && l->l_type != lt_loaded && l != loader)
2433             if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2434               add_path (&l->l_rpath_dirs, XXX_RPATH);
2435         }
2436     }
2437
2438   /* Try the LD_LIBRARY_PATH environment variable.  */
2439   add_path (&env_path_list, XXX_ENV);
2440
2441   /* Look at the RUNPATH information for this binary.  */
2442   if (cache_rpath (loader, &loader->l_runpath_dirs, DT_RUNPATH, "RUNPATH"))
2443     add_path (&loader->l_runpath_dirs, XXX_RUNPATH);
2444
2445   /* XXX
2446      Here is where ld.so.cache gets checked, but we don't have
2447      a way to indicate that in the results for Dl_serinfo.  */
2448
2449   /* Finally, try the default path.  */
2450   if (!(loader->l_flags_1 & DF_1_NODEFLIB))
2451     add_path (&rtld_search_dirs, XXX_default);
2452
2453   if (counting)
2454     /* Count the struct size before the string area, which we didn't
2455        know before we completed dls_cnt.  */
2456     si->dls_size += (char *) &si->dls_serpath[si->dls_cnt] - (char *) si;
2457 }