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