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