AArch64: Optimize memcmp
[glibc.git] / elf / dl-load.c
blobbf8957e73c32021a6c5d33d12b8024bbc3b76619
1 /* Map in a shared object's segments from the file.
2 Copyright (C) 1995-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU 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.
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.
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 <https://www.gnu.org/licenses/>. */
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 <gnu/lib-names.h>
35 /* Type for the buffer we put the ELF header and hopefully the program
36 header. This buffer does not really have to be too large. In most
37 cases the program header follows the ELF header directly. If this
38 is not the case all bets are off and we can make the header
39 arbitrarily large and still won't get it read. This means the only
40 question is how large are the ELF and program header combined. The
41 ELF header 32-bit files is 52 bytes long and in 64-bit files is 64
42 bytes long. Each program header entry is again 32 and 56 bytes
43 long respectively. I.e., even with a file which has 10 program
44 header entries we only have to read 372B/624B respectively. Add to
45 this a bit of margin for program notes and reading 512B and 832B
46 for 32-bit and 64-bit files respecitvely is enough. If this
47 heuristic should really fail for some file the code in
48 `_dl_map_object_from_fd' knows how to recover. */
49 struct filebuf
51 ssize_t len;
52 #if __WORDSIZE == 32
53 # define FILEBUF_SIZE 512
54 #else
55 # define FILEBUF_SIZE 832
56 #endif
57 char buf[FILEBUF_SIZE] __attribute__ ((aligned (__alignof (ElfW(Ehdr)))));
60 #include "dynamic-link.h"
61 #include "get-dynamic-info.h"
62 #include <abi-tag.h>
63 #include <stackinfo.h>
64 #include <sysdep.h>
65 #include <stap-probe.h>
66 #include <libc-pointer-arith.h>
67 #include <array_length.h>
69 #include <dl-dst.h>
70 #include <dl-load.h>
71 #include <dl-map-segments.h>
72 #include <dl-unmap-segments.h>
73 #include <dl-machine-reject-phdr.h>
74 #include <dl-sysdep-open.h>
75 #include <dl-prop.h>
76 #include <not-cancel.h>
78 #include <endian.h>
79 #if BYTE_ORDER == BIG_ENDIAN
80 # define byteorder ELFDATA2MSB
81 #elif BYTE_ORDER == LITTLE_ENDIAN
82 # define byteorder ELFDATA2LSB
83 #else
84 # error "Unknown BYTE_ORDER " BYTE_ORDER
85 # define byteorder ELFDATANONE
86 #endif
88 #define STRING(x) __STRING (x)
91 int __stack_prot attribute_hidden attribute_relro
92 #if _STACK_GROWS_DOWN && defined PROT_GROWSDOWN
93 = PROT_GROWSDOWN;
94 #elif _STACK_GROWS_UP && defined PROT_GROWSUP
95 = PROT_GROWSUP;
96 #else
97 = 0;
98 #endif
101 /* This is the decomposed LD_LIBRARY_PATH search path. */
102 struct r_search_path_struct __rtld_env_path_list attribute_relro;
104 /* List of the hardware capabilities we might end up using. */
105 #ifdef SHARED
106 static const struct r_strlenpair *capstr attribute_relro;
107 static size_t ncapstr attribute_relro;
108 static size_t max_capstrlen attribute_relro;
109 #else
110 enum { ncapstr = 1, max_capstrlen = 0 };
111 #endif
114 /* Get the generated information about the trusted directories. Use
115 an array of concatenated strings to avoid relocations. See
116 gen-trusted-dirs.awk. */
117 #include "trusted-dirs.h"
119 static const char system_dirs[] = SYSTEM_DIRS;
120 static const size_t system_dirs_len[] =
122 SYSTEM_DIRS_LEN
124 #define nsystem_dirs_len array_length (system_dirs_len)
126 static bool
127 is_trusted_path_normalize (const char *path, size_t len)
129 if (len == 0)
130 return false;
132 char *npath = (char *) alloca (len + 2);
133 char *wnp = npath;
134 while (*path != '\0')
136 if (path[0] == '/')
138 if (path[1] == '.')
140 if (path[2] == '.' && (path[3] == '/' || path[3] == '\0'))
142 while (wnp > npath && *--wnp != '/')
144 path += 3;
145 continue;
147 else if (path[2] == '/' || path[2] == '\0')
149 path += 2;
150 continue;
154 if (wnp > npath && wnp[-1] == '/')
156 ++path;
157 continue;
161 *wnp++ = *path++;
164 if (wnp == npath || wnp[-1] != '/')
165 *wnp++ = '/';
167 const char *trun = system_dirs;
169 for (size_t idx = 0; idx < nsystem_dirs_len; ++idx)
171 if (wnp - npath >= system_dirs_len[idx]
172 && memcmp (trun, npath, system_dirs_len[idx]) == 0)
173 /* Found it. */
174 return true;
176 trun += system_dirs_len[idx] + 1;
179 return false;
182 /* Given a substring starting at INPUT, just after the DST '$' start
183 token, determine if INPUT contains DST token REF, following the
184 ELF gABI rules for DSTs:
186 * Longest possible sequence using the rules (greedy).
188 * Must start with a $ (enforced by caller).
190 * Must follow $ with one underscore or ASCII [A-Za-z] (caller
191 follows these rules for REF) or '{' (start curly quoted name).
193 * Must follow first two characters with zero or more [A-Za-z0-9_]
194 (enforced by caller) or '}' (end curly quoted name).
196 If the sequence is a DST matching REF then the length of the DST
197 (excluding the $ sign but including curly braces, if any) is
198 returned, otherwise 0. */
199 static size_t
200 is_dst (const char *input, const char *ref)
202 bool is_curly = false;
204 /* Is a ${...} input sequence? */
205 if (input[0] == '{')
207 is_curly = true;
208 ++input;
211 /* Check for matching name, following closing curly brace (if
212 required), or trailing characters which are part of an
213 identifier. */
214 size_t rlen = strlen (ref);
215 if (strncmp (input, ref, rlen) != 0
216 || (is_curly && input[rlen] != '}')
217 || ((input[rlen] >= 'A' && input[rlen] <= 'Z')
218 || (input[rlen] >= 'a' && input[rlen] <= 'z')
219 || (input[rlen] >= '0' && input[rlen] <= '9')
220 || (input[rlen] == '_')))
221 return 0;
223 if (is_curly)
224 /* Count the two curly braces. */
225 return rlen + 2;
226 else
227 return rlen;
230 /* INPUT should be the start of a path e.g DT_RPATH or name e.g.
231 DT_NEEDED. The return value is the number of known DSTs found. We
232 count all known DSTs regardless of __libc_enable_secure; the caller
233 is responsible for enforcing the security of the substitution rules
234 (usually _dl_dst_substitute). */
235 size_t
236 _dl_dst_count (const char *input)
238 size_t cnt = 0;
240 input = strchr (input, '$');
242 /* Most likely there is no DST. */
243 if (__glibc_likely (input == NULL))
244 return 0;
248 size_t len;
250 ++input;
251 /* All DSTs must follow ELF gABI rules, see is_dst (). */
252 if ((len = is_dst (input, "ORIGIN")) != 0
253 || (len = is_dst (input, "PLATFORM")) != 0
254 || (len = is_dst (input, "LIB")) != 0)
255 ++cnt;
257 /* There may be more than one DST in the input. */
258 input = strchr (input + len, '$');
260 while (input != NULL);
262 return cnt;
265 /* Process INPUT for DSTs and store in RESULT using the information
266 from link map L to resolve the DSTs. This function only handles one
267 path at a time and does not handle colon-separated path lists (see
268 fillin_rpath ()). Lastly the size of result in bytes should be at
269 least equal to the value returned by DL_DST_REQUIRED. Note that it
270 is possible for a DT_NEEDED, DT_AUXILIARY, and DT_FILTER entries to
271 have colons, but we treat those as literal colons here, not as path
272 list delimeters. */
273 char *
274 _dl_dst_substitute (struct link_map *l, const char *input, char *result)
276 /* Copy character-by-character from input into the working pointer
277 looking for any DSTs. We track the start of input and if we are
278 going to check for trusted paths, all of which are part of $ORIGIN
279 handling in SUID/SGID cases (see below). In some cases, like when
280 a DST cannot be replaced, we may set result to an empty string and
281 return. */
282 char *wp = result;
283 const char *start = input;
284 bool check_for_trusted = false;
288 if (__glibc_unlikely (*input == '$'))
290 const char *repl = NULL;
291 size_t len;
293 ++input;
294 if ((len = is_dst (input, "ORIGIN")) != 0)
296 /* For SUID/GUID programs we normally ignore the path with
297 $ORIGIN in DT_RUNPATH, or DT_RPATH. However, there is
298 one exception to this rule, and it is:
300 * $ORIGIN appears as the first path element, and is
301 the only string in the path or is immediately
302 followed by a path separator and the rest of the
303 path,
305 and ...
307 * The path is rooted in a trusted directory.
309 This exception allows such programs to reference
310 shared libraries in subdirectories of trusted
311 directories. The use case is one of general
312 organization and deployment flexibility.
313 Trusted directories are usually such paths as "/lib64"
314 or "/usr/lib64", and the usual RPATHs take the form of
315 [$ORIGIN/../$LIB/somedir]. */
316 if (__glibc_unlikely (__libc_enable_secure)
317 && !(input == start + 1
318 && (input[len] == '\0' || input[len] == '/')))
319 repl = (const char *) -1;
320 else
321 repl = l->l_origin;
323 check_for_trusted = (__libc_enable_secure
324 && l->l_type == lt_executable);
326 else if ((len = is_dst (input, "PLATFORM")) != 0)
327 repl = GLRO(dl_platform);
328 else if ((len = is_dst (input, "LIB")) != 0)
329 repl = DL_DST_LIB;
331 if (repl != NULL && repl != (const char *) -1)
333 wp = __stpcpy (wp, repl);
334 input += len;
336 else if (len != 0)
338 /* We found a valid DST that we know about, but we could
339 not find a replacement value for it, therefore we
340 cannot use this path and discard it. */
341 *result = '\0';
342 return result;
344 else
345 /* No DST we recognize. */
346 *wp++ = '$';
348 else
350 *wp++ = *input++;
353 while (*input != '\0');
355 /* In SUID/SGID programs, after $ORIGIN expansion the normalized
356 path must be rooted in one of the trusted directories. The $LIB
357 and $PLATFORM DST cannot in any way be manipulated by the caller
358 because they are fixed values that are set by the dynamic loader
359 and therefore any paths using just $LIB or $PLATFORM need not be
360 checked for trust, the authors of the binaries themselves are
361 trusted to have designed this correctly. Only $ORIGIN is tested in
362 this way because it may be manipulated in some ways with hard
363 links. */
364 if (__glibc_unlikely (check_for_trusted)
365 && !is_trusted_path_normalize (result, wp - result))
367 *result = '\0';
368 return result;
371 *wp = '\0';
373 return result;
377 /* Return a malloc allocated copy of INPUT with all recognized DSTs
378 replaced. On some platforms it might not be possible to determine the
379 path from which the object belonging to the map is loaded. In this
380 case the path containing the DST is left out. On error NULL
381 is returned. */
382 static char *
383 expand_dynamic_string_token (struct link_map *l, const char *input)
385 /* We make two runs over the string. First we determine how large the
386 resulting string is and then we copy it over. Since this is no
387 frequently executed operation we are looking here not for performance
388 but rather for code size. */
389 size_t cnt;
390 size_t total;
391 char *result;
393 /* Determine the number of DSTs. */
394 cnt = _dl_dst_count (input);
396 /* If we do not have to replace anything simply copy the string. */
397 if (__glibc_likely (cnt == 0))
398 return __strdup (input);
400 /* Determine the length of the substituted string. */
401 total = DL_DST_REQUIRED (l, input, strlen (input), cnt);
403 /* Allocate the necessary memory. */
404 result = (char *) malloc (total + 1);
405 if (result == NULL)
406 return NULL;
408 return _dl_dst_substitute (l, input, result);
412 /* Add `name' to the list of names for a particular shared object.
413 `name' is expected to have been allocated with malloc and will
414 be freed if the shared object already has this name.
415 Returns false if the object already had this name. */
416 static void
417 add_name_to_object (struct link_map *l, const char *name)
419 struct libname_list *lnp, *lastp;
420 struct libname_list *newname;
421 size_t name_len;
423 lastp = NULL;
424 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
425 if (strcmp (name, lnp->name) == 0)
426 return;
428 name_len = strlen (name) + 1;
429 newname = (struct libname_list *) malloc (sizeof *newname + name_len);
430 if (newname == NULL)
432 /* No more memory. */
433 _dl_signal_error (ENOMEM, name, NULL, N_("cannot allocate name record"));
434 return;
436 /* The object should have a libname set from _dl_new_object. */
437 assert (lastp != NULL);
439 newname->name = memcpy (newname + 1, name, name_len);
440 newname->next = NULL;
441 newname->dont_free = 0;
442 /* CONCURRENCY NOTES:
444 Make sure the initialization of newname happens before its address is
445 read from the lastp->next store below.
447 GL(dl_load_lock) is held here (and by other writers, e.g. dlclose), so
448 readers of libname_list->next (e.g. _dl_check_caller or the reads above)
449 can use that for synchronization, however the read in _dl_name_match_p
450 may be executed without holding the lock during _dl_runtime_resolve
451 (i.e. lazy symbol resolution when a function of library l is called).
453 The release MO store below synchronizes with the acquire MO load in
454 _dl_name_match_p. Other writes need to synchronize with that load too,
455 however those happen either early when the process is single threaded
456 (dl_main) or when the library is unloaded (dlclose) and the user has to
457 synchronize library calls with unloading. */
458 atomic_store_release (&lastp->next, newname);
461 /* Standard search directories. */
462 struct r_search_path_struct __rtld_search_dirs attribute_relro;
464 static size_t max_dirnamelen;
466 static struct r_search_path_elem **
467 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
468 const char *what, const char *where, struct link_map *l)
470 char *cp;
471 size_t nelems = 0;
473 while ((cp = __strsep (&rpath, sep)) != NULL)
475 struct r_search_path_elem *dirp;
476 char *to_free = NULL;
477 size_t len = 0;
479 /* `strsep' can pass an empty string. */
480 if (*cp != '\0')
482 to_free = cp = expand_dynamic_string_token (l, cp);
484 /* expand_dynamic_string_token can return NULL in case of empty
485 path or memory allocation failure. */
486 if (cp == NULL)
487 continue;
489 /* Compute the length after dynamic string token expansion and
490 ignore empty paths. */
491 len = strlen (cp);
492 if (len == 0)
494 free (to_free);
495 continue;
498 /* Remove trailing slashes (except for "/"). */
499 while (len > 1 && cp[len - 1] == '/')
500 --len;
502 /* Now add one if there is none so far. */
503 if (len > 0 && cp[len - 1] != '/')
504 cp[len++] = '/';
507 /* See if this directory is already known. */
508 for (dirp = GL(dl_all_dirs); dirp != NULL; dirp = dirp->next)
509 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
510 break;
512 if (dirp != NULL)
514 /* It is available, see whether it's on our own list. */
515 size_t cnt;
516 for (cnt = 0; cnt < nelems; ++cnt)
517 if (result[cnt] == dirp)
518 break;
520 if (cnt == nelems)
521 result[nelems++] = dirp;
523 else
525 size_t cnt;
526 enum r_dir_status init_val;
527 size_t where_len = where ? strlen (where) + 1 : 0;
529 /* It's a new directory. Create an entry and add it. */
530 dirp = (struct r_search_path_elem *)
531 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status)
532 + where_len + len + 1);
533 if (dirp == NULL)
534 _dl_signal_error (ENOMEM, NULL, NULL,
535 N_("cannot create cache for search path"));
537 dirp->dirname = ((char *) dirp + sizeof (*dirp)
538 + ncapstr * sizeof (enum r_dir_status));
539 *((char *) __mempcpy ((char *) dirp->dirname, cp, len)) = '\0';
540 dirp->dirnamelen = len;
542 if (len > max_dirnamelen)
543 max_dirnamelen = len;
545 /* We have to make sure all the relative directories are
546 never ignored. The current directory might change and
547 all our saved information would be void. */
548 init_val = cp[0] != '/' ? existing : unknown;
549 for (cnt = 0; cnt < ncapstr; ++cnt)
550 dirp->status[cnt] = init_val;
552 dirp->what = what;
553 if (__glibc_likely (where != NULL))
554 dirp->where = memcpy ((char *) dirp + sizeof (*dirp) + len + 1
555 + (ncapstr * sizeof (enum r_dir_status)),
556 where, where_len);
557 else
558 dirp->where = NULL;
560 dirp->next = GL(dl_all_dirs);
561 GL(dl_all_dirs) = dirp;
563 /* Put it in the result array. */
564 result[nelems++] = dirp;
566 free (to_free);
569 /* Terminate the array. */
570 result[nelems] = NULL;
572 return result;
576 static bool
577 decompose_rpath (struct r_search_path_struct *sps,
578 const char *rpath, struct link_map *l, const char *what)
580 /* Make a copy we can work with. */
581 const char *where = l->l_name;
582 char *cp;
583 struct r_search_path_elem **result;
584 size_t nelems;
585 /* Initialize to please the compiler. */
586 const char *errstring = NULL;
588 /* First see whether we must forget the RUNPATH and RPATH from this
589 object. */
590 if (__glibc_unlikely (GLRO(dl_inhibit_rpath) != NULL)
591 && !__libc_enable_secure)
593 const char *inhp = GLRO(dl_inhibit_rpath);
597 const char *wp = where;
599 while (*inhp == *wp && *wp != '\0')
601 ++inhp;
602 ++wp;
605 if (*wp == '\0' && (*inhp == '\0' || *inhp == ':'))
607 /* This object is on the list of objects for which the
608 RUNPATH and RPATH must not be used. */
609 sps->dirs = (void *) -1;
610 return false;
613 while (*inhp != '\0')
614 if (*inhp++ == ':')
615 break;
617 while (*inhp != '\0');
620 /* Ignore empty rpaths. */
621 if (*rpath == '\0')
623 sps->dirs = (struct r_search_path_elem **) -1;
624 return false;
627 /* Make a writable copy. */
628 char *copy = __strdup (rpath);
629 if (copy == NULL)
631 errstring = N_("cannot create RUNPATH/RPATH copy");
632 goto signal_error;
635 /* Count the number of necessary elements in the result array. */
636 nelems = 0;
637 for (cp = copy; *cp != '\0'; ++cp)
638 if (*cp == ':')
639 ++nelems;
641 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
642 number of necessary entries. */
643 result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
644 * sizeof (*result));
645 if (result == NULL)
647 free (copy);
648 errstring = N_("cannot create cache for search path");
649 signal_error:
650 _dl_signal_error (ENOMEM, NULL, NULL, errstring);
653 fillin_rpath (copy, result, ":", what, where, l);
655 /* Free the copied RPATH string. `fillin_rpath' make own copies if
656 necessary. */
657 free (copy);
659 /* There is no path after expansion. */
660 if (result[0] == NULL)
662 free (result);
663 sps->dirs = (struct r_search_path_elem **) -1;
664 return false;
667 sps->dirs = result;
668 /* The caller will change this value if we haven't used a real malloc. */
669 sps->malloced = 1;
670 return true;
673 /* Make sure cached path information is stored in *SP
674 and return true if there are any paths to search there. */
675 static bool
676 cache_rpath (struct link_map *l,
677 struct r_search_path_struct *sp,
678 int tag,
679 const char *what)
681 if (sp->dirs == (void *) -1)
682 return false;
684 if (sp->dirs != NULL)
685 return true;
687 if (l->l_info[tag] == NULL)
689 /* There is no path. */
690 sp->dirs = (void *) -1;
691 return false;
694 /* Make sure the cache information is available. */
695 return decompose_rpath (sp, (const char *) (D_PTR (l, l_info[DT_STRTAB])
696 + l->l_info[tag]->d_un.d_val),
697 l, what);
701 void
702 _dl_init_paths (const char *llp, const char *source,
703 const char *glibc_hwcaps_prepend,
704 const char *glibc_hwcaps_mask)
706 size_t idx;
707 const char *strp;
708 struct r_search_path_elem *pelem, **aelem;
709 size_t round_size;
710 struct link_map __attribute__ ((unused)) *l = NULL;
711 /* Initialize to please the compiler. */
712 const char *errstring = NULL;
714 /* Fill in the information about the application's RPATH and the
715 directories addressed by the LD_LIBRARY_PATH environment variable. */
717 #ifdef SHARED
718 /* Get the capabilities. */
719 capstr = _dl_important_hwcaps (glibc_hwcaps_prepend, glibc_hwcaps_mask,
720 &ncapstr, &max_capstrlen);
721 #endif
723 /* First set up the rest of the default search directory entries. */
724 aelem = __rtld_search_dirs.dirs = (struct r_search_path_elem **)
725 malloc ((nsystem_dirs_len + 1) * sizeof (struct r_search_path_elem *));
726 if (__rtld_search_dirs.dirs == NULL)
728 errstring = N_("cannot create search path array");
729 signal_error:
730 _dl_signal_error (ENOMEM, NULL, NULL, errstring);
733 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
734 + ncapstr * sizeof (enum r_dir_status))
735 / sizeof (struct r_search_path_elem));
737 __rtld_search_dirs.dirs[0]
738 = malloc (nsystem_dirs_len * round_size
739 * sizeof (*__rtld_search_dirs.dirs[0]));
740 if (__rtld_search_dirs.dirs[0] == NULL)
742 errstring = N_("cannot create cache for search path");
743 goto signal_error;
746 __rtld_search_dirs.malloced = 0;
747 pelem = GL(dl_all_dirs) = __rtld_search_dirs.dirs[0];
748 strp = system_dirs;
749 idx = 0;
753 size_t cnt;
755 *aelem++ = pelem;
757 pelem->what = "system search path";
758 pelem->where = NULL;
760 pelem->dirname = strp;
761 pelem->dirnamelen = system_dirs_len[idx];
762 strp += system_dirs_len[idx] + 1;
764 /* System paths must be absolute. */
765 assert (pelem->dirname[0] == '/');
766 for (cnt = 0; cnt < ncapstr; ++cnt)
767 pelem->status[cnt] = unknown;
769 pelem->next = (++idx == nsystem_dirs_len ? NULL : (pelem + round_size));
771 pelem += round_size;
773 while (idx < nsystem_dirs_len);
775 max_dirnamelen = SYSTEM_DIRS_MAX_LEN;
776 *aelem = NULL;
778 /* This points to the map of the main object. If there is no main
779 object (e.g., under --help, use the dynamic loader itself as a
780 stand-in. */
781 l = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
782 #ifdef SHARED
783 if (l == NULL)
784 l = &GL (dl_rtld_map);
785 #endif
786 assert (l->l_type != lt_loaded);
788 if (l->l_info[DT_RUNPATH])
790 /* Allocate room for the search path and fill in information
791 from RUNPATH. */
792 decompose_rpath (&l->l_runpath_dirs,
793 (const void *) (D_PTR (l, l_info[DT_STRTAB])
794 + l->l_info[DT_RUNPATH]->d_un.d_val),
795 l, "RUNPATH");
796 /* During rtld init the memory is allocated by the stub malloc,
797 prevent any attempt to free it by the normal malloc. */
798 l->l_runpath_dirs.malloced = 0;
800 /* The RPATH is ignored. */
801 l->l_rpath_dirs.dirs = (void *) -1;
803 else
805 l->l_runpath_dirs.dirs = (void *) -1;
807 if (l->l_info[DT_RPATH])
809 /* Allocate room for the search path and fill in information
810 from RPATH. */
811 decompose_rpath (&l->l_rpath_dirs,
812 (const void *) (D_PTR (l, l_info[DT_STRTAB])
813 + l->l_info[DT_RPATH]->d_un.d_val),
814 l, "RPATH");
815 /* During rtld init the memory is allocated by the stub
816 malloc, prevent any attempt to free it by the normal
817 malloc. */
818 l->l_rpath_dirs.malloced = 0;
820 else
821 l->l_rpath_dirs.dirs = (void *) -1;
824 if (llp != NULL && *llp != '\0')
826 char *llp_tmp = strdupa (llp);
828 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
829 elements it has. */
830 size_t nllp = 1;
831 for (const char *cp = llp_tmp; *cp != '\0'; ++cp)
832 if (*cp == ':' || *cp == ';')
833 ++nllp;
835 __rtld_env_path_list.dirs = (struct r_search_path_elem **)
836 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
837 if (__rtld_env_path_list.dirs == NULL)
839 errstring = N_("cannot create cache for search path");
840 goto signal_error;
843 (void) fillin_rpath (llp_tmp, __rtld_env_path_list.dirs, ":;",
844 source, NULL, l);
846 if (__rtld_env_path_list.dirs[0] == NULL)
848 free (__rtld_env_path_list.dirs);
849 __rtld_env_path_list.dirs = (void *) -1;
852 __rtld_env_path_list.malloced = 0;
854 else
855 __rtld_env_path_list.dirs = (void *) -1;
859 /* Process PT_GNU_PROPERTY program header PH in module L after
860 PT_LOAD segments are mapped. Only one NT_GNU_PROPERTY_TYPE_0
861 note is handled which contains processor specific properties.
862 FD is -1 for the kernel mapped main executable otherwise it is
863 the fd used for loading module L. */
865 void
866 _dl_process_pt_gnu_property (struct link_map *l, int fd, const ElfW(Phdr) *ph)
868 const ElfW(Nhdr) *note = (const void *) (ph->p_vaddr + l->l_addr);
869 const ElfW(Addr) size = ph->p_memsz;
870 const ElfW(Addr) align = ph->p_align;
872 /* The NT_GNU_PROPERTY_TYPE_0 note must be aligned to 4 bytes in
873 32-bit objects and to 8 bytes in 64-bit objects. Skip notes
874 with incorrect alignment. */
875 if (align != (__ELF_NATIVE_CLASS / 8))
876 return;
878 const ElfW(Addr) start = (ElfW(Addr)) note;
879 unsigned int last_type = 0;
881 while ((ElfW(Addr)) (note + 1) - start < size)
883 /* Find the NT_GNU_PROPERTY_TYPE_0 note. */
884 if (note->n_namesz == 4
885 && note->n_type == NT_GNU_PROPERTY_TYPE_0
886 && memcmp (note + 1, "GNU", 4) == 0)
888 /* Check for invalid property. */
889 if (note->n_descsz < 8
890 || (note->n_descsz % sizeof (ElfW(Addr))) != 0)
891 return;
893 /* Start and end of property array. */
894 unsigned char *ptr = (unsigned char *) (note + 1) + 4;
895 unsigned char *ptr_end = ptr + note->n_descsz;
899 unsigned int type = *(unsigned int *) ptr;
900 unsigned int datasz = *(unsigned int *) (ptr + 4);
902 /* Property type must be in ascending order. */
903 if (type < last_type)
904 return;
906 ptr += 8;
907 if ((ptr + datasz) > ptr_end)
908 return;
910 last_type = type;
912 /* Target specific property processing. */
913 if (_dl_process_gnu_property (l, fd, type, datasz, ptr) == 0)
914 return;
916 /* Check the next property item. */
917 ptr += ALIGN_UP (datasz, sizeof (ElfW(Addr)));
919 while ((ptr_end - ptr) >= 8);
921 /* Only handle one NT_GNU_PROPERTY_TYPE_0. */
922 return;
925 note = ((const void *) note
926 + ELF_NOTE_NEXT_OFFSET (note->n_namesz, note->n_descsz,
927 align));
932 /* Map in the shared object NAME, actually located in REALNAME, and already
933 opened on FD. */
935 #ifndef EXTERNAL_MAP_FROM_FD
936 static
937 #endif
938 struct link_map *
939 _dl_map_object_from_fd (const char *name, const char *origname, int fd,
940 struct filebuf *fbp, char *realname,
941 struct link_map *loader, int l_type, int mode,
942 void **stack_endp, Lmid_t nsid)
944 struct link_map *l = NULL;
945 const ElfW(Ehdr) *header;
946 const ElfW(Phdr) *phdr;
947 const ElfW(Phdr) *ph;
948 size_t maplength;
949 int type;
950 /* Initialize to keep the compiler happy. */
951 const char *errstring = NULL;
952 int errval = 0;
953 struct r_debug *r = _dl_debug_update (nsid);
954 bool make_consistent = false;
956 /* Get file information. To match the kernel behavior, do not fill
957 in this information for the executable in case of an explicit
958 loader invocation. */
959 struct r_file_id id;
960 if (mode & __RTLD_OPENEXEC)
962 assert (nsid == LM_ID_BASE);
963 memset (&id, 0, sizeof (id));
965 else
967 if (__glibc_unlikely (!_dl_get_file_id (fd, &id)))
969 errstring = N_("cannot stat shared object");
970 lose_errno:
971 errval = errno;
972 lose:
973 /* The file might already be closed. */
974 if (fd != -1)
975 __close_nocancel (fd);
976 if (l != NULL && l->l_map_start != 0)
977 _dl_unmap_segments (l);
978 if (l != NULL && l->l_origin != (char *) -1l)
979 free ((char *) l->l_origin);
980 if (l != NULL && !l->l_libname->dont_free)
981 free (l->l_libname);
982 if (l != NULL && l->l_phdr_allocated)
983 free ((void *) l->l_phdr);
984 free (l);
985 free (realname);
987 if (make_consistent && r != NULL)
989 r->r_state = RT_CONSISTENT;
990 _dl_debug_state ();
991 LIBC_PROBE (map_failed, 2, nsid, r);
994 _dl_signal_error (errval, name, NULL, errstring);
997 /* Look again to see if the real name matched another already loaded. */
998 for (l = GL(dl_ns)[nsid]._ns_loaded; l != NULL; l = l->l_next)
999 if (!l->l_removed && _dl_file_id_match_p (&l->l_file_id, &id))
1001 /* The object is already loaded.
1002 Just bump its reference count and return it. */
1003 __close_nocancel (fd);
1005 /* If the name is not in the list of names for this object add
1006 it. */
1007 free (realname);
1008 add_name_to_object (l, name);
1010 return l;
1014 #ifdef SHARED
1015 /* When loading into a namespace other than the base one we must
1016 avoid loading ld.so since there can only be one copy. Ever. */
1017 if (__glibc_unlikely (nsid != LM_ID_BASE)
1018 && (_dl_file_id_match_p (&id, &GL(dl_rtld_map).l_file_id)
1019 || _dl_name_match_p (name, &GL(dl_rtld_map))))
1021 /* This is indeed ld.so. Create a new link_map which refers to
1022 the real one for almost everything. */
1023 l = _dl_new_object (realname, name, l_type, loader, mode, nsid);
1024 if (l == NULL)
1025 goto fail_new;
1027 /* Refer to the real descriptor. */
1028 l->l_real = &GL(dl_rtld_map);
1030 /* Copy l_addr and l_ld to avoid a GDB warning with dlmopen(). */
1031 l->l_addr = l->l_real->l_addr;
1032 l->l_ld = l->l_real->l_ld;
1034 /* No need to bump the refcount of the real object, ld.so will
1035 never be unloaded. */
1036 __close_nocancel (fd);
1038 /* Add the map for the mirrored object to the object list. */
1039 _dl_add_to_namespace_list (l, nsid);
1041 return l;
1043 #endif
1045 if (mode & RTLD_NOLOAD)
1047 /* We are not supposed to load the object unless it is already
1048 loaded. So return now. */
1049 free (realname);
1050 __close_nocancel (fd);
1051 return NULL;
1054 /* Print debugging message. */
1055 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_FILES))
1056 _dl_debug_printf ("file=%s [%lu]; generating link map\n", name, nsid);
1058 /* This is the ELF header. We read it in `open_verify'. */
1059 header = (void *) fbp->buf;
1061 /* Enter the new object in the list of loaded objects. */
1062 l = _dl_new_object (realname, name, l_type, loader, mode, nsid);
1063 if (__glibc_unlikely (l == NULL))
1065 #ifdef SHARED
1066 fail_new:
1067 #endif
1068 errstring = N_("cannot create shared object descriptor");
1069 goto lose_errno;
1072 /* Extract the remaining details we need from the ELF header
1073 and then read in the program header table. */
1074 l->l_entry = header->e_entry;
1075 type = header->e_type;
1076 l->l_phnum = header->e_phnum;
1078 maplength = header->e_phnum * sizeof (ElfW(Phdr));
1079 if (header->e_phoff + maplength <= (size_t) fbp->len)
1080 phdr = (void *) (fbp->buf + header->e_phoff);
1081 else
1083 phdr = alloca (maplength);
1084 if ((size_t) __pread64_nocancel (fd, (void *) phdr, maplength,
1085 header->e_phoff) != maplength)
1087 errstring = N_("cannot read file data");
1088 goto lose_errno;
1092 /* On most platforms presume that PT_GNU_STACK is absent and the stack is
1093 * executable. Other platforms default to a nonexecutable stack and don't
1094 * need PT_GNU_STACK to do so. */
1095 uint_fast16_t stack_flags = DEFAULT_STACK_PERMS;
1098 /* Scan the program header table, collecting its load commands. */
1099 struct loadcmd loadcmds[l->l_phnum];
1100 size_t nloadcmds = 0;
1101 bool has_holes = false;
1102 bool empty_dynamic = false;
1104 /* The struct is initialized to zero so this is not necessary:
1105 l->l_ld = 0;
1106 l->l_phdr = 0;
1107 l->l_addr = 0; */
1108 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
1109 switch (ph->p_type)
1111 /* These entries tell us where to find things once the file's
1112 segments are mapped in. We record the addresses it says
1113 verbatim, and later correct for the run-time load address. */
1114 case PT_DYNAMIC:
1115 if (ph->p_filesz == 0)
1116 empty_dynamic = true; /* Usually separate debuginfo. */
1117 else
1119 /* Debuginfo only files from "objcopy --only-keep-debug"
1120 contain a PT_DYNAMIC segment with p_filesz == 0. Skip
1121 such a segment to avoid a crash later. */
1122 l->l_ld = (void *) ph->p_vaddr;
1123 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1124 l->l_ld_readonly = (ph->p_flags & PF_W) == 0;
1126 break;
1128 case PT_PHDR:
1129 l->l_phdr = (void *) ph->p_vaddr;
1130 break;
1132 case PT_LOAD:
1133 /* A load command tells us to map in part of the file.
1134 We record the load commands and process them all later. */
1135 if (__glibc_unlikely ((ph->p_align & (GLRO(dl_pagesize) - 1)) != 0))
1137 errstring = N_("ELF load command alignment not page-aligned");
1138 goto lose;
1140 if (__glibc_unlikely (((ph->p_vaddr - ph->p_offset)
1141 & (ph->p_align - 1)) != 0))
1143 errstring
1144 = N_("ELF load command address/offset not properly aligned");
1145 goto lose;
1148 struct loadcmd *c = &loadcmds[nloadcmds++];
1149 c->mapstart = ALIGN_DOWN (ph->p_vaddr, GLRO(dl_pagesize));
1150 c->mapend = ALIGN_UP (ph->p_vaddr + ph->p_filesz, GLRO(dl_pagesize));
1151 c->dataend = ph->p_vaddr + ph->p_filesz;
1152 c->allocend = ph->p_vaddr + ph->p_memsz;
1153 c->mapoff = ALIGN_DOWN (ph->p_offset, GLRO(dl_pagesize));
1155 /* Determine whether there is a gap between the last segment
1156 and this one. */
1157 if (nloadcmds > 1 && c[-1].mapend != c->mapstart)
1158 has_holes = true;
1160 /* Optimize a common case. */
1161 #if (PF_R | PF_W | PF_X) == 7 && (PROT_READ | PROT_WRITE | PROT_EXEC) == 7
1162 c->prot = (PF_TO_PROT
1163 >> ((ph->p_flags & (PF_R | PF_W | PF_X)) * 4)) & 0xf;
1164 #else
1165 c->prot = 0;
1166 if (ph->p_flags & PF_R)
1167 c->prot |= PROT_READ;
1168 if (ph->p_flags & PF_W)
1169 c->prot |= PROT_WRITE;
1170 if (ph->p_flags & PF_X)
1171 c->prot |= PROT_EXEC;
1172 #endif
1173 break;
1175 case PT_TLS:
1176 if (ph->p_memsz == 0)
1177 /* Nothing to do for an empty segment. */
1178 break;
1180 l->l_tls_blocksize = ph->p_memsz;
1181 l->l_tls_align = ph->p_align;
1182 if (ph->p_align == 0)
1183 l->l_tls_firstbyte_offset = 0;
1184 else
1185 l->l_tls_firstbyte_offset = ph->p_vaddr & (ph->p_align - 1);
1186 l->l_tls_initimage_size = ph->p_filesz;
1187 /* Since we don't know the load address yet only store the
1188 offset. We will adjust it later. */
1189 l->l_tls_initimage = (void *) ph->p_vaddr;
1191 /* l->l_tls_modid is assigned below, once there is no
1192 possibility for failure. */
1194 if (l->l_type != lt_library
1195 && GL(dl_tls_dtv_slotinfo_list) == NULL)
1197 #ifdef SHARED
1198 /* We are loading the executable itself when the dynamic
1199 linker was executed directly. The setup will happen
1200 later. */
1201 assert (l->l_prev == NULL || (mode & __RTLD_AUDIT) != 0);
1202 #else
1203 assert (false && "TLS not initialized in static application");
1204 #endif
1206 break;
1208 case PT_GNU_STACK:
1209 stack_flags = ph->p_flags;
1210 break;
1212 case PT_GNU_RELRO:
1213 l->l_relro_addr = ph->p_vaddr;
1214 l->l_relro_size = ph->p_memsz;
1215 break;
1218 if (__glibc_unlikely (nloadcmds == 0))
1220 /* This only happens for a bogus object that will be caught with
1221 another error below. But we don't want to go through the
1222 calculations below using NLOADCMDS - 1. */
1223 errstring = N_("object file has no loadable segments");
1224 goto lose;
1227 /* dlopen of an executable is not valid because it is not possible
1228 to perform proper relocations, handle static TLS, or run the
1229 ELF constructors. For PIE, the check needs the dynamic
1230 section, so there is another check below. */
1231 if (__glibc_unlikely (type != ET_DYN)
1232 && __glibc_unlikely ((mode & __RTLD_OPENEXEC) == 0))
1234 /* This object is loaded at a fixed address. This must never
1235 happen for objects loaded with dlopen. */
1236 errstring = N_("cannot dynamically load executable");
1237 goto lose;
1240 /* This check recognizes most separate debuginfo files. */
1241 if (__glibc_unlikely ((l->l_ld == 0 && type == ET_DYN) || empty_dynamic))
1243 errstring = N_("object file has no dynamic section");
1244 goto lose;
1247 /* Length of the sections to be loaded. */
1248 maplength = loadcmds[nloadcmds - 1].allocend - loadcmds[0].mapstart;
1250 /* Now process the load commands and map segments into memory.
1251 This is responsible for filling in:
1252 l_map_start, l_map_end, l_addr, l_contiguous, l_text_end, l_phdr
1254 errstring = _dl_map_segments (l, fd, header, type, loadcmds, nloadcmds,
1255 maplength, has_holes, loader);
1256 if (__glibc_unlikely (errstring != NULL))
1258 /* Mappings can be in an inconsistent state: avoid unmap. */
1259 l->l_map_start = l->l_map_end = 0;
1260 goto lose;
1264 if (l->l_ld != 0)
1265 l->l_ld = (ElfW(Dyn) *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1267 elf_get_dynamic_info (l, false, false);
1269 /* Make sure we are not dlopen'ing an object that has the
1270 DF_1_NOOPEN flag set, or a PIE object. */
1271 if ((__glibc_unlikely (l->l_flags_1 & DF_1_NOOPEN)
1272 && (mode & __RTLD_DLOPEN))
1273 || (__glibc_unlikely (l->l_flags_1 & DF_1_PIE)
1274 && __glibc_unlikely ((mode & __RTLD_OPENEXEC) == 0)))
1276 if (l->l_flags_1 & DF_1_PIE)
1277 errstring
1278 = N_("cannot dynamically load position-independent executable");
1279 else
1280 errstring = N_("shared object cannot be dlopen()ed");
1281 goto lose;
1284 if (l->l_phdr == NULL)
1286 /* The program header is not contained in any of the segments.
1287 We have to allocate memory ourself and copy it over from out
1288 temporary place. */
1289 ElfW(Phdr) *newp = (ElfW(Phdr) *) malloc (header->e_phnum
1290 * sizeof (ElfW(Phdr)));
1291 if (newp == NULL)
1293 errstring = N_("cannot allocate memory for program header");
1294 goto lose_errno;
1297 l->l_phdr = memcpy (newp, phdr,
1298 (header->e_phnum * sizeof (ElfW(Phdr))));
1299 l->l_phdr_allocated = 1;
1301 else
1302 /* Adjust the PT_PHDR value by the runtime load address. */
1303 l->l_phdr = (ElfW(Phdr) *) ((ElfW(Addr)) l->l_phdr + l->l_addr);
1305 if (__glibc_unlikely ((stack_flags &~ GL(dl_stack_flags)) & PF_X))
1307 /* The stack is presently not executable, but this module
1308 requires that it be executable. We must change the
1309 protection of the variable which contains the flags used in
1310 the mprotect calls. */
1311 #ifdef SHARED
1312 if ((mode & (__RTLD_DLOPEN | __RTLD_AUDIT)) == __RTLD_DLOPEN)
1314 const uintptr_t p = (uintptr_t) &__stack_prot & -GLRO(dl_pagesize);
1315 const size_t s = (uintptr_t) (&__stack_prot + 1) - p;
1317 struct link_map *const m = &GL(dl_rtld_map);
1318 const uintptr_t relro_end = ((m->l_addr + m->l_relro_addr
1319 + m->l_relro_size)
1320 & -GLRO(dl_pagesize));
1321 if (__glibc_likely (p + s <= relro_end))
1323 /* The variable lies in the region protected by RELRO. */
1324 if (__mprotect ((void *) p, s, PROT_READ|PROT_WRITE) < 0)
1326 errstring = N_("cannot change memory protections");
1327 goto lose_errno;
1329 __stack_prot |= PROT_READ|PROT_WRITE|PROT_EXEC;
1330 __mprotect ((void *) p, s, PROT_READ);
1332 else
1333 __stack_prot |= PROT_READ|PROT_WRITE|PROT_EXEC;
1335 else
1336 #endif
1337 __stack_prot |= PROT_READ|PROT_WRITE|PROT_EXEC;
1339 #ifdef check_consistency
1340 check_consistency ();
1341 #endif
1343 #if PTHREAD_IN_LIBC
1344 errval = _dl_make_stacks_executable (stack_endp);
1345 #else
1346 errval = (*GL(dl_make_stack_executable_hook)) (stack_endp);
1347 #endif
1348 if (errval)
1350 errstring = N_("\
1351 cannot enable executable stack as shared object requires");
1352 goto lose;
1356 /* Adjust the address of the TLS initialization image. */
1357 if (l->l_tls_initimage != NULL)
1358 l->l_tls_initimage = (char *) l->l_tls_initimage + l->l_addr;
1360 /* Process program headers again after load segments are mapped in
1361 case processing requires accessing those segments. Scan program
1362 headers backward so that PT_NOTE can be skipped if PT_GNU_PROPERTY
1363 exits. */
1364 for (ph = &l->l_phdr[l->l_phnum]; ph != l->l_phdr; --ph)
1365 switch (ph[-1].p_type)
1367 case PT_NOTE:
1368 _dl_process_pt_note (l, fd, &ph[-1]);
1369 break;
1370 case PT_GNU_PROPERTY:
1371 _dl_process_pt_gnu_property (l, fd, &ph[-1]);
1372 break;
1375 /* We are done mapping in the file. We no longer need the descriptor. */
1376 if (__glibc_unlikely (__close_nocancel (fd) != 0))
1378 errstring = N_("cannot close file descriptor");
1379 goto lose_errno;
1381 /* Signal that we closed the file. */
1382 fd = -1;
1384 /* Failures before this point are handled locally via lose.
1385 There are no more failures in this function until return,
1386 to change that the cleanup handling needs to be updated. */
1388 /* If this is ET_EXEC, we should have loaded it as lt_executable. */
1389 assert (type != ET_EXEC || l->l_type == lt_executable);
1391 l->l_entry += l->l_addr;
1393 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_FILES))
1394 _dl_debug_printf ("\
1395 dynamic: 0x%0*lx base: 0x%0*lx size: 0x%0*Zx\n\
1396 entry: 0x%0*lx phdr: 0x%0*lx phnum: %*u\n\n",
1397 (int) sizeof (void *) * 2,
1398 (unsigned long int) l->l_ld,
1399 (int) sizeof (void *) * 2,
1400 (unsigned long int) l->l_addr,
1401 (int) sizeof (void *) * 2, maplength,
1402 (int) sizeof (void *) * 2,
1403 (unsigned long int) l->l_entry,
1404 (int) sizeof (void *) * 2,
1405 (unsigned long int) l->l_phdr,
1406 (int) sizeof (void *) * 2, l->l_phnum);
1408 /* Set up the symbol hash table. */
1409 _dl_setup_hash (l);
1411 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
1412 have to do this for the main map. */
1413 if ((mode & RTLD_DEEPBIND) == 0
1414 && __glibc_unlikely (l->l_info[DT_SYMBOLIC] != NULL)
1415 && &l->l_searchlist != l->l_scope[0])
1417 /* Create an appropriate searchlist. It contains only this map.
1418 This is the definition of DT_SYMBOLIC in SysVr4. */
1419 l->l_symbolic_searchlist.r_list[0] = l;
1420 l->l_symbolic_searchlist.r_nlist = 1;
1422 /* Now move the existing entries one back. */
1423 memmove (&l->l_scope[1], &l->l_scope[0],
1424 (l->l_scope_max - 1) * sizeof (l->l_scope[0]));
1426 /* Now add the new entry. */
1427 l->l_scope[0] = &l->l_symbolic_searchlist;
1430 /* Remember whether this object must be initialized first. */
1431 if (l->l_flags_1 & DF_1_INITFIRST)
1432 GL(dl_initfirst) = l;
1434 /* Finally the file information. */
1435 l->l_file_id = id;
1437 #ifdef SHARED
1438 /* When auditing is used the recorded names might not include the
1439 name by which the DSO is actually known. Add that as well. */
1440 if (__glibc_unlikely (origname != NULL))
1441 add_name_to_object (l, origname);
1442 #else
1443 /* Audit modules only exist when linking is dynamic so ORIGNAME
1444 cannot be non-NULL. */
1445 assert (origname == NULL);
1446 #endif
1448 /* When we profile the SONAME might be needed for something else but
1449 loading. Add it right away. */
1450 if (__glibc_unlikely (GLRO(dl_profile) != NULL)
1451 && l->l_info[DT_SONAME] != NULL)
1452 add_name_to_object (l, ((const char *) D_PTR (l, l_info[DT_STRTAB])
1453 + l->l_info[DT_SONAME]->d_un.d_val));
1455 /* If we have newly loaded libc.so, update the namespace
1456 description. */
1457 if (GL(dl_ns)[nsid].libc_map == NULL
1458 && l->l_info[DT_SONAME] != NULL
1459 && strcmp (((const char *) D_PTR (l, l_info[DT_STRTAB])
1460 + l->l_info[DT_SONAME]->d_un.d_val), LIBC_SO) == 0)
1461 GL(dl_ns)[nsid].libc_map = l;
1463 /* _dl_close can only eventually undo the module ID assignment (via
1464 remove_slotinfo) if this function returns a pointer to a link
1465 map. Therefore, delay this step until all possibilities for
1466 failure have been excluded. */
1467 if (l->l_tls_blocksize > 0
1468 && (__glibc_likely (l->l_type == lt_library)
1469 /* If GL(dl_tls_dtv_slotinfo_list) == NULL, then rtld.c did
1470 not set up TLS data structures, so don't use them now. */
1471 || __glibc_likely (GL(dl_tls_dtv_slotinfo_list) != NULL)))
1472 /* Assign the next available module ID. */
1473 _dl_assign_tls_modid (l);
1475 #ifdef DL_AFTER_LOAD
1476 DL_AFTER_LOAD (l);
1477 #endif
1479 /* Now that the object is fully initialized add it to the object list. */
1480 _dl_add_to_namespace_list (l, nsid);
1482 /* Signal that we are going to add new objects. */
1483 if (r->r_state == RT_CONSISTENT)
1485 #ifdef SHARED
1486 /* Auditing checkpoint: we are going to add new objects. Since this
1487 is called after _dl_add_to_namespace_list the namespace is guaranteed
1488 to not be empty. */
1489 if ((mode & __RTLD_AUDIT) == 0
1490 && __glibc_unlikely (GLRO(dl_naudit) > 0))
1492 struct link_map *head = GL(dl_ns)[nsid]._ns_loaded;
1493 /* Do not call the functions for any auditing object. */
1494 if (head->l_auditing == 0)
1496 struct audit_ifaces *afct = GLRO(dl_audit);
1497 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1499 if (afct->activity != NULL)
1500 afct->activity (&link_map_audit_state (head, cnt)->cookie,
1501 LA_ACT_ADD);
1503 afct = afct->next;
1507 #endif
1509 /* Notify the debugger we have added some objects. We need to
1510 call _dl_debug_initialize in a static program in case dynamic
1511 linking has not been used before. */
1512 r->r_state = RT_ADD;
1513 _dl_debug_state ();
1514 LIBC_PROBE (map_start, 2, nsid, r);
1515 make_consistent = true;
1517 else
1518 assert (r->r_state == RT_ADD);
1520 #ifdef SHARED
1521 /* Auditing checkpoint: we have a new object. */
1522 if (__glibc_unlikely (GLRO(dl_naudit) > 0)
1523 && !GL(dl_ns)[l->l_ns]._ns_loaded->l_auditing)
1525 struct audit_ifaces *afct = GLRO(dl_audit);
1526 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1528 if (afct->objopen != NULL)
1530 struct auditstate *state = link_map_audit_state (l, cnt);
1531 state->bindflags = afct->objopen (l, nsid, &state->cookie);
1532 l->l_audit_any_plt |= state->bindflags != 0;
1535 afct = afct->next;
1538 #endif
1540 return l;
1543 /* Print search path. */
1544 static void
1545 print_search_path (struct r_search_path_elem **list,
1546 const char *what, const char *name)
1548 char buf[max_dirnamelen + max_capstrlen];
1549 int first = 1;
1551 _dl_debug_printf (" search path=");
1553 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
1555 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
1556 size_t cnt;
1558 for (cnt = 0; cnt < ncapstr; ++cnt)
1559 if ((*list)->status[cnt] != nonexisting)
1561 #ifdef SHARED
1562 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
1563 if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
1564 cp[0] = '\0';
1565 else
1566 cp[-1] = '\0';
1567 #else
1568 *endp = '\0';
1569 #endif
1571 _dl_debug_printf_c (first ? "%s" : ":%s", buf);
1572 first = 0;
1575 ++list;
1578 if (name != NULL)
1579 _dl_debug_printf_c ("\t\t(%s from file %s)\n", what,
1580 DSO_FILENAME (name));
1581 else
1582 _dl_debug_printf_c ("\t\t(%s)\n", what);
1585 /* Open a file and verify it is an ELF file for this architecture. We
1586 ignore only ELF files for other architectures. Non-ELF files and
1587 ELF files with different header information cause fatal errors since
1588 this could mean there is something wrong in the installation and the
1589 user might want to know about this.
1591 If FD is not -1, then the file is already open and FD refers to it.
1592 In that case, FD is consumed for both successful and error returns. */
1593 static int
1594 open_verify (const char *name, int fd,
1595 struct filebuf *fbp, struct link_map *loader,
1596 int whatcode, int mode, bool *found_other_class, bool free_name)
1598 /* This is the expected ELF header. */
1599 #define ELF32_CLASS ELFCLASS32
1600 #define ELF64_CLASS ELFCLASS64
1601 #ifndef VALID_ELF_HEADER
1602 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
1603 # define VALID_ELF_OSABI(osabi) (osabi == ELFOSABI_SYSV)
1604 # define VALID_ELF_ABIVERSION(osabi,ver) (ver == 0)
1605 #elif defined MORE_ELF_HEADER_DATA
1606 MORE_ELF_HEADER_DATA;
1607 #endif
1608 static const unsigned char expected[EI_NIDENT] =
1610 [EI_MAG0] = ELFMAG0,
1611 [EI_MAG1] = ELFMAG1,
1612 [EI_MAG2] = ELFMAG2,
1613 [EI_MAG3] = ELFMAG3,
1614 [EI_CLASS] = ELFW(CLASS),
1615 [EI_DATA] = byteorder,
1616 [EI_VERSION] = EV_CURRENT,
1617 [EI_OSABI] = ELFOSABI_SYSV,
1618 [EI_ABIVERSION] = 0
1620 static const struct
1622 ElfW(Word) vendorlen;
1623 ElfW(Word) datalen;
1624 ElfW(Word) type;
1625 char vendor[4];
1626 } expected_note = { 4, 16, 1, "GNU" };
1627 /* Initialize it to make the compiler happy. */
1628 const char *errstring = NULL;
1629 int errval = 0;
1631 #ifdef SHARED
1632 /* Give the auditing libraries a chance. */
1633 if (__glibc_unlikely (GLRO(dl_naudit) > 0) && whatcode != 0
1634 && loader->l_auditing == 0)
1636 const char *original_name = name;
1637 struct audit_ifaces *afct = GLRO(dl_audit);
1638 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1640 if (afct->objsearch != NULL)
1642 struct auditstate *state = link_map_audit_state (loader, cnt);
1643 name = afct->objsearch (name, &state->cookie, whatcode);
1644 if (name == NULL)
1645 /* Ignore the path. */
1646 return -1;
1649 afct = afct->next;
1652 if (fd != -1 && name != original_name && strcmp (name, original_name))
1654 /* An audit library changed what we're supposed to open,
1655 so FD no longer matches it. */
1656 __close_nocancel (fd);
1657 fd = -1;
1660 #endif
1662 if (fd == -1)
1663 /* Open the file. We always open files read-only. */
1664 fd = __open64_nocancel (name, O_RDONLY | O_CLOEXEC);
1666 if (fd != -1)
1668 ElfW(Ehdr) *ehdr;
1669 ElfW(Phdr) *phdr, *ph;
1670 ElfW(Word) *abi_note;
1671 ElfW(Word) *abi_note_malloced = NULL;
1672 unsigned int osversion;
1673 size_t maplength;
1675 /* We successfully opened the file. Now verify it is a file
1676 we can use. */
1677 __set_errno (0);
1678 fbp->len = 0;
1679 assert (sizeof (fbp->buf) > sizeof (ElfW(Ehdr)));
1680 /* Read in the header. */
1683 ssize_t retlen = __read_nocancel (fd, fbp->buf + fbp->len,
1684 sizeof (fbp->buf) - fbp->len);
1685 if (retlen <= 0)
1686 break;
1687 fbp->len += retlen;
1689 while (__glibc_unlikely (fbp->len < sizeof (ElfW(Ehdr))));
1691 /* This is where the ELF header is loaded. */
1692 ehdr = (ElfW(Ehdr) *) fbp->buf;
1694 /* Now run the tests. */
1695 if (__glibc_unlikely (fbp->len < (ssize_t) sizeof (ElfW(Ehdr))))
1697 errval = errno;
1698 errstring = (errval == 0
1699 ? N_("file too short") : N_("cannot read file data"));
1700 lose:
1701 if (free_name)
1703 char *realname = (char *) name;
1704 name = strdupa (realname);
1705 free (realname);
1707 __close_nocancel (fd);
1708 _dl_signal_error (errval, name, NULL, errstring);
1711 /* See whether the ELF header is what we expect. */
1712 if (__glibc_unlikely (! VALID_ELF_HEADER (ehdr->e_ident, expected,
1713 EI_ABIVERSION)
1714 || !VALID_ELF_ABIVERSION (ehdr->e_ident[EI_OSABI],
1715 ehdr->e_ident[EI_ABIVERSION])
1716 || memcmp (&ehdr->e_ident[EI_PAD],
1717 &expected[EI_PAD],
1718 EI_NIDENT - EI_PAD) != 0))
1720 /* Something is wrong. */
1721 const Elf32_Word *magp = (const void *) ehdr->e_ident;
1722 if (*magp !=
1723 #if BYTE_ORDER == LITTLE_ENDIAN
1724 ((ELFMAG0 << (EI_MAG0 * 8))
1725 | (ELFMAG1 << (EI_MAG1 * 8))
1726 | (ELFMAG2 << (EI_MAG2 * 8))
1727 | (ELFMAG3 << (EI_MAG3 * 8)))
1728 #else
1729 ((ELFMAG0 << (EI_MAG3 * 8))
1730 | (ELFMAG1 << (EI_MAG2 * 8))
1731 | (ELFMAG2 << (EI_MAG1 * 8))
1732 | (ELFMAG3 << (EI_MAG0 * 8)))
1733 #endif
1735 errstring = N_("invalid ELF header");
1736 else if (ehdr->e_ident[EI_CLASS] != ELFW(CLASS))
1738 /* This is not a fatal error. On architectures where
1739 32-bit and 64-bit binaries can be run this might
1740 happen. */
1741 *found_other_class = true;
1742 goto close_and_out;
1744 else if (ehdr->e_ident[EI_DATA] != byteorder)
1746 if (BYTE_ORDER == BIG_ENDIAN)
1747 errstring = N_("ELF file data encoding not big-endian");
1748 else
1749 errstring = N_("ELF file data encoding not little-endian");
1751 else if (ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1752 errstring
1753 = N_("ELF file version ident does not match current one");
1754 /* XXX We should be able so set system specific versions which are
1755 allowed here. */
1756 else if (!VALID_ELF_OSABI (ehdr->e_ident[EI_OSABI]))
1757 errstring = N_("ELF file OS ABI invalid");
1758 else if (!VALID_ELF_ABIVERSION (ehdr->e_ident[EI_OSABI],
1759 ehdr->e_ident[EI_ABIVERSION]))
1760 errstring = N_("ELF file ABI version invalid");
1761 else if (memcmp (&ehdr->e_ident[EI_PAD], &expected[EI_PAD],
1762 EI_NIDENT - EI_PAD) != 0)
1763 errstring = N_("nonzero padding in e_ident");
1764 else
1765 /* Otherwise we don't know what went wrong. */
1766 errstring = N_("internal error");
1768 goto lose;
1771 if (__glibc_unlikely (ehdr->e_version != EV_CURRENT))
1773 errstring = N_("ELF file version does not match current one");
1774 goto lose;
1776 if (! __glibc_likely (elf_machine_matches_host (ehdr)))
1777 goto close_and_out;
1778 else if (__glibc_unlikely (ehdr->e_type != ET_DYN
1779 && ehdr->e_type != ET_EXEC))
1781 errstring = N_("only ET_DYN and ET_EXEC can be loaded");
1782 goto lose;
1784 else if (__glibc_unlikely (ehdr->e_phentsize != sizeof (ElfW(Phdr))))
1786 errstring = N_("ELF file's phentsize not the expected size");
1787 goto lose;
1790 maplength = ehdr->e_phnum * sizeof (ElfW(Phdr));
1791 if (ehdr->e_phoff + maplength <= (size_t) fbp->len)
1792 phdr = (void *) (fbp->buf + ehdr->e_phoff);
1793 else
1795 phdr = alloca (maplength);
1796 if ((size_t) __pread64_nocancel (fd, (void *) phdr, maplength,
1797 ehdr->e_phoff) != maplength)
1799 read_error:
1800 errval = errno;
1801 errstring = N_("cannot read file data");
1802 goto lose;
1806 if (__glibc_unlikely (elf_machine_reject_phdr_p
1807 (phdr, ehdr->e_phnum, fbp->buf, fbp->len,
1808 loader, fd)))
1809 goto close_and_out;
1811 /* Check .note.ABI-tag if present. */
1812 for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph)
1813 if (ph->p_type == PT_NOTE && ph->p_filesz >= 32
1814 && (ph->p_align == 4 || ph->p_align == 8))
1816 ElfW(Addr) size = ph->p_filesz;
1818 if (ph->p_offset + size <= (size_t) fbp->len)
1819 abi_note = (void *) (fbp->buf + ph->p_offset);
1820 else
1822 /* Note: __libc_use_alloca is not usable here, because
1823 thread info may not have been set up yet. */
1824 if (size < __MAX_ALLOCA_CUTOFF)
1825 abi_note = alloca (size);
1826 else
1828 /* There could be multiple PT_NOTEs. */
1829 abi_note_malloced = realloc (abi_note_malloced, size);
1830 if (abi_note_malloced == NULL)
1831 goto read_error;
1833 abi_note = abi_note_malloced;
1835 if (__pread64_nocancel (fd, (void *) abi_note, size,
1836 ph->p_offset) != size)
1838 free (abi_note_malloced);
1839 goto read_error;
1843 while (memcmp (abi_note, &expected_note, sizeof (expected_note)))
1845 ElfW(Addr) note_size
1846 = ELF_NOTE_NEXT_OFFSET (abi_note[0], abi_note[1],
1847 ph->p_align);
1849 if (size - 32 < note_size)
1851 size = 0;
1852 break;
1854 size -= note_size;
1855 abi_note = (void *) abi_note + note_size;
1858 if (size == 0)
1859 continue;
1861 osversion = (abi_note[5] & 0xff) * 65536
1862 + (abi_note[6] & 0xff) * 256
1863 + (abi_note[7] & 0xff);
1864 if (abi_note[4] != __ABI_TAG_OS
1865 || (GLRO(dl_osversion) && GLRO(dl_osversion) < osversion))
1867 close_and_out:
1868 __close_nocancel (fd);
1869 __set_errno (ENOENT);
1870 fd = -1;
1873 break;
1875 free (abi_note_malloced);
1878 return fd;
1881 /* Try to open NAME in one of the directories in *DIRSP.
1882 Return the fd, or -1. If successful, fill in *REALNAME
1883 with the malloc'd full directory name. If it turns out
1884 that none of the directories in *DIRSP exists, *DIRSP is
1885 replaced with (void *) -1, and the old value is free()d
1886 if MAY_FREE_DIRS is true. */
1888 static int
1889 open_path (const char *name, size_t namelen, int mode,
1890 struct r_search_path_struct *sps, char **realname,
1891 struct filebuf *fbp, struct link_map *loader, int whatcode,
1892 bool *found_other_class)
1894 struct r_search_path_elem **dirs = sps->dirs;
1895 char *buf;
1896 int fd = -1;
1897 const char *current_what = NULL;
1898 int any = 0;
1900 if (__glibc_unlikely (dirs == NULL))
1901 /* We're called before _dl_init_paths when loading the main executable
1902 given on the command line when rtld is run directly. */
1903 return -1;
1905 buf = alloca (max_dirnamelen + max_capstrlen + namelen);
1908 struct r_search_path_elem *this_dir = *dirs;
1909 size_t buflen = 0;
1910 size_t cnt;
1911 char *edp;
1912 int here_any = 0;
1913 int err;
1915 /* If we are debugging the search for libraries print the path
1916 now if it hasn't happened now. */
1917 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_LIBS)
1918 && current_what != this_dir->what)
1920 current_what = this_dir->what;
1921 print_search_path (dirs, current_what, this_dir->where);
1924 edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1925 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1927 /* Skip this directory if we know it does not exist. */
1928 if (this_dir->status[cnt] == nonexisting)
1929 continue;
1931 #ifdef SHARED
1932 buflen =
1933 ((char *) __mempcpy (__mempcpy (edp, capstr[cnt].str,
1934 capstr[cnt].len),
1935 name, namelen)
1936 - buf);
1937 #else
1938 buflen = (char *) __mempcpy (edp, name, namelen) - buf;
1939 #endif
1941 /* Print name we try if this is wanted. */
1942 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_LIBS))
1943 _dl_debug_printf (" trying file=%s\n", buf);
1945 fd = open_verify (buf, -1, fbp, loader, whatcode, mode,
1946 found_other_class, false);
1947 if (this_dir->status[cnt] == unknown)
1949 if (fd != -1)
1950 this_dir->status[cnt] = existing;
1951 /* Do not update the directory information when loading
1952 auditing code. We must try to disturb the program as
1953 little as possible. */
1954 else if (loader == NULL
1955 || GL(dl_ns)[loader->l_ns]._ns_loaded->l_auditing == 0)
1957 /* We failed to open machine dependent library. Let's
1958 test whether there is any directory at all. */
1959 struct __stat64_t64 st;
1961 buf[buflen - namelen - 1] = '\0';
1963 if (__stat64_time64 (buf, &st) != 0
1964 || ! S_ISDIR (st.st_mode))
1965 /* The directory does not exist or it is no directory. */
1966 this_dir->status[cnt] = nonexisting;
1967 else
1968 this_dir->status[cnt] = existing;
1972 /* Remember whether we found any existing directory. */
1973 here_any |= this_dir->status[cnt] != nonexisting;
1975 if (fd != -1 && __glibc_unlikely (mode & __RTLD_SECURE)
1976 && __libc_enable_secure)
1978 /* This is an extra security effort to make sure nobody can
1979 preload broken shared objects which are in the trusted
1980 directories and so exploit the bugs. */
1981 struct __stat64_t64 st;
1983 if (__fstat64_time64 (fd, &st) != 0
1984 || (st.st_mode & S_ISUID) == 0)
1986 /* The shared object cannot be tested for being SUID
1987 or this bit is not set. In this case we must not
1988 use this object. */
1989 __close_nocancel (fd);
1990 fd = -1;
1991 /* We simply ignore the file, signal this by setting
1992 the error value which would have been set by `open'. */
1993 errno = ENOENT;
1998 if (fd != -1)
2000 *realname = (char *) malloc (buflen);
2001 if (*realname != NULL)
2003 memcpy (*realname, buf, buflen);
2004 return fd;
2006 else
2008 /* No memory for the name, we certainly won't be able
2009 to load and link it. */
2010 __close_nocancel (fd);
2011 return -1;
2014 if (here_any && (err = errno) != ENOENT && err != EACCES)
2015 /* The file exists and is readable, but something went wrong. */
2016 return -1;
2018 /* Remember whether we found anything. */
2019 any |= here_any;
2021 while (*++dirs != NULL);
2023 /* Remove the whole path if none of the directories exists. */
2024 if (__glibc_unlikely (! any))
2026 /* Paths which were allocated using the minimal malloc() in ld.so
2027 must not be freed using the general free() in libc. */
2028 if (sps->malloced)
2029 free (sps->dirs);
2031 /* __rtld_search_dirs and __rtld_env_path_list are
2032 attribute_relro, therefore avoid writing to them. */
2033 if (sps != &__rtld_search_dirs && sps != &__rtld_env_path_list)
2034 sps->dirs = (void *) -1;
2037 return -1;
2040 /* Map in the shared object file NAME. */
2042 struct link_map *
2043 _dl_map_object (struct link_map *loader, const char *name,
2044 int type, int trace_mode, int mode, Lmid_t nsid)
2046 int fd;
2047 const char *origname = NULL;
2048 char *realname;
2049 char *name_copy;
2050 struct link_map *l;
2051 struct filebuf fb;
2053 assert (nsid >= 0);
2054 assert (nsid < GL(dl_nns));
2056 /* Look for this name among those already loaded. */
2057 for (l = GL(dl_ns)[nsid]._ns_loaded; l; l = l->l_next)
2059 /* If the requested name matches the soname of a loaded object,
2060 use that object. Elide this check for names that have not
2061 yet been opened. */
2062 if (__glibc_unlikely ((l->l_faked | l->l_removed) != 0))
2063 continue;
2064 if (!_dl_name_match_p (name, l))
2066 const char *soname;
2068 if (__glibc_likely (l->l_soname_added)
2069 || l->l_info[DT_SONAME] == NULL)
2070 continue;
2072 soname = ((const char *) D_PTR (l, l_info[DT_STRTAB])
2073 + l->l_info[DT_SONAME]->d_un.d_val);
2074 if (strcmp (name, soname) != 0)
2075 continue;
2077 /* We have a match on a new name -- cache it. */
2078 add_name_to_object (l, soname);
2079 l->l_soname_added = 1;
2082 /* We have a match. */
2083 return l;
2086 /* Display information if we are debugging. */
2087 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_FILES)
2088 && loader != NULL)
2089 _dl_debug_printf ((mode & __RTLD_CALLMAP) == 0
2090 ? "\nfile=%s [%lu]; needed by %s [%lu]\n"
2091 : "\nfile=%s [%lu]; dynamically loaded by %s [%lu]\n",
2092 name, nsid, DSO_FILENAME (loader->l_name), loader->l_ns);
2094 #ifdef SHARED
2095 /* Give the auditing libraries a chance to change the name before we
2096 try anything. */
2097 if (__glibc_unlikely (GLRO(dl_naudit) > 0)
2098 && (loader == NULL || loader->l_auditing == 0))
2100 struct audit_ifaces *afct = GLRO(dl_audit);
2101 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2103 if (afct->objsearch != NULL)
2105 const char *before = name;
2106 struct auditstate *state = link_map_audit_state (loader, cnt);
2107 name = afct->objsearch (name, &state->cookie, LA_SER_ORIG);
2108 if (name == NULL)
2110 /* Do not try anything further. */
2111 fd = -1;
2112 goto no_file;
2114 if (before != name && strcmp (before, name) != 0)
2116 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_FILES))
2117 _dl_debug_printf ("audit changed filename %s -> %s\n",
2118 before, name);
2120 if (origname == NULL)
2121 origname = before;
2125 afct = afct->next;
2128 #endif
2130 /* Will be true if we found a DSO which is of the other ELF class. */
2131 bool found_other_class = false;
2133 if (strchr (name, '/') == NULL)
2135 /* Search for NAME in several places. */
2137 size_t namelen = strlen (name) + 1;
2139 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_LIBS))
2140 _dl_debug_printf ("find library=%s [%lu]; searching\n", name, nsid);
2142 fd = -1;
2144 /* When the object has the RUNPATH information we don't use any
2145 RPATHs. */
2146 if (loader == NULL || loader->l_info[DT_RUNPATH] == NULL)
2148 /* This is the executable's map (if there is one). Make sure that
2149 we do not look at it twice. */
2150 struct link_map *main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2151 bool did_main_map = false;
2153 /* First try the DT_RPATH of the dependent object that caused NAME
2154 to be loaded. Then that object's dependent, and on up. */
2155 for (l = loader; l; l = l->l_loader)
2156 if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2158 fd = open_path (name, namelen, mode,
2159 &l->l_rpath_dirs,
2160 &realname, &fb, loader, LA_SER_RUNPATH,
2161 &found_other_class);
2162 if (fd != -1)
2163 break;
2165 did_main_map |= l == main_map;
2168 /* If dynamically linked, try the DT_RPATH of the executable
2169 itself. NB: we do this for lookups in any namespace. */
2170 if (fd == -1 && !did_main_map
2171 && main_map != NULL && main_map->l_type != lt_loaded
2172 && cache_rpath (main_map, &main_map->l_rpath_dirs, DT_RPATH,
2173 "RPATH"))
2174 fd = open_path (name, namelen, mode,
2175 &main_map->l_rpath_dirs,
2176 &realname, &fb, loader ?: main_map, LA_SER_RUNPATH,
2177 &found_other_class);
2180 /* Try the LD_LIBRARY_PATH environment variable. */
2181 if (fd == -1 && __rtld_env_path_list.dirs != (void *) -1)
2182 fd = open_path (name, namelen, mode, &__rtld_env_path_list,
2183 &realname, &fb,
2184 loader ?: GL(dl_ns)[LM_ID_BASE]._ns_loaded,
2185 LA_SER_LIBPATH, &found_other_class);
2187 /* Look at the RUNPATH information for this binary. */
2188 if (fd == -1 && loader != NULL
2189 && cache_rpath (loader, &loader->l_runpath_dirs,
2190 DT_RUNPATH, "RUNPATH"))
2191 fd = open_path (name, namelen, mode,
2192 &loader->l_runpath_dirs, &realname, &fb, loader,
2193 LA_SER_RUNPATH, &found_other_class);
2195 if (fd == -1)
2197 realname = _dl_sysdep_open_object (name, namelen, &fd);
2198 if (realname != NULL)
2200 fd = open_verify (realname, fd,
2201 &fb, loader ?: GL(dl_ns)[nsid]._ns_loaded,
2202 LA_SER_CONFIG, mode, &found_other_class,
2203 false);
2204 if (fd == -1)
2205 free (realname);
2209 #ifdef USE_LDCONFIG
2210 if (fd == -1
2211 && (__glibc_likely ((mode & __RTLD_SECURE) == 0)
2212 || ! __libc_enable_secure)
2213 && __glibc_likely (GLRO(dl_inhibit_cache) == 0))
2215 /* Check the list of libraries in the file /etc/ld.so.cache,
2216 for compatibility with Linux's ldconfig program. */
2217 char *cached = _dl_load_cache_lookup (name);
2219 if (cached != NULL)
2221 // XXX Correct to unconditionally default to namespace 0?
2222 l = (loader
2223 ?: GL(dl_ns)[LM_ID_BASE]._ns_loaded
2224 # ifdef SHARED
2225 ?: &GL(dl_rtld_map)
2226 # endif
2229 /* If the loader has the DF_1_NODEFLIB flag set we must not
2230 use a cache entry from any of these directories. */
2231 if (__glibc_unlikely (l->l_flags_1 & DF_1_NODEFLIB))
2233 const char *dirp = system_dirs;
2234 unsigned int cnt = 0;
2238 if (memcmp (cached, dirp, system_dirs_len[cnt]) == 0)
2240 /* The prefix matches. Don't use the entry. */
2241 free (cached);
2242 cached = NULL;
2243 break;
2246 dirp += system_dirs_len[cnt] + 1;
2247 ++cnt;
2249 while (cnt < nsystem_dirs_len);
2252 if (cached != NULL)
2254 fd = open_verify (cached, -1,
2255 &fb, loader ?: GL(dl_ns)[nsid]._ns_loaded,
2256 LA_SER_CONFIG, mode, &found_other_class,
2257 false);
2258 if (__glibc_likely (fd != -1))
2259 realname = cached;
2260 else
2261 free (cached);
2265 #endif
2267 /* Finally, try the default path. */
2268 if (fd == -1
2269 && ((l = loader ?: GL(dl_ns)[nsid]._ns_loaded) == NULL
2270 || __glibc_likely (!(l->l_flags_1 & DF_1_NODEFLIB)))
2271 && __rtld_search_dirs.dirs != (void *) -1)
2272 fd = open_path (name, namelen, mode, &__rtld_search_dirs,
2273 &realname, &fb, l, LA_SER_DEFAULT, &found_other_class);
2275 /* Add another newline when we are tracing the library loading. */
2276 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_LIBS))
2277 _dl_debug_printf ("\n");
2279 else
2281 /* The path may contain dynamic string tokens. */
2282 realname = (loader
2283 ? expand_dynamic_string_token (loader, name)
2284 : __strdup (name));
2285 if (realname == NULL)
2286 fd = -1;
2287 else
2289 fd = open_verify (realname, -1, &fb,
2290 loader ?: GL(dl_ns)[nsid]._ns_loaded, 0, mode,
2291 &found_other_class, true);
2292 if (__glibc_unlikely (fd == -1))
2293 free (realname);
2297 #ifdef SHARED
2298 no_file:
2299 #endif
2300 /* In case the LOADER information has only been provided to get to
2301 the appropriate RUNPATH/RPATH information we do not need it
2302 anymore. */
2303 if (mode & __RTLD_CALLMAP)
2304 loader = NULL;
2306 if (__glibc_unlikely (fd == -1))
2308 if (trace_mode
2309 && __glibc_likely ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK) == 0))
2311 /* We haven't found an appropriate library. But since we
2312 are only interested in the list of libraries this isn't
2313 so severe. Fake an entry with all the information we
2314 have. */
2315 static const Elf_Symndx dummy_bucket = STN_UNDEF;
2317 /* Allocate a new object map. */
2318 if ((name_copy = __strdup (name)) == NULL
2319 || (l = _dl_new_object (name_copy, name, type, loader,
2320 mode, nsid)) == NULL)
2322 free (name_copy);
2323 _dl_signal_error (ENOMEM, name, NULL,
2324 N_("cannot create shared object descriptor"));
2326 /* Signal that this is a faked entry. */
2327 l->l_faked = 1;
2328 /* Since the descriptor is initialized with zero we do not
2329 have do this here.
2330 l->l_reserved = 0; */
2331 l->l_buckets = &dummy_bucket;
2332 l->l_nbuckets = 1;
2333 l->l_relocated = 1;
2335 /* Enter the object in the object list. */
2336 _dl_add_to_namespace_list (l, nsid);
2338 return l;
2340 else if (found_other_class)
2341 _dl_signal_error (0, name, NULL,
2342 ELFW(CLASS) == ELFCLASS32
2343 ? N_("wrong ELF class: ELFCLASS64")
2344 : N_("wrong ELF class: ELFCLASS32"));
2345 else
2346 _dl_signal_error (errno, name, NULL,
2347 N_("cannot open shared object file"));
2350 void *stack_end = __libc_stack_end;
2351 return _dl_map_object_from_fd (name, origname, fd, &fb, realname, loader,
2352 type, mode, &stack_end, nsid);
2355 struct add_path_state
2357 bool counting;
2358 unsigned int idx;
2359 Dl_serinfo *si;
2360 char *allocptr;
2363 static void
2364 add_path (struct add_path_state *p, const struct r_search_path_struct *sps,
2365 unsigned int flags)
2367 if (sps->dirs != (void *) -1)
2369 struct r_search_path_elem **dirs = sps->dirs;
2372 const struct r_search_path_elem *const r = *dirs++;
2373 if (p->counting)
2375 p->si->dls_cnt++;
2376 p->si->dls_size += MAX (2, r->dirnamelen);
2378 else
2380 Dl_serpath *const sp = &p->si->dls_serpath[p->idx++];
2381 sp->dls_name = p->allocptr;
2382 if (r->dirnamelen < 2)
2383 *p->allocptr++ = r->dirnamelen ? '/' : '.';
2384 else
2385 p->allocptr = __mempcpy (p->allocptr,
2386 r->dirname, r->dirnamelen - 1);
2387 *p->allocptr++ = '\0';
2388 sp->dls_flags = flags;
2391 while (*dirs != NULL);
2395 void
2396 _dl_rtld_di_serinfo (struct link_map *loader, Dl_serinfo *si, bool counting)
2398 if (counting)
2400 si->dls_cnt = 0;
2401 si->dls_size = 0;
2404 struct add_path_state p =
2406 .counting = counting,
2407 .idx = 0,
2408 .si = si,
2409 .allocptr = (char *) &si->dls_serpath[si->dls_cnt]
2412 # define add_path(p, sps, flags) add_path(p, sps, 0) /* XXX */
2414 /* When the object has the RUNPATH information we don't use any RPATHs. */
2415 if (loader->l_info[DT_RUNPATH] == NULL)
2417 /* First try the DT_RPATH of the dependent object that caused NAME
2418 to be loaded. Then that object's dependent, and on up. */
2420 struct link_map *l = loader;
2423 if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2424 add_path (&p, &l->l_rpath_dirs, XXX_RPATH);
2425 l = l->l_loader;
2427 while (l != NULL);
2429 /* If dynamically linked, try the DT_RPATH of the executable itself. */
2430 if (loader->l_ns == LM_ID_BASE)
2432 l = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2433 if (l != NULL && l->l_type != lt_loaded && l != loader)
2434 if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2435 add_path (&p, &l->l_rpath_dirs, XXX_RPATH);
2439 /* Try the LD_LIBRARY_PATH environment variable. */
2440 add_path (&p, &__rtld_env_path_list, XXX_ENV);
2442 /* Look at the RUNPATH information for this binary. */
2443 if (cache_rpath (loader, &loader->l_runpath_dirs, DT_RUNPATH, "RUNPATH"))
2444 add_path (&p, &loader->l_runpath_dirs, XXX_RUNPATH);
2446 /* XXX
2447 Here is where ld.so.cache gets checked, but we don't have
2448 a way to indicate that in the results for Dl_serinfo. */
2450 /* Finally, try the default path. */
2451 if (!(loader->l_flags_1 & DF_1_NODEFLIB))
2452 add_path (&p, &__rtld_search_dirs, XXX_default);
2454 if (counting)
2455 /* Count the struct size before the string area, which we didn't
2456 know before we completed dls_cnt. */
2457 si->dls_size += (char *) &si->dls_serpath[si->dls_cnt] - (char *) si;