Update.
[glibc.git] / elf / dl-load.c
blob5ff472a46ba0ec12e624fc483e6f8d593e403d32
1 /* Map in a shared object's segments from the file.
2 Copyright (C) 1995-2002, 2003, 2004 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
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 "dynamic-link.h"
35 #include <abi-tag.h>
36 #include <dl-osinfo.h>
38 #include <dl-dst.h>
40 /* On some systems, no flag bits are given to specify file mapping. */
41 #ifndef MAP_FILE
42 # define MAP_FILE 0
43 #endif
45 /* The right way to map in the shared library files is MAP_COPY, which
46 makes a virtual copy of the data at the time of the mmap call; this
47 guarantees the mapped pages will be consistent even if the file is
48 overwritten. Some losing VM systems like Linux's lack MAP_COPY. All we
49 get is MAP_PRIVATE, which copies each page when it is modified; this
50 means if the file is overwritten, we may at some point get some pages
51 from the new version after starting with pages from the old version. */
52 #ifndef MAP_COPY
53 # define MAP_COPY MAP_PRIVATE
54 #endif
56 /* Some systems link their relocatable objects for another base address
57 than 0. We want to know the base address for these such that we can
58 subtract this address from the segment addresses during mapping.
59 This results in a more efficient address space usage. Defaults to
60 zero for almost all systems. */
61 #ifndef MAP_BASE_ADDR
62 # define MAP_BASE_ADDR(l) 0
63 #endif
66 #include <endian.h>
67 #if BYTE_ORDER == BIG_ENDIAN
68 # define byteorder ELFDATA2MSB
69 #elif BYTE_ORDER == LITTLE_ENDIAN
70 # define byteorder ELFDATA2LSB
71 #else
72 # error "Unknown BYTE_ORDER " BYTE_ORDER
73 # define byteorder ELFDATANONE
74 #endif
76 #define STRING(x) __STRING (x)
78 #ifdef MAP_ANON
79 /* The fd is not examined when using MAP_ANON. */
80 # define ANONFD -1
81 #else
82 int _dl_zerofd = -1;
83 # define ANONFD _dl_zerofd
84 #endif
86 /* Handle situations where we have a preferred location in memory for
87 the shared objects. */
88 #ifdef ELF_PREFERRED_ADDRESS_DATA
89 ELF_PREFERRED_ADDRESS_DATA;
90 #endif
91 #ifndef ELF_PREFERRED_ADDRESS
92 # define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
93 #endif
94 #ifndef ELF_FIXED_ADDRESS
95 # define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
96 #endif
98 /* Type for the buffer we put the ELF header and hopefully the program
99 header. This buffer does not really have to be too large. In most
100 cases the program header follows the ELF header directly. If this
101 is not the case all bets are off and we can make the header
102 arbitrarily large and still won't get it read. This means the only
103 question is how large are the ELF and program header combined. The
104 ELF header 32-bit files is 52 bytes long and in 64-bit files is 64
105 bytes long. Each program header entry is again 32 and 56 bytes
106 long respectively. I.e., even with a file which has 7 program
107 header entries we only have to read 512B. Add to this a bit of
108 margin for program notes and reading 512B and 640B for 32-bit and
109 64-bit files respecitvely is enough. If this heuristic should
110 really fail for some file the code in `_dl_map_object_from_fd'
111 knows how to recover. */
112 struct filebuf
114 ssize_t len;
115 #if __WORDSIZE == 32
116 # define FILEBUF_SIZE 512
117 #else
118 # define FILEBUF_SIZE 640
119 #endif
120 char buf[FILEBUF_SIZE] __attribute__ ((aligned (__alignof (ElfW(Ehdr)))));
123 /* This is the decomposed LD_LIBRARY_PATH search path. */
124 static struct r_search_path_struct env_path_list attribute_relro;
126 /* List of the hardware capabilities we might end up using. */
127 static const struct r_strlenpair *capstr attribute_relro;
128 static size_t ncapstr attribute_relro;
129 static size_t max_capstrlen attribute_relro;
132 /* Get the generated information about the trusted directories. */
133 #include "trusted-dirs.h"
135 static const char system_dirs[] = SYSTEM_DIRS;
136 static const size_t system_dirs_len[] =
138 SYSTEM_DIRS_LEN
140 #define nsystem_dirs_len \
141 (sizeof (system_dirs_len) / sizeof (system_dirs_len[0]))
144 /* Local version of `strdup' function. */
145 static inline char *
146 local_strdup (const char *s)
148 size_t len = strlen (s) + 1;
149 void *new = malloc (len);
151 if (new == NULL)
152 return NULL;
154 return (char *) memcpy (new, s, len);
158 static size_t
159 is_dst (const char *start, const char *name, const char *str,
160 int is_path, int secure)
162 size_t len;
163 bool is_curly = false;
165 if (name[0] == '{')
167 is_curly = true;
168 ++name;
171 len = 0;
172 while (name[len] == str[len] && name[len] != '\0')
173 ++len;
175 if (is_curly)
177 if (name[len] != '}')
178 return 0;
180 /* Point again at the beginning of the name. */
181 --name;
182 /* Skip over closing curly brace and adjust for the --name. */
183 len += 2;
185 else if (name[len] != '\0' && name[len] != '/'
186 && (!is_path || name[len] != ':'))
187 return 0;
189 if (__builtin_expect (secure, 0)
190 && ((name[len] != '\0' && (!is_path || name[len] != ':'))
191 || (name != start + 1 && (!is_path || name[-2] != ':'))))
192 return 0;
194 return len;
198 size_t
199 _dl_dst_count (const char *name, int is_path)
201 const char *const start = name;
202 size_t cnt = 0;
206 size_t len;
208 /* $ORIGIN is not expanded for SUID/GUID programs (except if it
209 is $ORIGIN alone) and it must always appear first in path. */
210 ++name;
211 if ((len = is_dst (start, name, "ORIGIN", is_path,
212 INTUSE(__libc_enable_secure))) != 0
213 || (len = is_dst (start, name, "PLATFORM", is_path, 0)) != 0
214 || (len = is_dst (start, name, "LIB", is_path, 0)) != 0)
215 ++cnt;
217 name = strchr (name + len, '$');
219 while (name != NULL);
221 return cnt;
225 char *
226 _dl_dst_substitute (struct link_map *l, const char *name, char *result,
227 int is_path)
229 const char *const start = name;
230 char *last_elem, *wp;
232 /* Now fill the result path. While copying over the string we keep
233 track of the start of the last path element. When we come accross
234 a DST we copy over the value or (if the value is not available)
235 leave the entire path element out. */
236 last_elem = wp = result;
240 if (__builtin_expect (*name == '$', 0))
242 const char *repl = NULL;
243 size_t len;
245 ++name;
246 if ((len = is_dst (start, name, "ORIGIN", is_path,
247 INTUSE(__libc_enable_secure))) != 0)
248 repl = l->l_origin;
249 else if ((len = is_dst (start, name, "PLATFORM", is_path, 0)) != 0)
250 repl = GLRO(dl_platform);
251 else if ((len = is_dst (start, name, "LIB", is_path, 0)) != 0)
252 repl = DL_DST_LIB;
254 if (repl != NULL && repl != (const char *) -1)
256 wp = __stpcpy (wp, repl);
257 name += len;
259 else if (len > 1)
261 /* We cannot use this path element, the value of the
262 replacement is unknown. */
263 wp = last_elem;
264 name += len;
265 while (*name != '\0' && (!is_path || *name != ':'))
266 ++name;
268 else
269 /* No DST we recognize. */
270 *wp++ = '$';
272 else
274 *wp++ = *name++;
275 if (is_path && *name == ':')
276 last_elem = wp;
279 while (*name != '\0');
281 *wp = '\0';
283 return result;
287 /* Return copy of argument with all recognized dynamic string tokens
288 ($ORIGIN and $PLATFORM for now) replaced. On some platforms it
289 might not be possible to determine the path from which the object
290 belonging to the map is loaded. In this case the path element
291 containing $ORIGIN is left out. */
292 static char *
293 expand_dynamic_string_token (struct link_map *l, const char *s)
295 /* We make two runs over the string. First we determine how large the
296 resulting string is and then we copy it over. Since this is now
297 frequently executed operation we are looking here not for performance
298 but rather for code size. */
299 size_t cnt;
300 size_t total;
301 char *result;
303 /* Determine the number of DST elements. */
304 cnt = DL_DST_COUNT (s, 1);
306 /* If we do not have to replace anything simply copy the string. */
307 if (__builtin_expect (cnt, 0) == 0)
308 return local_strdup (s);
310 /* Determine the length of the substituted string. */
311 total = DL_DST_REQUIRED (l, s, strlen (s), cnt);
313 /* Allocate the necessary memory. */
314 result = (char *) malloc (total + 1);
315 if (result == NULL)
316 return NULL;
318 return _dl_dst_substitute (l, s, result, 1);
322 /* Add `name' to the list of names for a particular shared object.
323 `name' is expected to have been allocated with malloc and will
324 be freed if the shared object already has this name.
325 Returns false if the object already had this name. */
326 static void
327 internal_function
328 add_name_to_object (struct link_map *l, const char *name)
330 struct libname_list *lnp, *lastp;
331 struct libname_list *newname;
332 size_t name_len;
334 lastp = NULL;
335 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
336 if (strcmp (name, lnp->name) == 0)
337 return;
339 name_len = strlen (name) + 1;
340 newname = (struct libname_list *) malloc (sizeof *newname + name_len);
341 if (newname == NULL)
343 /* No more memory. */
344 _dl_signal_error (ENOMEM, name, NULL, N_("cannot allocate name record"));
345 return;
347 /* The object should have a libname set from _dl_new_object. */
348 assert (lastp != NULL);
350 newname->name = memcpy (newname + 1, name, name_len);
351 newname->next = NULL;
352 newname->dont_free = 0;
353 lastp->next = newname;
356 /* Standard search directories. */
357 static struct r_search_path_struct rtld_search_dirs attribute_relro;
359 static size_t max_dirnamelen;
361 static struct r_search_path_elem **
362 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
363 int check_trusted, const char *what, const char *where)
365 char *cp;
366 size_t nelems = 0;
368 while ((cp = __strsep (&rpath, sep)) != NULL)
370 struct r_search_path_elem *dirp;
371 size_t len = strlen (cp);
373 /* `strsep' can pass an empty string. This has to be
374 interpreted as `use the current directory'. */
375 if (len == 0)
377 static const char curwd[] = "./";
378 cp = (char *) curwd;
381 /* Remove trailing slashes (except for "/"). */
382 while (len > 1 && cp[len - 1] == '/')
383 --len;
385 /* Now add one if there is none so far. */
386 if (len > 0 && cp[len - 1] != '/')
387 cp[len++] = '/';
389 /* Make sure we don't use untrusted directories if we run SUID. */
390 if (__builtin_expect (check_trusted, 0))
392 const char *trun = system_dirs;
393 size_t idx;
394 int unsecure = 1;
396 /* All trusted directories must be complete names. */
397 if (cp[0] == '/')
399 for (idx = 0; idx < nsystem_dirs_len; ++idx)
401 if (len == system_dirs_len[idx]
402 && memcmp (trun, cp, len) == 0)
404 /* Found it. */
405 unsecure = 0;
406 break;
409 trun += system_dirs_len[idx] + 1;
413 if (unsecure)
414 /* Simply drop this directory. */
415 continue;
418 /* See if this directory is already known. */
419 for (dirp = GL(dl_all_dirs); dirp != NULL; dirp = dirp->next)
420 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
421 break;
423 if (dirp != NULL)
425 /* It is available, see whether it's on our own list. */
426 size_t cnt;
427 for (cnt = 0; cnt < nelems; ++cnt)
428 if (result[cnt] == dirp)
429 break;
431 if (cnt == nelems)
432 result[nelems++] = dirp;
434 else
436 size_t cnt;
437 enum r_dir_status init_val;
438 size_t where_len = where ? strlen (where) + 1 : 0;
440 /* It's a new directory. Create an entry and add it. */
441 dirp = (struct r_search_path_elem *)
442 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status)
443 + where_len + len + 1);
444 if (dirp == NULL)
445 _dl_signal_error (ENOMEM, NULL, NULL,
446 N_("cannot create cache for search path"));
448 dirp->dirname = ((char *) dirp + sizeof (*dirp)
449 + ncapstr * sizeof (enum r_dir_status));
450 *((char *) __mempcpy ((char *) dirp->dirname, cp, len)) = '\0';
451 dirp->dirnamelen = len;
453 if (len > max_dirnamelen)
454 max_dirnamelen = len;
456 /* We have to make sure all the relative directories are
457 never ignored. The current directory might change and
458 all our saved information would be void. */
459 init_val = cp[0] != '/' ? existing : unknown;
460 for (cnt = 0; cnt < ncapstr; ++cnt)
461 dirp->status[cnt] = init_val;
463 dirp->what = what;
464 if (__builtin_expect (where != NULL, 1))
465 dirp->where = memcpy ((char *) dirp + sizeof (*dirp) + len + 1
466 + (ncapstr * sizeof (enum r_dir_status)),
467 where, where_len);
468 else
469 dirp->where = NULL;
471 dirp->next = GL(dl_all_dirs);
472 GL(dl_all_dirs) = dirp;
474 /* Put it in the result array. */
475 result[nelems++] = dirp;
479 /* Terminate the array. */
480 result[nelems] = NULL;
482 return result;
486 static void
487 internal_function
488 decompose_rpath (struct r_search_path_struct *sps,
489 const char *rpath, struct link_map *l, const char *what)
491 /* Make a copy we can work with. */
492 const char *where = l->l_name;
493 char *copy;
494 char *cp;
495 struct r_search_path_elem **result;
496 size_t nelems;
497 /* Initialize to please the compiler. */
498 const char *errstring = NULL;
500 /* First see whether we must forget the RUNPATH and RPATH from this
501 object. */
502 if (__builtin_expect (GLRO(dl_inhibit_rpath) != NULL, 0)
503 && !INTUSE(__libc_enable_secure))
505 const char *inhp = GLRO(dl_inhibit_rpath);
509 const char *wp = where;
511 while (*inhp == *wp && *wp != '\0')
513 ++inhp;
514 ++wp;
517 if (*wp == '\0' && (*inhp == '\0' || *inhp == ':'))
519 /* This object is on the list of objects for which the
520 RUNPATH and RPATH must not be used. */
521 result = calloc (1, sizeof *result);
522 if (result == NULL)
524 signal_error_cache:
525 errstring = N_("cannot create cache for search path");
526 signal_error:
527 _dl_signal_error (ENOMEM, NULL, NULL, errstring);
530 sps->dirs = result;
531 sps->malloced = 1;
533 return;
536 while (*inhp != '\0')
537 if (*inhp++ == ':')
538 break;
540 while (*inhp != '\0');
543 /* Make a writable copy. At the same time expand possible dynamic
544 string tokens. */
545 copy = expand_dynamic_string_token (l, rpath);
546 if (copy == NULL)
548 errstring = N_("cannot create RUNPATH/RPATH copy");
549 goto signal_error;
552 /* Count the number of necessary elements in the result array. */
553 nelems = 0;
554 for (cp = copy; *cp != '\0'; ++cp)
555 if (*cp == ':')
556 ++nelems;
558 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
559 number of necessary entries. */
560 result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
561 * sizeof (*result));
562 if (result == NULL)
563 goto signal_error_cache;
565 fillin_rpath (copy, result, ":", 0, what, where);
567 /* Free the copied RPATH string. `fillin_rpath' make own copies if
568 necessary. */
569 free (copy);
571 sps->dirs = result;
572 /* The caller will change this value if we haven't used a real malloc. */
573 sps->malloced = 1;
576 /* Make sure cached path information is stored in *SP
577 and return true if there are any paths to search there. */
578 static bool
579 cache_rpath (struct link_map *l,
580 struct r_search_path_struct *sp,
581 int tag,
582 const char *what)
584 if (sp->dirs == (void *) -1)
585 return false;
587 if (sp->dirs != NULL)
588 return true;
590 if (l->l_info[tag] == NULL)
592 /* There is no path. */
593 sp->dirs = (void *) -1;
594 return false;
597 /* Make sure the cache information is available. */
598 decompose_rpath (sp, (const char *) (D_PTR (l, l_info[DT_STRTAB])
599 + l->l_info[tag]->d_un.d_val),
600 l, what);
601 return true;
605 void
606 internal_function
607 _dl_init_paths (const char *llp)
609 size_t idx;
610 const char *strp;
611 struct r_search_path_elem *pelem, **aelem;
612 size_t round_size;
613 #ifdef SHARED
614 struct link_map *l;
615 #endif
616 /* Initialize to please the compiler. */
617 const char *errstring = NULL;
619 /* Fill in the information about the application's RPATH and the
620 directories addressed by the LD_LIBRARY_PATH environment variable. */
622 /* Get the capabilities. */
623 capstr = _dl_important_hwcaps (GLRO(dl_platform), GLRO(dl_platformlen),
624 &ncapstr, &max_capstrlen);
626 /* First set up the rest of the default search directory entries. */
627 aelem = rtld_search_dirs.dirs = (struct r_search_path_elem **)
628 malloc ((nsystem_dirs_len + 1) * sizeof (struct r_search_path_elem *));
629 if (rtld_search_dirs.dirs == NULL)
631 errstring = N_("cannot create search path array");
632 signal_error:
633 _dl_signal_error (ENOMEM, NULL, NULL, errstring);
636 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
637 + ncapstr * sizeof (enum r_dir_status))
638 / sizeof (struct r_search_path_elem));
640 rtld_search_dirs.dirs[0] = (struct r_search_path_elem *)
641 malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]))
642 * round_size * sizeof (struct r_search_path_elem));
643 if (rtld_search_dirs.dirs[0] == NULL)
645 errstring = N_("cannot create cache for search path");
646 goto signal_error;
649 rtld_search_dirs.malloced = 0;
650 pelem = GL(dl_all_dirs) = rtld_search_dirs.dirs[0];
651 strp = system_dirs;
652 idx = 0;
656 size_t cnt;
658 *aelem++ = pelem;
660 pelem->what = "system search path";
661 pelem->where = NULL;
663 pelem->dirname = strp;
664 pelem->dirnamelen = system_dirs_len[idx];
665 strp += system_dirs_len[idx] + 1;
667 /* System paths must be absolute. */
668 assert (pelem->dirname[0] == '/');
669 for (cnt = 0; cnt < ncapstr; ++cnt)
670 pelem->status[cnt] = unknown;
672 pelem->next = (++idx == nsystem_dirs_len ? NULL : (pelem + round_size));
674 pelem += round_size;
676 while (idx < nsystem_dirs_len);
678 max_dirnamelen = SYSTEM_DIRS_MAX_LEN;
679 *aelem = NULL;
681 #ifdef SHARED
682 /* This points to the map of the main object. */
683 l = GL(dl_loaded);
684 if (l != NULL)
686 assert (l->l_type != lt_loaded);
688 if (l->l_info[DT_RUNPATH])
690 /* Allocate room for the search path and fill in information
691 from RUNPATH. */
692 decompose_rpath (&l->l_runpath_dirs,
693 (const void *) (D_PTR (l, l_info[DT_STRTAB])
694 + l->l_info[DT_RUNPATH]->d_un.d_val),
695 l, "RUNPATH");
697 /* The RPATH is ignored. */
698 l->l_rpath_dirs.dirs = (void *) -1;
700 else
702 l->l_runpath_dirs.dirs = (void *) -1;
704 if (l->l_info[DT_RPATH])
706 /* Allocate room for the search path and fill in information
707 from RPATH. */
708 decompose_rpath (&l->l_rpath_dirs,
709 (const void *) (D_PTR (l, l_info[DT_STRTAB])
710 + l->l_info[DT_RPATH]->d_un.d_val),
711 l, "RPATH");
712 l->l_rpath_dirs.malloced = 0;
714 else
715 l->l_rpath_dirs.dirs = (void *) -1;
718 #endif /* SHARED */
720 if (llp != NULL && *llp != '\0')
722 size_t nllp;
723 const char *cp = llp;
724 char *llp_tmp = strdupa (llp);
726 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
727 elements it has. */
728 nllp = 1;
729 while (*cp)
731 if (*cp == ':' || *cp == ';')
732 ++nllp;
733 ++cp;
736 env_path_list.dirs = (struct r_search_path_elem **)
737 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
738 if (env_path_list.dirs == NULL)
740 errstring = N_("cannot create cache for search path");
741 goto signal_error;
744 (void) fillin_rpath (llp_tmp, env_path_list.dirs, ":;",
745 INTUSE(__libc_enable_secure), "LD_LIBRARY_PATH",
746 NULL);
748 if (env_path_list.dirs[0] == NULL)
750 free (env_path_list.dirs);
751 env_path_list.dirs = (void *) -1;
754 env_path_list.malloced = 0;
756 else
757 env_path_list.dirs = (void *) -1;
759 /* Remember the last search directory added at startup. */
760 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
764 static void
765 __attribute__ ((noreturn, noinline))
766 lose (int code, int fd, const char *name, char *realname, struct link_map *l,
767 const char *msg)
769 /* The file might already be closed. */
770 if (fd != -1)
771 (void) __close (fd);
772 if (l != NULL)
774 /* Remove the stillborn object from the list and free it. */
775 assert (l->l_next == NULL);
776 if (l->l_prev == NULL)
777 /* No other module loaded. This happens only in the static library,
778 or in rtld under --verify. */
779 GL(dl_loaded) = NULL;
780 else
781 l->l_prev->l_next = NULL;
782 --GL(dl_nloaded);
783 free (l);
785 free (realname);
786 _dl_signal_error (code, name, NULL, msg);
790 /* Map in the shared object NAME, actually located in REALNAME, and already
791 opened on FD. */
793 #ifndef EXTERNAL_MAP_FROM_FD
794 static
795 #endif
796 struct link_map *
797 _dl_map_object_from_fd (const char *name, int fd, struct filebuf *fbp,
798 char *realname, struct link_map *loader, int l_type,
799 int mode, void **stack_endp)
801 struct link_map *l = NULL;
802 const ElfW(Ehdr) *header;
803 const ElfW(Phdr) *phdr;
804 const ElfW(Phdr) *ph;
805 size_t maplength;
806 int type;
807 struct stat64 st;
808 /* Initialize to keep the compiler happy. */
809 const char *errstring = NULL;
810 int errval = 0;
812 /* Get file information. */
813 if (__builtin_expect (__fxstat64 (_STAT_VER, fd, &st) < 0, 0))
815 errstring = N_("cannot stat shared object");
816 call_lose_errno:
817 errval = errno;
818 call_lose:
819 lose (errval, fd, name, realname, l, errstring);
822 /* Look again to see if the real name matched another already loaded. */
823 for (l = GL(dl_loaded); l; l = l->l_next)
824 if (l->l_ino == st.st_ino && l->l_dev == st.st_dev)
826 /* The object is already loaded.
827 Just bump its reference count and return it. */
828 __close (fd);
830 /* If the name is not in the list of names for this object add
831 it. */
832 free (realname);
833 add_name_to_object (l, name);
835 return l;
838 if (mode & RTLD_NOLOAD)
839 /* We are not supposed to load the object unless it is already
840 loaded. So return now. */
841 return NULL;
843 /* Print debugging message. */
844 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
845 _dl_debug_printf ("file=%s; generating link map\n", name);
847 /* This is the ELF header. We read it in `open_verify'. */
848 header = (void *) fbp->buf;
850 #ifndef MAP_ANON
851 # define MAP_ANON 0
852 if (_dl_zerofd == -1)
854 _dl_zerofd = _dl_sysdep_open_zero_fill ();
855 if (_dl_zerofd == -1)
857 __close (fd);
858 _dl_signal_error (errno, NULL, NULL,
859 N_("cannot open zero fill device"));
862 #endif
864 /* Enter the new object in the list of loaded objects. */
865 l = _dl_new_object (realname, name, l_type, loader);
866 if (__builtin_expect (! l, 0))
868 errstring = N_("cannot create shared object descriptor");
869 goto call_lose_errno;
872 /* Extract the remaining details we need from the ELF header
873 and then read in the program header table. */
874 l->l_entry = header->e_entry;
875 type = header->e_type;
876 l->l_phnum = header->e_phnum;
878 maplength = header->e_phnum * sizeof (ElfW(Phdr));
879 if (header->e_phoff + maplength <= (size_t) fbp->len)
880 phdr = (void *) (fbp->buf + header->e_phoff);
881 else
883 phdr = alloca (maplength);
884 __lseek (fd, header->e_phoff, SEEK_SET);
885 if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
887 errstring = N_("cannot read file data");
888 goto call_lose_errno;
892 /* Presumed absent PT_GNU_STACK. */
893 uint_fast16_t stack_flags = PF_R|PF_W|PF_X;
896 /* Scan the program header table, collecting its load commands. */
897 struct loadcmd
899 ElfW(Addr) mapstart, mapend, dataend, allocend;
900 off_t mapoff;
901 int prot;
902 } loadcmds[l->l_phnum], *c;
903 size_t nloadcmds = 0;
904 bool has_holes = false;
906 /* The struct is initialized to zero so this is not necessary:
907 l->l_ld = 0;
908 l->l_phdr = 0;
909 l->l_addr = 0; */
910 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
911 switch (ph->p_type)
913 /* These entries tell us where to find things once the file's
914 segments are mapped in. We record the addresses it says
915 verbatim, and later correct for the run-time load address. */
916 case PT_DYNAMIC:
917 l->l_ld = (void *) ph->p_vaddr;
918 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
919 break;
921 case PT_PHDR:
922 l->l_phdr = (void *) ph->p_vaddr;
923 break;
925 case PT_LOAD:
926 /* A load command tells us to map in part of the file.
927 We record the load commands and process them all later. */
928 if (__builtin_expect ((ph->p_align & (GLRO(dl_pagesize) - 1)) != 0,
931 errstring = N_("ELF load command alignment not page-aligned");
932 goto call_lose;
934 if (__builtin_expect (((ph->p_vaddr - ph->p_offset)
935 & (ph->p_align - 1)) != 0, 0))
937 errstring
938 = N_("ELF load command address/offset not properly aligned");
939 goto call_lose;
942 c = &loadcmds[nloadcmds++];
943 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
944 c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1)
945 & ~(GLRO(dl_pagesize) - 1));
946 c->dataend = ph->p_vaddr + ph->p_filesz;
947 c->allocend = ph->p_vaddr + ph->p_memsz;
948 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
950 /* Determine whether there is a gap between the last segment
951 and this one. */
952 if (nloadcmds > 1 && c[-1].mapend != c->mapstart)
953 has_holes = true;
955 /* Optimize a common case. */
956 #if (PF_R | PF_W | PF_X) == 7 && (PROT_READ | PROT_WRITE | PROT_EXEC) == 7
957 c->prot = (PF_TO_PROT
958 >> ((ph->p_flags & (PF_R | PF_W | PF_X)) * 4)) & 0xf;
959 #else
960 c->prot = 0;
961 if (ph->p_flags & PF_R)
962 c->prot |= PROT_READ;
963 if (ph->p_flags & PF_W)
964 c->prot |= PROT_WRITE;
965 if (ph->p_flags & PF_X)
966 c->prot |= PROT_EXEC;
967 #endif
968 break;
970 case PT_TLS:
971 #ifdef USE_TLS
972 if (ph->p_memsz == 0)
973 /* Nothing to do for an empty segment. */
974 break;
976 l->l_tls_blocksize = ph->p_memsz;
977 l->l_tls_align = ph->p_align;
978 if (ph->p_align == 0)
979 l->l_tls_firstbyte_offset = 0;
980 else
981 l->l_tls_firstbyte_offset = ph->p_vaddr & (ph->p_align - 1);
982 l->l_tls_initimage_size = ph->p_filesz;
983 /* Since we don't know the load address yet only store the
984 offset. We will adjust it later. */
985 l->l_tls_initimage = (void *) ph->p_vaddr;
987 /* If not loading the initial set of shared libraries,
988 check whether we should permit loading a TLS segment. */
989 if (__builtin_expect (l->l_type == lt_library, 1)
990 /* If GL(dl_tls_dtv_slotinfo_list) == NULL, then rtld.c did
991 not set up TLS data structures, so don't use them now. */
992 || __builtin_expect (GL(dl_tls_dtv_slotinfo_list) != NULL, 1))
994 /* Assign the next available module ID. */
995 l->l_tls_modid = _dl_next_tls_modid ();
996 break;
999 # ifdef SHARED
1000 if (l->l_prev == NULL)
1001 /* We are loading the executable itself when the dynamic linker
1002 was executed directly. The setup will happen later. */
1003 break;
1005 /* In a static binary there is no way to tell if we dynamically
1006 loaded libpthread. */
1007 if (GL(dl_error_catch_tsd) == &_dl_initial_error_catch_tsd)
1008 # endif
1010 /* We have not yet loaded libpthread.
1011 We can do the TLS setup right now! */
1013 void *tcb;
1015 /* The first call allocates TLS bookkeeping data structures.
1016 Then we allocate the TCB for the initial thread. */
1017 if (__builtin_expect (_dl_tls_setup (), 0)
1018 || __builtin_expect ((tcb = _dl_allocate_tls (NULL)) == NULL,
1021 errval = ENOMEM;
1022 errstring = N_("\
1023 cannot allocate TLS data structures for initial thread");
1024 goto call_lose;
1027 /* Now we install the TCB in the thread register. */
1028 errstring = TLS_INIT_TP (tcb, 0);
1029 if (__builtin_expect (errstring == NULL, 1))
1031 /* Now we are all good. */
1032 l->l_tls_modid = ++GL(dl_tls_max_dtv_idx);
1033 break;
1036 /* The kernel is too old or somesuch. */
1037 errval = 0;
1038 _dl_deallocate_tls (tcb, 1);
1039 goto call_lose;
1041 #endif
1043 /* Uh-oh, the binary expects TLS support but we cannot
1044 provide it. */
1045 errval = 0;
1046 errstring = N_("cannot handle TLS data");
1047 goto call_lose;
1048 break;
1050 case PT_GNU_STACK:
1051 stack_flags = ph->p_flags;
1052 break;
1054 case PT_GNU_RELRO:
1055 l->l_relro_addr = ph->p_vaddr;
1056 l->l_relro_size = ph->p_memsz;
1057 break;
1060 if (__builtin_expect (nloadcmds == 0, 0))
1062 /* This only happens for a bogus object that will be caught with
1063 another error below. But we don't want to go through the
1064 calculations below using NLOADCMDS - 1. */
1065 errstring = N_("object file has no loadable segments");
1066 goto call_lose;
1069 /* Now process the load commands and map segments into memory. */
1070 c = loadcmds;
1072 /* Length of the sections to be loaded. */
1073 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
1075 if (__builtin_expect (type, ET_DYN) == ET_DYN)
1077 /* This is a position-independent shared object. We can let the
1078 kernel map it anywhere it likes, but we must have space for all
1079 the segments in their specified positions relative to the first.
1080 So we map the first segment without MAP_FIXED, but with its
1081 extent increased to cover all the segments. Then we remove
1082 access from excess portion, and there is known sufficient space
1083 there to remap from the later segments.
1085 As a refinement, sometimes we have an address that we would
1086 prefer to map such objects at; but this is only a preference,
1087 the OS can do whatever it likes. */
1088 ElfW(Addr) mappref;
1089 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength,
1090 c->mapstart & GLRO(dl_use_load_bias))
1091 - MAP_BASE_ADDR (l));
1093 /* Remember which part of the address space this object uses. */
1094 l->l_map_start = (ElfW(Addr)) __mmap ((void *) mappref, maplength,
1095 c->prot, MAP_COPY | MAP_FILE,
1096 fd, c->mapoff);
1097 if (__builtin_expect ((void *) l->l_map_start == MAP_FAILED, 0))
1099 map_error:
1100 errstring = N_("failed to map segment from shared object");
1101 goto call_lose_errno;
1104 l->l_map_end = l->l_map_start + maplength;
1105 l->l_addr = l->l_map_start - c->mapstart;
1107 if (has_holes)
1108 /* Change protection on the excess portion to disallow all access;
1109 the portions we do not remap later will be inaccessible as if
1110 unallocated. Then jump into the normal segment-mapping loop to
1111 handle the portion of the segment past the end of the file
1112 mapping. */
1113 __mprotect ((caddr_t) l->l_text_end,
1114 loadcmds[nloadcmds - 1].allocend - c->mapend,
1115 PROT_NONE);
1117 goto postmap;
1119 else
1121 /* This object is loaded at a fixed address. This must never
1122 happen for objects loaded with dlopen(). */
1123 if (__builtin_expect ((mode & __RTLD_OPENEXEC) == 0, 0))
1125 errstring = N_("cannot dynamically load executable");
1126 goto call_lose;
1129 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
1130 fixed. */
1131 ELF_FIXED_ADDRESS (loader, c->mapstart);
1134 /* Remember which part of the address space this object uses. */
1135 l->l_map_start = c->mapstart + l->l_addr;
1136 l->l_map_end = l->l_map_start + maplength;
1138 while (c < &loadcmds[nloadcmds])
1140 if (c->mapend > c->mapstart
1141 /* Map the segment contents from the file. */
1142 && (__mmap ((void *) (l->l_addr + c->mapstart),
1143 c->mapend - c->mapstart, c->prot,
1144 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff)
1145 == MAP_FAILED))
1146 goto map_error;
1148 postmap:
1149 if (c->prot & PROT_EXEC)
1150 l->l_text_end = l->l_addr + c->mapend;
1152 if (l->l_phdr == 0
1153 && (ElfW(Off)) c->mapoff <= header->e_phoff
1154 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
1155 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
1156 /* Found the program header in this segment. */
1157 l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff);
1159 if (c->allocend > c->dataend)
1161 /* Extra zero pages should appear at the end of this segment,
1162 after the data mapped from the file. */
1163 ElfW(Addr) zero, zeroend, zeropage;
1165 zero = l->l_addr + c->dataend;
1166 zeroend = l->l_addr + c->allocend;
1167 zeropage = ((zero + GLRO(dl_pagesize) - 1)
1168 & ~(GLRO(dl_pagesize) - 1));
1170 if (zeroend < zeropage)
1171 /* All the extra data is in the last page of the segment.
1172 We can just zero it. */
1173 zeropage = zeroend;
1175 if (zeropage > zero)
1177 /* Zero the final part of the last page of the segment. */
1178 if (__builtin_expect ((c->prot & PROT_WRITE) == 0, 0))
1180 /* Dag nab it. */
1181 if (__mprotect ((caddr_t) (zero
1182 & ~(GLRO(dl_pagesize) - 1)),
1183 GLRO(dl_pagesize), c->prot|PROT_WRITE) < 0)
1185 errstring = N_("cannot change memory protections");
1186 goto call_lose_errno;
1189 memset ((void *) zero, '\0', zeropage - zero);
1190 if (__builtin_expect ((c->prot & PROT_WRITE) == 0, 0))
1191 __mprotect ((caddr_t) (zero & ~(GLRO(dl_pagesize) - 1)),
1192 GLRO(dl_pagesize), c->prot);
1195 if (zeroend > zeropage)
1197 /* Map the remaining zero pages in from the zero fill FD. */
1198 caddr_t mapat;
1199 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
1200 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
1201 ANONFD, 0);
1202 if (__builtin_expect (mapat == MAP_FAILED, 0))
1204 errstring = N_("cannot map zero-fill pages");
1205 goto call_lose_errno;
1210 ++c;
1213 if (l->l_phdr == NULL)
1215 /* The program header is not contained in any of the segments.
1216 We have to allocate memory ourself and copy it over from
1217 out temporary place. */
1218 ElfW(Phdr) *newp = (ElfW(Phdr) *) malloc (header->e_phnum
1219 * sizeof (ElfW(Phdr)));
1220 if (newp == NULL)
1222 errstring = N_("cannot allocate memory for program header");
1223 goto call_lose_errno;
1226 l->l_phdr = memcpy (newp, phdr,
1227 (header->e_phnum * sizeof (ElfW(Phdr))));
1228 l->l_phdr_allocated = 1;
1230 else
1231 /* Adjust the PT_PHDR value by the runtime load address. */
1232 l->l_phdr = (ElfW(Phdr) *) ((ElfW(Addr)) l->l_phdr + l->l_addr);
1235 #ifdef USE_TLS
1236 /* Adjust the address of the TLS initialization image. */
1237 if (l->l_tls_initimage != NULL)
1238 l->l_tls_initimage = (char *) l->l_tls_initimage + l->l_addr;
1239 #endif
1241 /* We are done mapping in the file. We no longer need the descriptor. */
1242 __close (fd);
1243 /* Signal that we closed the file. */
1244 fd = -1;
1246 if (l->l_type == lt_library && type == ET_EXEC)
1247 l->l_type = lt_executable;
1249 if (l->l_ld == 0)
1251 if (__builtin_expect (type == ET_DYN, 0))
1253 errstring = N_("object file has no dynamic section");
1254 goto call_lose;
1257 else
1258 l->l_ld = (ElfW(Dyn) *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1260 l->l_entry += l->l_addr;
1262 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
1263 _dl_debug_printf ("\
1264 dynamic: 0x%0*lx base: 0x%0*lx size: 0x%0*Zx\n\
1265 entry: 0x%0*lx phdr: 0x%0*lx phnum: %*u\n\n",
1266 (int) sizeof (void *) * 2,
1267 (unsigned long int) l->l_ld,
1268 (int) sizeof (void *) * 2,
1269 (unsigned long int) l->l_addr,
1270 (int) sizeof (void *) * 2, maplength,
1271 (int) sizeof (void *) * 2,
1272 (unsigned long int) l->l_entry,
1273 (int) sizeof (void *) * 2,
1274 (unsigned long int) l->l_phdr,
1275 (int) sizeof (void *) * 2, l->l_phnum);
1277 elf_get_dynamic_info (l, NULL);
1279 /* Make sure we are not dlopen'ing an object
1280 that has the DF_1_NOOPEN flag set. */
1281 if (__builtin_expect (l->l_flags_1 & DF_1_NOOPEN, 0)
1282 && (mode & __RTLD_DLOPEN))
1284 /* We are not supposed to load this object. Free all resources. */
1285 __munmap ((void *) l->l_map_start, l->l_map_end - l->l_map_start);
1287 if (!l->l_libname->dont_free)
1288 free (l->l_libname);
1290 if (l->l_phdr_allocated)
1291 free ((void *) l->l_phdr);
1293 errstring = N_("shared object cannot be dlopen()ed");
1294 goto call_lose;
1297 if (l->l_info[DT_HASH])
1298 _dl_setup_hash (l);
1300 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
1301 have to do this for the main map. */
1302 if (__builtin_expect (l->l_info[DT_SYMBOLIC] != NULL, 0)
1303 && &l->l_searchlist != l->l_scope[0])
1305 /* Create an appropriate searchlist. It contains only this map.
1307 XXX This is the definition of DT_SYMBOLIC in SysVr4. The old
1308 GNU ld.so implementation had a different interpretation which
1309 is more reasonable. We are prepared to add this possibility
1310 back as part of a GNU extension of the ELF format. */
1311 l->l_symbolic_searchlist.r_list =
1312 (struct link_map **) malloc (sizeof (struct link_map *));
1314 if (l->l_symbolic_searchlist.r_list == NULL)
1316 errstring = N_("cannot create searchlist");
1317 goto call_lose_errno;
1320 l->l_symbolic_searchlist.r_list[0] = l;
1321 l->l_symbolic_searchlist.r_nlist = 1;
1323 /* Now move the existing entries one back. */
1324 memmove (&l->l_scope[1], &l->l_scope[0],
1325 (l->l_scope_max - 1) * sizeof (l->l_scope[0]));
1327 /* Now add the new entry. */
1328 l->l_scope[0] = &l->l_symbolic_searchlist;
1331 /* Remember whether this object must be initialized first. */
1332 if (l->l_flags_1 & DF_1_INITFIRST)
1333 GL(dl_initfirst) = l;
1335 /* Finally the file information. */
1336 l->l_dev = st.st_dev;
1337 l->l_ino = st.st_ino;
1339 if (__builtin_expect ((stack_flags &~ GL(dl_stack_flags)) & PF_X, 0))
1341 /* The stack is presently not executable, but this module
1342 requires that it be executable. */
1343 errval = (*GL(dl_make_stack_executable_hook)) (stack_endp);
1344 if (errval)
1346 errstring = N_("\
1347 cannot enable executable stack as shared object requires");
1348 goto call_lose;
1352 /* When we profile the SONAME might be needed for something else but
1353 loading. Add it right away. */
1354 if (__builtin_expect (GLRO(dl_profile) != NULL, 0)
1355 && l->l_info[DT_SONAME] != NULL)
1356 add_name_to_object (l, ((const char *) D_PTR (l, l_info[DT_STRTAB])
1357 + l->l_info[DT_SONAME]->d_un.d_val));
1359 return l;
1362 /* Print search path. */
1363 static void
1364 print_search_path (struct r_search_path_elem **list,
1365 const char *what, const char *name)
1367 char buf[max_dirnamelen + max_capstrlen];
1368 int first = 1;
1370 _dl_debug_printf (" search path=");
1372 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
1374 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
1375 size_t cnt;
1377 for (cnt = 0; cnt < ncapstr; ++cnt)
1378 if ((*list)->status[cnt] != nonexisting)
1380 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
1381 if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
1382 cp[0] = '\0';
1383 else
1384 cp[-1] = '\0';
1386 _dl_debug_printf_c (first ? "%s" : ":%s", buf);
1387 first = 0;
1390 ++list;
1393 if (name != NULL)
1394 _dl_debug_printf_c ("\t\t(%s from file %s)\n", what,
1395 name[0] ? name : rtld_progname);
1396 else
1397 _dl_debug_printf_c ("\t\t(%s)\n", what);
1400 /* Open a file and verify it is an ELF file for this architecture. We
1401 ignore only ELF files for other architectures. Non-ELF files and
1402 ELF files with different header information cause fatal errors since
1403 this could mean there is something wrong in the installation and the
1404 user might want to know about this. */
1405 static int
1406 open_verify (const char *name, struct filebuf *fbp)
1408 /* This is the expected ELF header. */
1409 #define ELF32_CLASS ELFCLASS32
1410 #define ELF64_CLASS ELFCLASS64
1411 #ifndef VALID_ELF_HEADER
1412 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
1413 # define VALID_ELF_OSABI(osabi) (osabi == ELFOSABI_SYSV)
1414 # define VALID_ELF_ABIVERSION(ver) (ver == 0)
1415 #endif
1416 static const unsigned char expected[EI_PAD] =
1418 [EI_MAG0] = ELFMAG0,
1419 [EI_MAG1] = ELFMAG1,
1420 [EI_MAG2] = ELFMAG2,
1421 [EI_MAG3] = ELFMAG3,
1422 [EI_CLASS] = ELFW(CLASS),
1423 [EI_DATA] = byteorder,
1424 [EI_VERSION] = EV_CURRENT,
1425 [EI_OSABI] = ELFOSABI_SYSV,
1426 [EI_ABIVERSION] = 0
1428 static const struct
1430 ElfW(Word) vendorlen;
1431 ElfW(Word) datalen;
1432 ElfW(Word) type;
1433 char vendor[4];
1434 } expected_note = { 4, 16, 1, "GNU" };
1435 int fd;
1436 /* Initialize it to make the compiler happy. */
1437 const char *errstring = NULL;
1438 int errval = 0;
1440 /* Open the file. We always open files read-only. */
1441 fd = __open (name, O_RDONLY);
1442 if (fd != -1)
1444 ElfW(Ehdr) *ehdr;
1445 ElfW(Phdr) *phdr, *ph;
1446 ElfW(Word) *abi_note, abi_note_buf[8];
1447 unsigned int osversion;
1448 size_t maplength;
1450 /* We successfully openened the file. Now verify it is a file
1451 we can use. */
1452 __set_errno (0);
1453 fbp->len = __libc_read (fd, fbp->buf, sizeof (fbp->buf));
1455 /* This is where the ELF header is loaded. */
1456 assert (sizeof (fbp->buf) > sizeof (ElfW(Ehdr)));
1457 ehdr = (ElfW(Ehdr) *) fbp->buf;
1459 /* Now run the tests. */
1460 if (__builtin_expect (fbp->len < (ssize_t) sizeof (ElfW(Ehdr)), 0))
1462 errval = errno;
1463 errstring = (errval == 0
1464 ? N_("file too short") : N_("cannot read file data"));
1465 call_lose:
1466 lose (errval, fd, name, NULL, NULL, errstring);
1469 /* See whether the ELF header is what we expect. */
1470 if (__builtin_expect (! VALID_ELF_HEADER (ehdr->e_ident, expected,
1471 EI_PAD), 0))
1473 /* Something is wrong. */
1474 if (*(Elf32_Word *) &ehdr->e_ident !=
1475 #if BYTE_ORDER == LITTLE_ENDIAN
1476 ((ELFMAG0 << (EI_MAG0 * 8)) |
1477 (ELFMAG1 << (EI_MAG1 * 8)) |
1478 (ELFMAG2 << (EI_MAG2 * 8)) |
1479 (ELFMAG3 << (EI_MAG3 * 8)))
1480 #else
1481 ((ELFMAG0 << (EI_MAG3 * 8)) |
1482 (ELFMAG1 << (EI_MAG2 * 8)) |
1483 (ELFMAG2 << (EI_MAG1 * 8)) |
1484 (ELFMAG3 << (EI_MAG0 * 8)))
1485 #endif
1487 errstring = N_("invalid ELF header");
1488 else if (ehdr->e_ident[EI_CLASS] != ELFW(CLASS))
1489 /* This is not a fatal error. On architectures where
1490 32-bit and 64-bit binaries can be run this might
1491 happen. */
1492 goto close_and_out;
1493 else if (ehdr->e_ident[EI_DATA] != byteorder)
1495 if (BYTE_ORDER == BIG_ENDIAN)
1496 errstring = N_("ELF file data encoding not big-endian");
1497 else
1498 errstring = N_("ELF file data encoding not little-endian");
1500 else if (ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1501 errstring
1502 = N_("ELF file version ident does not match current one");
1503 /* XXX We should be able so set system specific versions which are
1504 allowed here. */
1505 else if (!VALID_ELF_OSABI (ehdr->e_ident[EI_OSABI]))
1506 errstring = N_("ELF file OS ABI invalid");
1507 else if (!VALID_ELF_ABIVERSION (ehdr->e_ident[EI_ABIVERSION]))
1508 errstring = N_("ELF file ABI version invalid");
1509 else
1510 /* Otherwise we don't know what went wrong. */
1511 errstring = N_("internal error");
1513 goto call_lose;
1516 if (__builtin_expect (ehdr->e_version, EV_CURRENT) != EV_CURRENT)
1518 errstring = N_("ELF file version does not match current one");
1519 goto call_lose;
1521 if (! __builtin_expect (elf_machine_matches_host (ehdr), 1))
1522 goto close_and_out;
1523 else if (__builtin_expect (ehdr->e_type, ET_DYN) != ET_DYN
1524 && __builtin_expect (ehdr->e_type, ET_EXEC) != ET_EXEC)
1526 errstring = N_("only ET_DYN and ET_EXEC can be loaded");
1527 goto call_lose;
1529 else if (__builtin_expect (ehdr->e_phentsize, sizeof (ElfW(Phdr)))
1530 != sizeof (ElfW(Phdr)))
1532 errstring = N_("ELF file's phentsize not the expected size");
1533 goto call_lose;
1536 maplength = ehdr->e_phnum * sizeof (ElfW(Phdr));
1537 if (ehdr->e_phoff + maplength <= (size_t) fbp->len)
1538 phdr = (void *) (fbp->buf + ehdr->e_phoff);
1539 else
1541 phdr = alloca (maplength);
1542 __lseek (fd, ehdr->e_phoff, SEEK_SET);
1543 if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
1545 read_error:
1546 errval = errno;
1547 errstring = N_("cannot read file data");
1548 goto call_lose;
1552 /* Check .note.ABI-tag if present. */
1553 for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph)
1554 if (ph->p_type == PT_NOTE && ph->p_filesz == 32 && ph->p_align >= 4)
1556 if (ph->p_offset + 32 <= (size_t) fbp->len)
1557 abi_note = (void *) (fbp->buf + ph->p_offset);
1558 else
1560 __lseek (fd, ph->p_offset, SEEK_SET);
1561 if (__libc_read (fd, (void *) abi_note_buf, 32) != 32)
1562 goto read_error;
1564 abi_note = abi_note_buf;
1567 if (memcmp (abi_note, &expected_note, sizeof (expected_note)))
1568 continue;
1570 osversion = (abi_note[5] & 0xff) * 65536
1571 + (abi_note[6] & 0xff) * 256
1572 + (abi_note[7] & 0xff);
1573 if (abi_note[4] != __ABI_TAG_OS
1574 || (GLRO(dl_osversion) && GLRO(dl_osversion) < osversion))
1576 close_and_out:
1577 __close (fd);
1578 __set_errno (ENOENT);
1579 fd = -1;
1582 break;
1586 return fd;
1589 /* Try to open NAME in one of the directories in *DIRSP.
1590 Return the fd, or -1. If successful, fill in *REALNAME
1591 with the malloc'd full directory name. If it turns out
1592 that none of the directories in *DIRSP exists, *DIRSP is
1593 replaced with (void *) -1, and the old value is free()d
1594 if MAY_FREE_DIRS is true. */
1596 static int
1597 open_path (const char *name, size_t namelen, int preloaded,
1598 struct r_search_path_struct *sps, char **realname,
1599 struct filebuf *fbp)
1601 struct r_search_path_elem **dirs = sps->dirs;
1602 char *buf;
1603 int fd = -1;
1604 const char *current_what = NULL;
1605 int any = 0;
1607 buf = alloca (max_dirnamelen + max_capstrlen + namelen);
1610 struct r_search_path_elem *this_dir = *dirs;
1611 size_t buflen = 0;
1612 size_t cnt;
1613 char *edp;
1614 int here_any = 0;
1615 int err;
1617 /* If we are debugging the search for libraries print the path
1618 now if it hasn't happened now. */
1619 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0)
1620 && current_what != this_dir->what)
1622 current_what = this_dir->what;
1623 print_search_path (dirs, current_what, this_dir->where);
1626 edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1627 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1629 /* Skip this directory if we know it does not exist. */
1630 if (this_dir->status[cnt] == nonexisting)
1631 continue;
1633 buflen =
1634 ((char *) __mempcpy (__mempcpy (edp, capstr[cnt].str,
1635 capstr[cnt].len),
1636 name, namelen)
1637 - buf);
1639 /* Print name we try if this is wanted. */
1640 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1641 _dl_debug_printf (" trying file=%s\n", buf);
1643 fd = open_verify (buf, fbp);
1644 if (this_dir->status[cnt] == unknown)
1646 if (fd != -1)
1647 this_dir->status[cnt] = existing;
1648 else
1650 /* We failed to open machine dependent library. Let's
1651 test whether there is any directory at all. */
1652 struct stat64 st;
1654 buf[buflen - namelen - 1] = '\0';
1656 if (__xstat64 (_STAT_VER, buf, &st) != 0
1657 || ! S_ISDIR (st.st_mode))
1658 /* The directory does not exist or it is no directory. */
1659 this_dir->status[cnt] = nonexisting;
1660 else
1661 this_dir->status[cnt] = existing;
1665 /* Remember whether we found any existing directory. */
1666 here_any |= this_dir->status[cnt] == existing;
1668 if (fd != -1 && __builtin_expect (preloaded, 0)
1669 && INTUSE(__libc_enable_secure))
1671 /* This is an extra security effort to make sure nobody can
1672 preload broken shared objects which are in the trusted
1673 directories and so exploit the bugs. */
1674 struct stat64 st;
1676 if (__fxstat64 (_STAT_VER, fd, &st) != 0
1677 || (st.st_mode & S_ISUID) == 0)
1679 /* The shared object cannot be tested for being SUID
1680 or this bit is not set. In this case we must not
1681 use this object. */
1682 __close (fd);
1683 fd = -1;
1684 /* We simply ignore the file, signal this by setting
1685 the error value which would have been set by `open'. */
1686 errno = ENOENT;
1691 if (fd != -1)
1693 *realname = (char *) malloc (buflen);
1694 if (*realname != NULL)
1696 memcpy (*realname, buf, buflen);
1697 return fd;
1699 else
1701 /* No memory for the name, we certainly won't be able
1702 to load and link it. */
1703 __close (fd);
1704 return -1;
1707 if (here_any && (err = errno) != ENOENT && err != EACCES)
1708 /* The file exists and is readable, but something went wrong. */
1709 return -1;
1711 /* Remember whether we found anything. */
1712 any |= here_any;
1714 while (*++dirs != NULL);
1716 /* Remove the whole path if none of the directories exists. */
1717 if (__builtin_expect (! any, 0))
1719 /* Paths which were allocated using the minimal malloc() in ld.so
1720 must not be freed using the general free() in libc. */
1721 if (sps->malloced)
1722 free (sps->dirs);
1723 sps->dirs = (void *) -1;
1726 return -1;
1729 /* Map in the shared object file NAME. */
1731 struct link_map *
1732 internal_function
1733 _dl_map_object (struct link_map *loader, const char *name, int preloaded,
1734 int type, int trace_mode, int mode)
1736 int fd;
1737 char *realname;
1738 char *name_copy;
1739 struct link_map *l;
1740 struct filebuf fb;
1742 /* Look for this name among those already loaded. */
1743 for (l = GL(dl_loaded); l; l = l->l_next)
1745 /* If the requested name matches the soname of a loaded object,
1746 use that object. Elide this check for names that have not
1747 yet been opened. */
1748 if (__builtin_expect (l->l_faked, 0) != 0)
1749 continue;
1750 if (!_dl_name_match_p (name, l))
1752 const char *soname;
1754 if (__builtin_expect (l->l_soname_added, 1)
1755 || l->l_info[DT_SONAME] == NULL)
1756 continue;
1758 soname = ((const char *) D_PTR (l, l_info[DT_STRTAB])
1759 + l->l_info[DT_SONAME]->d_un.d_val);
1760 if (strcmp (name, soname) != 0)
1761 continue;
1763 /* We have a match on a new name -- cache it. */
1764 add_name_to_object (l, soname);
1765 l->l_soname_added = 1;
1768 /* We have a match. */
1769 return l;
1772 /* Display information if we are debugging. */
1773 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0)
1774 && loader != NULL)
1775 _dl_debug_printf ("\nfile=%s; needed by %s\n", name,
1776 loader->l_name[0]
1777 ? loader->l_name : rtld_progname);
1779 if (strchr (name, '/') == NULL)
1781 /* Search for NAME in several places. */
1783 size_t namelen = strlen (name) + 1;
1785 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1786 _dl_debug_printf ("find library=%s; searching\n", name);
1788 fd = -1;
1790 /* When the object has the RUNPATH information we don't use any
1791 RPATHs. */
1792 if (loader == NULL || loader->l_info[DT_RUNPATH] == NULL)
1794 /* First try the DT_RPATH of the dependent object that caused NAME
1795 to be loaded. Then that object's dependent, and on up. */
1796 for (l = loader; fd == -1 && l; l = l->l_loader)
1797 if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
1798 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1799 &realname, &fb);
1801 /* If dynamically linked, try the DT_RPATH of the executable
1802 itself. */
1803 l = GL(dl_loaded);
1804 if (fd == -1 && l && l->l_type != lt_loaded && l != loader
1805 && l->l_rpath_dirs.dirs != (void *) -1)
1806 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1807 &realname, &fb);
1810 /* Try the LD_LIBRARY_PATH environment variable. */
1811 if (fd == -1 && env_path_list.dirs != (void *) -1)
1812 fd = open_path (name, namelen, preloaded, &env_path_list,
1813 &realname, &fb);
1815 /* Look at the RUNPATH information for this binary. */
1816 if (fd == -1 && loader != NULL
1817 && cache_rpath (loader, &loader->l_runpath_dirs,
1818 DT_RUNPATH, "RUNPATH"))
1819 fd = open_path (name, namelen, preloaded,
1820 &loader->l_runpath_dirs, &realname, &fb);
1822 if (fd == -1
1823 && (__builtin_expect (! preloaded, 1)
1824 || ! INTUSE(__libc_enable_secure)))
1826 /* Check the list of libraries in the file /etc/ld.so.cache,
1827 for compatibility with Linux's ldconfig program. */
1828 const char *cached = _dl_load_cache_lookup (name);
1830 if (cached != NULL)
1832 #ifdef SHARED
1833 l = loader ?: GL(dl_loaded);
1834 #else
1835 l = loader;
1836 #endif
1838 /* If the loader has the DF_1_NODEFLIB flag set we must not
1839 use a cache entry from any of these directories. */
1840 if (
1841 #ifndef SHARED
1842 /* 'l' is always != NULL for dynamically linked objects. */
1843 l != NULL &&
1844 #endif
1845 __builtin_expect (l->l_flags_1 & DF_1_NODEFLIB, 0))
1847 const char *dirp = system_dirs;
1848 unsigned int cnt = 0;
1852 if (memcmp (cached, dirp, system_dirs_len[cnt]) == 0)
1854 /* The prefix matches. Don't use the entry. */
1855 cached = NULL;
1856 break;
1859 dirp += system_dirs_len[cnt] + 1;
1860 ++cnt;
1862 while (cnt < nsystem_dirs_len);
1865 if (cached != NULL)
1867 fd = open_verify (cached, &fb);
1868 if (__builtin_expect (fd != -1, 1))
1870 realname = local_strdup (cached);
1871 if (realname == NULL)
1873 __close (fd);
1874 fd = -1;
1881 /* Finally, try the default path. */
1882 if (fd == -1
1883 && ((l = loader ?: GL(dl_loaded)) == NULL
1884 || __builtin_expect (!(l->l_flags_1 & DF_1_NODEFLIB), 1))
1885 && rtld_search_dirs.dirs != (void *) -1)
1886 fd = open_path (name, namelen, preloaded, &rtld_search_dirs,
1887 &realname, &fb);
1889 /* Add another newline when we are tracing the library loading. */
1890 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1891 _dl_debug_printf ("\n");
1893 else
1895 /* The path may contain dynamic string tokens. */
1896 realname = (loader
1897 ? expand_dynamic_string_token (loader, name)
1898 : local_strdup (name));
1899 if (realname == NULL)
1900 fd = -1;
1901 else
1903 fd = open_verify (realname, &fb);
1904 if (__builtin_expect (fd, 0) == -1)
1905 free (realname);
1909 if (__builtin_expect (fd, 0) == -1)
1911 if (trace_mode
1912 && __builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK, 0) == 0)
1914 /* We haven't found an appropriate library. But since we
1915 are only interested in the list of libraries this isn't
1916 so severe. Fake an entry with all the information we
1917 have. */
1918 static const Elf_Symndx dummy_bucket = STN_UNDEF;
1920 /* Enter the new object in the list of loaded objects. */
1921 if ((name_copy = local_strdup (name)) == NULL
1922 || (l = _dl_new_object (name_copy, name, type, loader)) == NULL)
1923 _dl_signal_error (ENOMEM, name, NULL,
1924 N_("cannot create shared object descriptor"));
1925 /* Signal that this is a faked entry. */
1926 l->l_faked = 1;
1927 /* Since the descriptor is initialized with zero we do not
1928 have do this here.
1929 l->l_reserved = 0; */
1930 l->l_buckets = &dummy_bucket;
1931 l->l_nbuckets = 1;
1932 l->l_relocated = 1;
1934 return l;
1936 else
1937 _dl_signal_error (errno, name, NULL,
1938 N_("cannot open shared object file"));
1941 void *stack_end = __libc_stack_end;
1942 return _dl_map_object_from_fd (name, fd, &fb, realname, loader, type, mode,
1943 &stack_end);
1947 void
1948 internal_function
1949 _dl_rtld_di_serinfo (struct link_map *loader, Dl_serinfo *si, bool counting)
1951 if (counting)
1953 si->dls_cnt = 0;
1954 si->dls_size = 0;
1957 unsigned int idx = 0;
1958 char *allocptr = (char *) &si->dls_serpath[si->dls_cnt];
1959 void add_path (const struct r_search_path_struct *sps, unsigned int flags)
1960 # define add_path(sps, flags) add_path(sps, 0) /* XXX */
1962 if (sps->dirs != (void *) -1)
1964 struct r_search_path_elem **dirs = sps->dirs;
1967 const struct r_search_path_elem *const r = *dirs++;
1968 if (counting)
1970 si->dls_cnt++;
1971 si->dls_size += r->dirnamelen;
1973 else
1975 Dl_serpath *const sp = &si->dls_serpath[idx++];
1976 sp->dls_name = allocptr;
1977 allocptr = __mempcpy (allocptr,
1978 r->dirname, r->dirnamelen - 1);
1979 *allocptr++ = '\0';
1980 sp->dls_flags = flags;
1983 while (*dirs != NULL);
1987 /* When the object has the RUNPATH information we don't use any RPATHs. */
1988 if (loader->l_info[DT_RUNPATH] == NULL)
1990 /* First try the DT_RPATH of the dependent object that caused NAME
1991 to be loaded. Then that object's dependent, and on up. */
1993 struct link_map *l = loader;
1996 if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
1997 add_path (&l->l_rpath_dirs, XXX_RPATH);
1998 l = l->l_loader;
2000 while (l != NULL);
2002 /* If dynamically linked, try the DT_RPATH of the executable itself. */
2003 l = GL(dl_loaded);
2004 if (l != NULL && l->l_type != lt_loaded && l != loader)
2005 if (cache_rpath (l, &l->l_rpath_dirs, DT_RPATH, "RPATH"))
2006 add_path (&l->l_rpath_dirs, XXX_RPATH);
2009 /* Try the LD_LIBRARY_PATH environment variable. */
2010 add_path (&env_path_list, XXX_ENV);
2012 /* Look at the RUNPATH information for this binary. */
2013 if (cache_rpath (loader, &loader->l_runpath_dirs, DT_RUNPATH, "RUNPATH"))
2014 add_path (&loader->l_runpath_dirs, XXX_RUNPATH);
2016 /* XXX
2017 Here is where ld.so.cache gets checked, but we don't have
2018 a way to indicate that in the results for Dl_serinfo. */
2020 /* Finally, try the default path. */
2021 if (!(loader->l_flags_1 & DF_1_NODEFLIB))
2022 add_path (&rtld_search_dirs, XXX_default);
2024 if (counting)
2025 /* Count the struct size before the string area, which we didn't
2026 know before we completed dls_cnt. */
2027 si->dls_size += (char *) &si->dls_serpath[si->dls_cnt] - (char *) si;