Use INTERNAL_SYSCALL.
[glibc.git] / elf / dl-load.c
blob9d9ba945398617307ec93c675154b16d1dbe881c
1 /* Map in a shared object's segments from the file.
2 Copyright (C) 1995,96,97,98,99,2000,2001,2002 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 <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 <dl-osinfo.h>
37 #include <dl-dst.h>
39 /* On some systems, no flag bits are given to specify file mapping. */
40 #ifndef MAP_FILE
41 # define MAP_FILE 0
42 #endif
44 /* The right way to map in the shared library files is MAP_COPY, which
45 makes a virtual copy of the data at the time of the mmap call; this
46 guarantees the mapped pages will be consistent even if the file is
47 overwritten. Some losing VM systems like Linux's lack MAP_COPY. All we
48 get is MAP_PRIVATE, which copies each page when it is modified; this
49 means if the file is overwritten, we may at some point get some pages
50 from the new version after starting with pages from the old version. */
51 #ifndef MAP_COPY
52 # define MAP_COPY MAP_PRIVATE
53 #endif
55 /* Some systems link their relocatable objects for another base address
56 than 0. We want to know the base address for these such that we can
57 subtract this address from the segment addresses during mapping.
58 This results in a more efficient address space usage. Defaults to
59 zero for almost all systems. */
60 #ifndef MAP_BASE_ADDR
61 # define MAP_BASE_ADDR(l) 0
62 #endif
65 #include <endian.h>
66 #if BYTE_ORDER == BIG_ENDIAN
67 # define byteorder ELFDATA2MSB
68 #elif BYTE_ORDER == LITTLE_ENDIAN
69 # define byteorder ELFDATA2LSB
70 #else
71 # error "Unknown BYTE_ORDER " BYTE_ORDER
72 # define byteorder ELFDATANONE
73 #endif
75 #define STRING(x) __STRING (x)
77 #ifdef MAP_ANON
78 /* The fd is not examined when using MAP_ANON. */
79 # define ANONFD -1
80 #else
81 int _dl_zerofd = -1;
82 # define ANONFD _dl_zerofd
83 #endif
85 /* Handle situations where we have a preferred location in memory for
86 the shared objects. */
87 #ifdef ELF_PREFERRED_ADDRESS_DATA
88 ELF_PREFERRED_ADDRESS_DATA;
89 #endif
90 #ifndef ELF_PREFERRED_ADDRESS
91 # define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
92 #endif
93 #ifndef ELF_FIXED_ADDRESS
94 # define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
95 #endif
97 /* Type for the buffer we put the ELF header and hopefully the program
98 header. This buffer does not really have to be too large. In most
99 cases the program header follows the ELF header directly. If this
100 is not the case all bets are off and we can make the header arbitrarily
101 large and still won't get it read. This means the only question is
102 how large are the ELF and program header combined. The ELF header
103 in 64-bit files is 56 bytes long. Each program header entry is again
104 56 bytes long. I.e., even with a file which has 17 program header
105 entries we only have to read 1kB. And 17 program header entries is
106 plenty, normal files have < 10. If this heuristic should really fail
107 for some file the code in `_dl_map_object_from_fd' knows how to
108 recover. */
109 struct filebuf
111 ssize_t len;
112 char buf[1024] __attribute__ ((aligned (__alignof (ElfW(Ehdr)))));
115 /* This is the decomposed LD_LIBRARY_PATH search path. */
116 static struct r_search_path_struct env_path_list;
118 /* List of the hardware capabilities we might end up using. */
119 static const struct r_strlenpair *capstr;
120 static size_t ncapstr;
121 static size_t max_capstrlen;
124 /* Get the generated information about the trusted directories. */
125 #include "trusted-dirs.h"
127 static const char system_dirs[] = SYSTEM_DIRS;
128 static const size_t system_dirs_len[] =
130 SYSTEM_DIRS_LEN
132 #define nsystem_dirs_len \
133 (sizeof (system_dirs_len) / sizeof (system_dirs_len[0]))
136 /* Local version of `strdup' function. */
137 static inline char *
138 local_strdup (const char *s)
140 size_t len = strlen (s) + 1;
141 void *new = malloc (len);
143 if (new == NULL)
144 return NULL;
146 return (char *) memcpy (new, s, len);
150 static size_t
151 is_dst (const char *start, const char *name, const char *str,
152 int is_path, int secure)
154 size_t len;
155 bool is_curly = false;
157 if (name[0] == '{')
159 is_curly = true;
160 ++name;
163 len = 0;
164 while (name[len] == str[len] && name[len] != '\0')
165 ++len;
167 if (is_curly)
169 if (name[len] != '}')
170 return 0;
172 /* Point again at the beginning of the name. */
173 --name;
174 /* Skip over closing curly brace and adjust for the --name. */
175 len += 2;
177 else if (name[len] != '\0' && name[len] != '/'
178 && (!is_path || name[len] != ':'))
179 return 0;
181 if (__builtin_expect (secure, 0)
182 && ((name[len] != '\0' && (!is_path || name[len] != ':'))
183 || (name != start + 1 && (!is_path || name[-2] != ':'))))
184 return 0;
186 return len;
190 size_t
191 _dl_dst_count (const char *name, int is_path)
193 const char *const start = name;
194 size_t cnt = 0;
198 size_t len;
200 /* $ORIGIN is not expanded for SUID/GUID programs (except if it
201 is $ORIGIN alone) and it must always appear first in path. */
202 ++name;
203 if ((len = is_dst (start, name, "ORIGIN", is_path,
204 INTUSE(__libc_enable_secure))) != 0
205 || (len = is_dst (start, name, "PLATFORM", is_path, 0)) != 0
206 || (len = is_dst (start, name, "LIB", is_path, 0)) != 0)
207 ++cnt;
209 name = strchr (name + len, '$');
211 while (name != NULL);
213 return cnt;
215 INTDEF (_dl_dst_count)
218 char *
219 _dl_dst_substitute (struct link_map *l, const char *name, char *result,
220 int is_path)
222 const char *const start = name;
223 char *last_elem, *wp;
225 /* Now fill the result path. While copying over the string we keep
226 track of the start of the last path element. When we come accross
227 a DST we copy over the value or (if the value is not available)
228 leave the entire path element out. */
229 last_elem = wp = result;
233 if (__builtin_expect (*name == '$', 0))
235 const char *repl = NULL;
236 size_t len;
238 ++name;
239 if ((len = is_dst (start, name, "ORIGIN", is_path,
240 INTUSE(__libc_enable_secure))) != 0)
241 repl = l->l_origin;
242 else if ((len = is_dst (start, name, "PLATFORM", is_path, 0)) != 0)
243 repl = GL(dl_platform);
244 else if ((len = is_dst (start, name, "LIB", is_path, 0)) != 0)
245 repl = DL_DST_LIB;
247 if (repl != NULL && repl != (const char *) -1)
249 wp = __stpcpy (wp, repl);
250 name += len;
252 else if (len > 1)
254 /* We cannot use this path element, the value of the
255 replacement is unknown. */
256 wp = last_elem;
257 name += len;
258 while (*name != '\0' && (!is_path || *name != ':'))
259 ++name;
261 else
262 /* No DST we recognize. */
263 *wp++ = '$';
265 else
267 *wp++ = *name++;
268 if (is_path && *name == ':')
269 last_elem = wp;
272 while (*name != '\0');
274 *wp = '\0';
276 return result;
278 INTDEF (_dl_dst_substitute)
281 /* Return copy of argument with all recognized dynamic string tokens
282 ($ORIGIN and $PLATFORM for now) replaced. On some platforms it
283 might not be possible to determine the path from which the object
284 belonging to the map is loaded. In this case the path element
285 containing $ORIGIN is left out. */
286 static char *
287 expand_dynamic_string_token (struct link_map *l, const char *s)
289 /* We make two runs over the string. First we determine how large the
290 resulting string is and then we copy it over. Since this is now
291 frequently executed operation we are looking here not for performance
292 but rather for code size. */
293 size_t cnt;
294 size_t total;
295 char *result;
297 /* Determine the number of DST elements. */
298 cnt = DL_DST_COUNT (s, 1);
300 /* If we do not have to replace anything simply copy the string. */
301 if (__builtin_expect (cnt, 0) == 0)
302 return local_strdup (s);
304 /* Determine the length of the substituted string. */
305 total = DL_DST_REQUIRED (l, s, strlen (s), cnt);
307 /* Allocate the necessary memory. */
308 result = (char *) malloc (total + 1);
309 if (result == NULL)
310 return NULL;
312 return INTUSE(_dl_dst_substitute) (l, s, result, 1);
316 /* Add `name' to the list of names for a particular shared object.
317 `name' is expected to have been allocated with malloc and will
318 be freed if the shared object already has this name.
319 Returns false if the object already had this name. */
320 static void
321 internal_function
322 add_name_to_object (struct link_map *l, const char *name)
324 struct libname_list *lnp, *lastp;
325 struct libname_list *newname;
326 size_t name_len;
328 lastp = NULL;
329 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
330 if (strcmp (name, lnp->name) == 0)
331 return;
333 name_len = strlen (name) + 1;
334 newname = (struct libname_list *) malloc (sizeof *newname + name_len);
335 if (newname == NULL)
337 /* No more memory. */
338 INTUSE(_dl_signal_error) (ENOMEM, name, NULL,
339 N_("cannot allocate name record"));
340 return;
342 /* The object should have a libname set from _dl_new_object. */
343 assert (lastp != NULL);
345 newname->name = memcpy (newname + 1, name, name_len);
346 newname->next = NULL;
347 newname->dont_free = 0;
348 lastp->next = newname;
351 /* Standard search directories. */
352 static struct r_search_path_struct rtld_search_dirs;
354 static size_t max_dirnamelen;
356 static inline struct r_search_path_elem **
357 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
358 int check_trusted, const char *what, const char *where)
360 char *cp;
361 size_t nelems = 0;
363 while ((cp = __strsep (&rpath, sep)) != NULL)
365 struct r_search_path_elem *dirp;
366 size_t len = strlen (cp);
368 /* `strsep' can pass an empty string. This has to be
369 interpreted as `use the current directory'. */
370 if (len == 0)
372 static const char curwd[] = "./";
373 cp = (char *) curwd;
376 /* Remove trailing slashes (except for "/"). */
377 while (len > 1 && cp[len - 1] == '/')
378 --len;
380 /* Now add one if there is none so far. */
381 if (len > 0 && cp[len - 1] != '/')
382 cp[len++] = '/';
384 /* Make sure we don't use untrusted directories if we run SUID. */
385 if (__builtin_expect (check_trusted, 0))
387 const char *trun = system_dirs;
388 size_t idx;
389 int unsecure = 1;
391 /* All trusted directories must be complete names. */
392 if (cp[0] == '/')
394 for (idx = 0; idx < nsystem_dirs_len; ++idx)
396 if (len == system_dirs_len[idx]
397 && memcmp (trun, cp, len) == 0)
399 /* Found it. */
400 unsecure = 0;
401 break;
404 trun += system_dirs_len[idx] + 1;
408 if (unsecure)
409 /* Simply drop this directory. */
410 continue;
413 /* See if this directory is already known. */
414 for (dirp = GL(dl_all_dirs); dirp != NULL; dirp = dirp->next)
415 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
416 break;
418 if (dirp != NULL)
420 /* It is available, see whether it's on our own list. */
421 size_t cnt;
422 for (cnt = 0; cnt < nelems; ++cnt)
423 if (result[cnt] == dirp)
424 break;
426 if (cnt == nelems)
427 result[nelems++] = dirp;
429 else
431 size_t cnt;
432 enum r_dir_status init_val;
433 size_t where_len = where ? strlen (where) + 1 : 0;
435 /* It's a new directory. Create an entry and add it. */
436 dirp = (struct r_search_path_elem *)
437 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status)
438 + where_len + len + 1);
439 if (dirp == NULL)
440 INTUSE(_dl_signal_error) (ENOMEM, NULL, NULL,
441 N_("cannot create cache for search path"));
443 dirp->dirname = ((char *) dirp + sizeof (*dirp)
444 + ncapstr * sizeof (enum r_dir_status));
445 *((char *) __mempcpy ((char *) dirp->dirname, cp, len)) = '\0';
446 dirp->dirnamelen = len;
448 if (len > max_dirnamelen)
449 max_dirnamelen = len;
451 /* We have to make sure all the relative directories are
452 never ignored. The current directory might change and
453 all our saved information would be void. */
454 init_val = cp[0] != '/' ? existing : unknown;
455 for (cnt = 0; cnt < ncapstr; ++cnt)
456 dirp->status[cnt] = init_val;
458 dirp->what = what;
459 if (__builtin_expect (where != NULL, 1))
460 dirp->where = memcpy ((char *) dirp + sizeof (*dirp) + len + 1
461 + (ncapstr * sizeof (enum r_dir_status)),
462 where, where_len);
463 else
464 dirp->where = NULL;
466 dirp->next = GL(dl_all_dirs);
467 GL(dl_all_dirs) = dirp;
469 /* Put it in the result array. */
470 result[nelems++] = dirp;
474 /* Terminate the array. */
475 result[nelems] = NULL;
477 return result;
481 static void
482 internal_function
483 decompose_rpath (struct r_search_path_struct *sps,
484 const char *rpath, struct link_map *l, const char *what)
486 /* Make a copy we can work with. */
487 const char *where = l->l_name;
488 char *copy;
489 char *cp;
490 struct r_search_path_elem **result;
491 size_t nelems;
492 /* Initialize to please the compiler. */
493 const char *errstring = NULL;
495 /* First see whether we must forget the RUNPATH and RPATH from this
496 object. */
497 if (__builtin_expect (GL(dl_inhibit_rpath) != NULL, 0)
498 && !INTUSE(__libc_enable_secure))
500 const char *inhp = GL(dl_inhibit_rpath);
504 const char *wp = where;
506 while (*inhp == *wp && *wp != '\0')
508 ++inhp;
509 ++wp;
512 if (*wp == '\0' && (*inhp == '\0' || *inhp == ':'))
514 /* This object is on the list of objects for which the
515 RUNPATH and RPATH must not be used. */
516 result = calloc (1, sizeof *result);
517 if (result == NULL)
519 signal_error_cache:
520 errstring = N_("cannot create cache for search path");
521 signal_error:
522 INTUSE(_dl_signal_error) (ENOMEM, NULL, NULL, errstring);
525 sps->dirs = result;
526 sps->malloced = 1;
528 return;
531 while (*inhp != '\0')
532 if (*inhp++ == ':')
533 break;
535 while (*inhp != '\0');
538 /* Make a writable copy. At the same time expand possible dynamic
539 string tokens. */
540 copy = expand_dynamic_string_token (l, rpath);
541 if (copy == NULL)
543 errstring = N_("cannot create RUNPATH/RPATH copy");
544 goto signal_error;
547 /* Count the number of necessary elements in the result array. */
548 nelems = 0;
549 for (cp = copy; *cp != '\0'; ++cp)
550 if (*cp == ':')
551 ++nelems;
553 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
554 number of necessary entries. */
555 result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
556 * sizeof (*result));
557 if (result == NULL)
558 goto signal_error_cache;
560 fillin_rpath (copy, result, ":", 0, what, where);
562 /* Free the copied RPATH string. `fillin_rpath' make own copies if
563 necessary. */
564 free (copy);
566 sps->dirs = result;
567 /* The caller will change this value if we haven't used a real malloc. */
568 sps->malloced = 1;
572 void
573 internal_function
574 _dl_init_paths (const char *llp)
576 size_t idx;
577 const char *strp;
578 struct r_search_path_elem *pelem, **aelem;
579 size_t round_size;
580 #ifdef SHARED
581 struct link_map *l;
582 #endif
583 /* Initialize to please the compiler. */
584 const char *errstring = NULL;
586 /* Fill in the information about the application's RPATH and the
587 directories addressed by the LD_LIBRARY_PATH environment variable. */
589 /* Get the capabilities. */
590 capstr = _dl_important_hwcaps (GL(dl_platform), GL(dl_platformlen),
591 &ncapstr, &max_capstrlen);
593 /* First set up the rest of the default search directory entries. */
594 aelem = rtld_search_dirs.dirs = (struct r_search_path_elem **)
595 malloc ((nsystem_dirs_len + 1) * sizeof (struct r_search_path_elem *));
596 if (rtld_search_dirs.dirs == NULL)
598 errstring = N_("cannot create search path array");
599 signal_error:
600 INTUSE(_dl_signal_error) (ENOMEM, NULL, NULL, errstring);
603 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
604 + ncapstr * sizeof (enum r_dir_status))
605 / sizeof (struct r_search_path_elem));
607 rtld_search_dirs.dirs[0] = (struct r_search_path_elem *)
608 malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]))
609 * round_size * sizeof (struct r_search_path_elem));
610 if (rtld_search_dirs.dirs[0] == NULL)
612 errstring = N_("cannot create cache for search path");
613 goto signal_error;
616 rtld_search_dirs.malloced = 0;
617 pelem = GL(dl_all_dirs) = rtld_search_dirs.dirs[0];
618 strp = system_dirs;
619 idx = 0;
623 size_t cnt;
625 *aelem++ = pelem;
627 pelem->what = "system search path";
628 pelem->where = NULL;
630 pelem->dirname = strp;
631 pelem->dirnamelen = system_dirs_len[idx];
632 strp += system_dirs_len[idx] + 1;
634 /* System paths must be absolute. */
635 assert (pelem->dirname[0] == '/');
636 for (cnt = 0; cnt < ncapstr; ++cnt)
637 pelem->status[cnt] = unknown;
639 pelem->next = (++idx == nsystem_dirs_len ? NULL : (pelem + round_size));
641 pelem += round_size;
643 while (idx < nsystem_dirs_len);
645 max_dirnamelen = SYSTEM_DIRS_MAX_LEN;
646 *aelem = NULL;
648 #ifdef SHARED
649 /* This points to the map of the main object. */
650 l = GL(dl_loaded);
651 if (l != NULL)
653 assert (l->l_type != lt_loaded);
655 if (l->l_info[DT_RUNPATH])
657 /* Allocate room for the search path and fill in information
658 from RUNPATH. */
659 decompose_rpath (&l->l_runpath_dirs,
660 (const void *) (D_PTR (l, l_info[DT_STRTAB])
661 + l->l_info[DT_RUNPATH]->d_un.d_val),
662 l, "RUNPATH");
664 /* The RPATH is ignored. */
665 l->l_rpath_dirs.dirs = (void *) -1;
667 else
669 l->l_runpath_dirs.dirs = (void *) -1;
671 if (l->l_info[DT_RPATH])
673 /* Allocate room for the search path and fill in information
674 from RPATH. */
675 decompose_rpath (&l->l_rpath_dirs,
676 (const void *) (D_PTR (l, l_info[DT_STRTAB])
677 + l->l_info[DT_RPATH]->d_un.d_val),
678 l, "RPATH");
679 l->l_rpath_dirs.malloced = 0;
681 else
682 l->l_rpath_dirs.dirs = (void *) -1;
685 #endif /* SHARED */
687 if (llp != NULL && *llp != '\0')
689 size_t nllp;
690 const char *cp = llp;
691 char *llp_tmp = strdupa (llp);
693 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
694 elements it has. */
695 nllp = 1;
696 while (*cp)
698 if (*cp == ':' || *cp == ';')
699 ++nllp;
700 ++cp;
703 env_path_list.dirs = (struct r_search_path_elem **)
704 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
705 if (env_path_list.dirs == NULL)
707 errstring = N_("cannot create cache for search path");
708 goto signal_error;
711 (void) fillin_rpath (llp_tmp, env_path_list.dirs, ":;",
712 INTUSE(__libc_enable_secure), "LD_LIBRARY_PATH",
713 NULL);
715 if (env_path_list.dirs[0] == NULL)
717 free (env_path_list.dirs);
718 env_path_list.dirs = (void *) -1;
721 env_path_list.malloced = 0;
723 else
724 env_path_list.dirs = (void *) -1;
726 /* Remember the last search directory added at startup. */
727 GL(dl_init_all_dirs) = GL(dl_all_dirs);
731 /* Think twice before changing anything in this function. It is placed
732 here and prepared using the `alloca' magic to prevent it from being
733 inlined. The function is only called in case of an error. But then
734 performance does not count. The function used to be "inlinable" and
735 the compiled did so all the time. This increased the code size for
736 absolutely no good reason. */
737 static void
738 __attribute__ ((noreturn))
739 lose (int code, int fd, const char *name, char *realname, struct link_map *l,
740 const char *msg)
742 /* The use of `alloca' here looks ridiculous but it helps. The goal
743 is to avoid the function from being inlined. There is no official
744 way to do this so we use this trick. gcc never inlines functions
745 which use `alloca'. */
746 int *a = (int *) alloca (sizeof (int));
747 a[0] = fd;
748 /* The file might already be closed. */
749 if (a[0] != -1)
750 (void) __close (a[0]);
751 if (l != NULL)
753 /* Remove the stillborn object from the list and free it. */
754 assert (l->l_next == NULL);
755 if (l->l_prev == NULL)
756 /* No other module loaded. This happens only in the static library,
757 or in rtld under --verify. */
758 GL(dl_loaded) = NULL;
759 else
760 l->l_prev->l_next = NULL;
761 --GL(dl_nloaded);
762 free (l);
764 free (realname);
765 INTUSE(_dl_signal_error) (code, name, NULL, msg);
769 /* Map in the shared object NAME, actually located in REALNAME, and already
770 opened on FD. */
772 #ifndef EXTERNAL_MAP_FROM_FD
773 static
774 #endif
775 struct link_map *
776 _dl_map_object_from_fd (const char *name, int fd, struct filebuf *fbp,
777 char *realname, struct link_map *loader, int l_type,
778 int mode)
780 struct link_map *l = NULL;
781 const ElfW(Ehdr) *header;
782 const ElfW(Phdr) *phdr;
783 const ElfW(Phdr) *ph;
784 size_t maplength;
785 int type;
786 struct stat64 st;
787 /* Initialize to keep the compiler happy. */
788 const char *errstring = NULL;
789 int errval = 0;
791 /* Get file information. */
792 if (__builtin_expect (__fxstat64 (_STAT_VER, fd, &st) < 0, 0))
794 errstring = N_("cannot stat shared object");
795 call_lose_errno:
796 errval = errno;
797 call_lose:
798 lose (errval, fd, name, realname, l, errstring);
801 /* Look again to see if the real name matched another already loaded. */
802 for (l = GL(dl_loaded); l; l = l->l_next)
803 if (l->l_ino == st.st_ino && l->l_dev == st.st_dev)
805 /* The object is already loaded.
806 Just bump its reference count and return it. */
807 __close (fd);
809 /* If the name is not in the list of names for this object add
810 it. */
811 free (realname);
812 add_name_to_object (l, name);
814 return l;
817 if (mode & RTLD_NOLOAD)
818 /* We are not supposed to load the object unless it is already
819 loaded. So return now. */
820 return NULL;
822 /* Print debugging message. */
823 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0))
824 INTUSE(_dl_debug_printf) ("file=%s; generating link map\n", name);
826 /* This is the ELF header. We read it in `open_verify'. */
827 header = (void *) fbp->buf;
829 #ifndef MAP_ANON
830 # define MAP_ANON 0
831 if (_dl_zerofd == -1)
833 _dl_zerofd = _dl_sysdep_open_zero_fill ();
834 if (_dl_zerofd == -1)
836 __close (fd);
837 INTUSE(_dl_signal_error) (errno, NULL, NULL,
838 N_("cannot open zero fill device"));
841 #endif
843 /* Enter the new object in the list of loaded objects. */
844 l = _dl_new_object (realname, name, l_type, loader);
845 if (__builtin_expect (! l, 0))
847 errstring = N_("cannot create shared object descriptor");
848 goto call_lose_errno;
851 /* Extract the remaining details we need from the ELF header
852 and then read in the program header table. */
853 l->l_entry = header->e_entry;
854 type = header->e_type;
855 l->l_phnum = header->e_phnum;
857 maplength = header->e_phnum * sizeof (ElfW(Phdr));
858 if (header->e_phoff + maplength <= (size_t) fbp->len)
859 phdr = (void *) (fbp->buf + header->e_phoff);
860 else
862 phdr = alloca (maplength);
863 __lseek (fd, header->e_phoff, SEEK_SET);
864 if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
866 errstring = N_("cannot read file data");
867 goto call_lose_errno;
872 /* Scan the program header table, collecting its load commands. */
873 struct loadcmd
875 ElfW(Addr) mapstart, mapend, dataend, allocend;
876 off_t mapoff;
877 int prot;
878 } loadcmds[l->l_phnum], *c;
879 size_t nloadcmds = 0;
881 /* The struct is initialized to zero so this is not necessary:
882 l->l_ld = 0;
883 l->l_phdr = 0;
884 l->l_addr = 0; */
885 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
886 switch (ph->p_type)
888 /* These entries tell us where to find things once the file's
889 segments are mapped in. We record the addresses it says
890 verbatim, and later correct for the run-time load address. */
891 case PT_DYNAMIC:
892 l->l_ld = (void *) ph->p_vaddr;
893 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
894 break;
896 case PT_PHDR:
897 l->l_phdr = (void *) ph->p_vaddr;
898 break;
900 case PT_LOAD:
901 /* A load command tells us to map in part of the file.
902 We record the load commands and process them all later. */
903 if (__builtin_expect ((ph->p_align & (GL(dl_pagesize) - 1)) != 0,
906 errstring = N_("ELF load command alignment not page-aligned");
907 goto call_lose;
909 if (__builtin_expect (((ph->p_vaddr - ph->p_offset)
910 & (ph->p_align - 1)) != 0, 0))
912 errstring
913 = N_("ELF load command address/offset not properly aligned");
914 goto call_lose;
917 c = &loadcmds[nloadcmds++];
918 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
919 c->mapend = ((ph->p_vaddr + ph->p_filesz + GL(dl_pagesize) - 1)
920 & ~(GL(dl_pagesize) - 1));
921 c->dataend = ph->p_vaddr + ph->p_filesz;
922 c->allocend = ph->p_vaddr + ph->p_memsz;
923 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
925 /* Optimize a common case. */
926 #if (PF_R | PF_W | PF_X) == 7 && (PROT_READ | PROT_WRITE | PROT_EXEC) == 7
927 c->prot = (PF_TO_PROT
928 >> ((ph->p_flags & (PF_R | PF_W | PF_X)) * 4)) & 0xf;
929 #else
930 c->prot = 0;
931 if (ph->p_flags & PF_R)
932 c->prot |= PROT_READ;
933 if (ph->p_flags & PF_W)
934 c->prot |= PROT_WRITE;
935 if (ph->p_flags & PF_X)
936 c->prot |= PROT_EXEC;
937 #endif
938 break;
940 case PT_TLS:
941 #ifdef USE_TLS
942 if (ph->p_memsz == 0)
943 /* Nothing to do for an empty segment. */
944 break;
946 l->l_tls_blocksize = ph->p_memsz;
947 l->l_tls_align = ph->p_align;
948 l->l_tls_initimage_size = ph->p_filesz;
949 /* Since we don't know the load address yet only store the
950 offset. We will adjust it later. */
951 l->l_tls_initimage = (void *) ph->p_vaddr;
953 /* If not loading the initial set of shared libraries,
954 check whether we should permit loading a TLS segment. */
955 if (__builtin_expect (l->l_type == lt_library, 1)
956 /* If GL(dl_tls_max_dtv_idx) == 0, then rtld.c did not
957 set up TLS data structures, so don't use them now. */
958 || __builtin_expect (GL(dl_tls_max_dtv_idx), 1) != 0)
960 /* Assign the next available module ID. */
961 l->l_tls_modid = _dl_next_tls_modid ();
962 break;
965 # ifdef SHARED
966 if (l->l_prev == NULL)
967 /* We are loading the executable itself when the dynamic linker
968 was executed directly. The setup will happen later. */
969 break;
971 /* In a static binary there is no way to tell if we dynamically
972 loaded libpthread. */
973 if (GL(dl_error_catch_tsd) == &_dl_initial_error_catch_tsd)
974 # endif
976 /* We have not yet loaded libpthread.
977 We can do the TLS setup right now! */
979 void *tcb;
981 /* The first call allocates TLS bookkeeping data structures.
982 Then we allocate the TCB for the initial thread. */
983 if (__builtin_expect (_dl_tls_setup (), 0)
984 || __builtin_expect ((tcb = _dl_allocate_tls (NULL)) == NULL,
987 errval = ENOMEM;
988 errstring = N_("\
989 cannot allocate TLS data structures for initial thread");
990 goto call_lose;
993 /* Now we install the TCB in the thread register. */
994 errstring = TLS_INIT_TP (tcb, 0);
995 if (__builtin_expect (errstring == NULL, 1))
997 /* Now we are all good. */
998 l->l_tls_modid = ++GL(dl_tls_max_dtv_idx);
999 break;
1002 /* The kernel is too old or somesuch. */
1003 errval = 0;
1004 _dl_deallocate_tls (tcb, 1);
1005 goto call_lose;
1007 #endif
1009 /* Uh-oh, the binary expects TLS support but we cannot
1010 provide it. */
1011 errval = 0;
1012 errstring = N_("cannot handle TLS data");
1013 goto call_lose;
1014 break;
1017 /* Now process the load commands and map segments into memory. */
1018 c = loadcmds;
1020 /* Length of the sections to be loaded. */
1021 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
1023 if (__builtin_expect (type, ET_DYN) == ET_DYN)
1025 /* This is a position-independent shared object. We can let the
1026 kernel map it anywhere it likes, but we must have space for all
1027 the segments in their specified positions relative to the first.
1028 So we map the first segment without MAP_FIXED, but with its
1029 extent increased to cover all the segments. Then we remove
1030 access from excess portion, and there is known sufficient space
1031 there to remap from the later segments.
1033 As a refinement, sometimes we have an address that we would
1034 prefer to map such objects at; but this is only a preference,
1035 the OS can do whatever it likes. */
1036 ElfW(Addr) mappref;
1037 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
1038 - MAP_BASE_ADDR (l));
1040 /* Remember which part of the address space this object uses. */
1041 l->l_map_start = (ElfW(Addr)) __mmap ((void *) mappref, maplength,
1042 c->prot, MAP_COPY | MAP_FILE,
1043 fd, c->mapoff);
1044 if (__builtin_expect ((void *) l->l_map_start == MAP_FAILED, 0))
1046 map_error:
1047 errstring = N_("failed to map segment from shared object");
1048 goto call_lose_errno;
1051 l->l_map_end = l->l_map_start + maplength;
1052 l->l_addr = l->l_map_start - c->mapstart;
1054 /* Change protection on the excess portion to disallow all access;
1055 the portions we do not remap later will be inaccessible as if
1056 unallocated. Then jump into the normal segment-mapping loop to
1057 handle the portion of the segment past the end of the file
1058 mapping. */
1059 __mprotect ((caddr_t) (l->l_addr + c->mapend),
1060 loadcmds[nloadcmds - 1].allocend - c->mapend,
1061 PROT_NONE);
1063 goto postmap;
1065 else
1067 /* This object is loaded at a fixed address. This must never
1068 happen for objects loaded with dlopen(). */
1069 if (__builtin_expect (mode & __RTLD_DLOPEN, 0))
1071 errstring = N_("cannot dynamically load executable");
1072 goto call_lose;
1075 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
1076 fixed. */
1077 ELF_FIXED_ADDRESS (loader, c->mapstart);
1080 /* Remember which part of the address space this object uses. */
1081 l->l_map_start = c->mapstart + l->l_addr;
1082 l->l_map_end = l->l_map_start + maplength;
1084 while (c < &loadcmds[nloadcmds])
1086 if (c->mapend > c->mapstart
1087 /* Map the segment contents from the file. */
1088 && (__mmap ((void *) (l->l_addr + c->mapstart),
1089 c->mapend - c->mapstart, c->prot,
1090 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff)
1091 == MAP_FAILED))
1092 goto map_error;
1094 postmap:
1095 if (l->l_phdr == 0
1096 && (ElfW(Off)) c->mapoff <= header->e_phoff
1097 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
1098 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
1099 /* Found the program header in this segment. */
1100 l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff);
1102 if (c->allocend > c->dataend)
1104 /* Extra zero pages should appear at the end of this segment,
1105 after the data mapped from the file. */
1106 ElfW(Addr) zero, zeroend, zeropage;
1108 zero = l->l_addr + c->dataend;
1109 zeroend = l->l_addr + c->allocend;
1110 zeropage = ((zero + GL(dl_pagesize) - 1)
1111 & ~(GL(dl_pagesize) - 1));
1113 if (zeroend < zeropage)
1114 /* All the extra data is in the last page of the segment.
1115 We can just zero it. */
1116 zeropage = zeroend;
1118 if (zeropage > zero)
1120 /* Zero the final part of the last page of the segment. */
1121 if ((c->prot & PROT_WRITE) == 0)
1123 /* Dag nab it. */
1124 if (__builtin_expect (__mprotect ((caddr_t)
1125 (zero
1126 & ~(GL(dl_pagesize)
1127 - 1)),
1128 GL(dl_pagesize),
1129 c->prot|PROT_WRITE) < 0,
1132 errstring = N_("cannot change memory protections");
1133 goto call_lose_errno;
1136 memset ((void *) zero, '\0', zeropage - zero);
1137 if ((c->prot & PROT_WRITE) == 0)
1138 __mprotect ((caddr_t) (zero & ~(GL(dl_pagesize) - 1)),
1139 GL(dl_pagesize), c->prot);
1142 if (zeroend > zeropage)
1144 /* Map the remaining zero pages in from the zero fill FD. */
1145 caddr_t mapat;
1146 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
1147 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
1148 ANONFD, 0);
1149 if (__builtin_expect (mapat == MAP_FAILED, 0))
1151 errstring = N_("cannot map zero-fill pages");
1152 goto call_lose_errno;
1157 ++c;
1160 if (l->l_phdr == NULL)
1162 /* The program header is not contained in any of the segments.
1163 We have to allocate memory ourself and copy it over from
1164 out temporary place. */
1165 ElfW(Phdr) *newp = (ElfW(Phdr) *) malloc (header->e_phnum
1166 * sizeof (ElfW(Phdr)));
1167 if (newp == NULL)
1169 errstring = N_("cannot allocate memory for program header");
1170 goto call_lose_errno;
1173 l->l_phdr = memcpy (newp, phdr,
1174 (header->e_phnum * sizeof (ElfW(Phdr))));
1175 l->l_phdr_allocated = 1;
1177 else
1178 /* Adjust the PT_PHDR value by the runtime load address. */
1179 (ElfW(Addr)) l->l_phdr += l->l_addr;
1182 #ifdef USE_TLS
1183 /* Adjust the address of the TLS initialization image. */
1184 if (l->l_tls_initimage != NULL)
1185 l->l_tls_initimage = (char *) l->l_tls_initimage + l->l_addr;
1186 #endif
1188 /* We are done mapping in the file. We no longer need the descriptor. */
1189 __close (fd);
1190 /* Signal that we closed the file. */
1191 fd = -1;
1193 if (l->l_type == lt_library && type == ET_EXEC)
1194 l->l_type = lt_executable;
1196 if (l->l_ld == 0)
1198 if (__builtin_expect (type == ET_DYN, 0))
1200 errstring = N_("object file has no dynamic section");
1201 goto call_lose;
1204 else
1205 (ElfW(Addr)) l->l_ld += l->l_addr;
1207 l->l_entry += l->l_addr;
1209 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0))
1210 INTUSE(_dl_debug_printf) ("\
1211 dynamic: 0x%0*lx base: 0x%0*lx size: 0x%0*Zx\n\
1212 entry: 0x%0*lx phdr: 0x%0*lx phnum: %*u\n\n",
1213 (int) sizeof (void *) * 2,
1214 (unsigned long int) l->l_ld,
1215 (int) sizeof (void *) * 2,
1216 (unsigned long int) l->l_addr,
1217 (int) sizeof (void *) * 2, maplength,
1218 (int) sizeof (void *) * 2,
1219 (unsigned long int) l->l_entry,
1220 (int) sizeof (void *) * 2,
1221 (unsigned long int) l->l_phdr,
1222 (int) sizeof (void *) * 2, l->l_phnum);
1224 elf_get_dynamic_info (l);
1226 /* Make sure we are not dlopen'ing an object
1227 that has the DF_1_NOOPEN flag set. */
1228 if (__builtin_expect (l->l_flags_1 & DF_1_NOOPEN, 0)
1229 && (mode & __RTLD_DLOPEN))
1231 /* We are not supposed to load this object. Free all resources. */
1232 __munmap ((void *) l->l_map_start, l->l_map_end - l->l_map_start);
1234 if (!l->l_libname->dont_free)
1235 free (l->l_libname);
1237 if (l->l_phdr_allocated)
1238 free ((void *) l->l_phdr);
1240 errstring = N_("shared object cannot be dlopen()ed");
1241 goto call_lose;
1244 if (l->l_info[DT_HASH])
1245 _dl_setup_hash (l);
1247 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
1248 have to do this for the main map. */
1249 if (__builtin_expect (l->l_info[DT_SYMBOLIC] != NULL, 0)
1250 && &l->l_searchlist != l->l_scope[0])
1252 /* Create an appropriate searchlist. It contains only this map.
1254 XXX This is the definition of DT_SYMBOLIC in SysVr4. The old
1255 GNU ld.so implementation had a different interpretation which
1256 is more reasonable. We are prepared to add this possibility
1257 back as part of a GNU extension of the ELF format. */
1258 l->l_symbolic_searchlist.r_list =
1259 (struct link_map **) malloc (sizeof (struct link_map *));
1261 if (l->l_symbolic_searchlist.r_list == NULL)
1263 errstring = N_("cannot create searchlist");
1264 goto call_lose_errno;
1267 l->l_symbolic_searchlist.r_list[0] = l;
1268 l->l_symbolic_searchlist.r_nlist = 1;
1270 /* Now move the existing entries one back. */
1271 memmove (&l->l_scope[1], &l->l_scope[0],
1272 (l->l_scope_max - 1) * sizeof (l->l_scope[0]));
1274 /* Now add the new entry. */
1275 l->l_scope[0] = &l->l_symbolic_searchlist;
1278 /* Remember whether this object must be initialized first. */
1279 if (l->l_flags_1 & DF_1_INITFIRST)
1280 GL(dl_initfirst) = l;
1282 /* Finally the file information. */
1283 l->l_dev = st.st_dev;
1284 l->l_ino = st.st_ino;
1286 /* When we profile the SONAME might be needed for something else but
1287 loading. Add it right away. */
1288 if (__builtin_expect (GL(dl_profile) != NULL, 0)
1289 && l->l_info[DT_SONAME] != NULL)
1290 add_name_to_object (l, ((const char *) D_PTR (l, l_info[DT_STRTAB])
1291 + l->l_info[DT_SONAME]->d_un.d_val));
1293 return l;
1296 /* Print search path. */
1297 static void
1298 print_search_path (struct r_search_path_elem **list,
1299 const char *what, const char *name)
1301 char buf[max_dirnamelen + max_capstrlen];
1302 int first = 1;
1304 INTUSE(_dl_debug_printf) (" search path=");
1306 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
1308 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
1309 size_t cnt;
1311 for (cnt = 0; cnt < ncapstr; ++cnt)
1312 if ((*list)->status[cnt] != nonexisting)
1314 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
1315 if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
1316 cp[0] = '\0';
1317 else
1318 cp[-1] = '\0';
1320 _dl_debug_printf_c (first ? "%s" : ":%s", buf);
1321 first = 0;
1324 ++list;
1327 if (name != NULL)
1328 _dl_debug_printf_c ("\t\t(%s from file %s)\n", what,
1329 name[0] ? name : rtld_progname);
1330 else
1331 _dl_debug_printf_c ("\t\t(%s)\n", what);
1334 /* Open a file and verify it is an ELF file for this architecture. We
1335 ignore only ELF files for other architectures. Non-ELF files and
1336 ELF files with different header information cause fatal errors since
1337 this could mean there is something wrong in the installation and the
1338 user might want to know about this. */
1339 static int
1340 open_verify (const char *name, struct filebuf *fbp)
1342 /* This is the expected ELF header. */
1343 #define ELF32_CLASS ELFCLASS32
1344 #define ELF64_CLASS ELFCLASS64
1345 #ifndef VALID_ELF_HEADER
1346 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
1347 # define VALID_ELF_OSABI(osabi) (osabi == ELFOSABI_SYSV)
1348 # define VALID_ELF_ABIVERSION(ver) (ver == 0)
1349 #endif
1350 static const unsigned char expected[EI_PAD] =
1352 [EI_MAG0] = ELFMAG0,
1353 [EI_MAG1] = ELFMAG1,
1354 [EI_MAG2] = ELFMAG2,
1355 [EI_MAG3] = ELFMAG3,
1356 [EI_CLASS] = ELFW(CLASS),
1357 [EI_DATA] = byteorder,
1358 [EI_VERSION] = EV_CURRENT,
1359 [EI_OSABI] = ELFOSABI_SYSV,
1360 [EI_ABIVERSION] = 0
1362 static const struct
1364 ElfW(Word) vendorlen;
1365 ElfW(Word) datalen;
1366 ElfW(Word) type;
1367 char vendor[4];
1368 } expected_note = { 4, 16, 1, "GNU" };
1369 int fd;
1370 /* Initialize it to make the compiler happy. */
1371 const char *errstring = NULL;
1372 int errval = 0;
1374 /* Open the file. We always open files read-only. */
1375 fd = __open (name, O_RDONLY);
1376 if (fd != -1)
1378 ElfW(Ehdr) *ehdr;
1379 ElfW(Phdr) *phdr, *ph;
1380 ElfW(Word) *abi_note, abi_note_buf[8];
1381 unsigned int osversion;
1382 size_t maplength;
1384 /* We successfully openened the file. Now verify it is a file
1385 we can use. */
1386 __set_errno (0);
1387 fbp->len = __libc_read (fd, fbp->buf, sizeof (fbp->buf));
1389 /* This is where the ELF header is loaded. */
1390 assert (sizeof (fbp->buf) > sizeof (ElfW(Ehdr)));
1391 ehdr = (ElfW(Ehdr) *) fbp->buf;
1393 /* Now run the tests. */
1394 if (__builtin_expect (fbp->len < (ssize_t) sizeof (ElfW(Ehdr)), 0))
1396 errval = errno;
1397 errstring = (errval == 0
1398 ? N_("file too short") : N_("cannot read file data"));
1399 call_lose:
1400 lose (errval, fd, name, NULL, NULL, errstring);
1403 /* See whether the ELF header is what we expect. */
1404 if (__builtin_expect (! VALID_ELF_HEADER (ehdr->e_ident, expected,
1405 EI_PAD), 0))
1407 /* Something is wrong. */
1408 if (*(Elf32_Word *) &ehdr->e_ident !=
1409 #if BYTE_ORDER == LITTLE_ENDIAN
1410 ((ELFMAG0 << (EI_MAG0 * 8)) |
1411 (ELFMAG1 << (EI_MAG1 * 8)) |
1412 (ELFMAG2 << (EI_MAG2 * 8)) |
1413 (ELFMAG3 << (EI_MAG3 * 8)))
1414 #else
1415 ((ELFMAG0 << (EI_MAG3 * 8)) |
1416 (ELFMAG1 << (EI_MAG2 * 8)) |
1417 (ELFMAG2 << (EI_MAG1 * 8)) |
1418 (ELFMAG3 << (EI_MAG0 * 8)))
1419 #endif
1421 errstring = N_("invalid ELF header");
1422 else if (ehdr->e_ident[EI_CLASS] != ELFW(CLASS))
1423 /* This is not a fatal error. On architectures where
1424 32-bit and 64-bit binaries can be run this might
1425 happen. */
1426 goto close_and_out;
1427 else if (ehdr->e_ident[EI_DATA] != byteorder)
1429 if (BYTE_ORDER == BIG_ENDIAN)
1430 errstring = N_("ELF file data encoding not big-endian");
1431 else
1432 errstring = N_("ELF file data encoding not little-endian");
1434 else if (ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1435 errstring
1436 = N_("ELF file version ident does not match current one");
1437 /* XXX We should be able so set system specific versions which are
1438 allowed here. */
1439 else if (!VALID_ELF_OSABI (ehdr->e_ident[EI_OSABI]))
1440 errstring = N_("ELF file OS ABI invalid");
1441 else if (!VALID_ELF_ABIVERSION (ehdr->e_ident[EI_ABIVERSION]))
1442 errstring = N_("ELF file ABI version invalid");
1443 else
1444 /* Otherwise we don't know what went wrong. */
1445 errstring = N_("internal error");
1447 goto call_lose;
1450 if (__builtin_expect (ehdr->e_version, EV_CURRENT) != EV_CURRENT)
1452 errstring = N_("ELF file version does not match current one");
1453 goto call_lose;
1455 if (! __builtin_expect (elf_machine_matches_host (ehdr), 1))
1456 goto close_and_out;
1457 else if (__builtin_expect (ehdr->e_phentsize, sizeof (ElfW(Phdr)))
1458 != sizeof (ElfW(Phdr)))
1460 errstring = N_("ELF file's phentsize not the expected size");
1461 goto call_lose;
1463 else if (__builtin_expect (ehdr->e_type, ET_DYN) != ET_DYN
1464 && __builtin_expect (ehdr->e_type, ET_EXEC) != ET_EXEC)
1466 errstring = N_("only ET_DYN and ET_EXEC can be loaded");
1467 goto call_lose;
1470 maplength = ehdr->e_phnum * sizeof (ElfW(Phdr));
1471 if (ehdr->e_phoff + maplength <= (size_t) fbp->len)
1472 phdr = (void *) (fbp->buf + ehdr->e_phoff);
1473 else
1475 phdr = alloca (maplength);
1476 __lseek (fd, ehdr->e_phoff, SEEK_SET);
1477 if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
1479 read_error:
1480 errval = errno;
1481 errstring = N_("cannot read file data");
1482 goto call_lose;
1486 /* Check .note.ABI-tag if present. */
1487 for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph)
1488 if (ph->p_type == PT_NOTE && ph->p_filesz == 32 && ph->p_align >= 4)
1490 if (ph->p_offset + 32 <= (size_t) fbp->len)
1491 abi_note = (void *) (fbp->buf + ph->p_offset);
1492 else
1494 __lseek (fd, ph->p_offset, SEEK_SET);
1495 if (__libc_read (fd, (void *) abi_note_buf, 32) != 32)
1496 goto read_error;
1498 abi_note = abi_note_buf;
1501 if (memcmp (abi_note, &expected_note, sizeof (expected_note)))
1502 continue;
1504 osversion = (abi_note[5] & 0xff) * 65536
1505 + (abi_note[6] & 0xff) * 256
1506 + (abi_note[7] & 0xff);
1507 if (abi_note[4] != __ABI_TAG_OS
1508 || (GL(dl_osversion) && GL(dl_osversion) < osversion))
1510 close_and_out:
1511 __close (fd);
1512 __set_errno (ENOENT);
1513 fd = -1;
1516 break;
1520 return fd;
1523 /* Try to open NAME in one of the directories in *DIRSP.
1524 Return the fd, or -1. If successful, fill in *REALNAME
1525 with the malloc'd full directory name. If it turns out
1526 that none of the directories in *DIRSP exists, *DIRSP is
1527 replaced with (void *) -1, and the old value is free()d
1528 if MAY_FREE_DIRS is true. */
1530 static int
1531 open_path (const char *name, size_t namelen, int preloaded,
1532 struct r_search_path_struct *sps, char **realname,
1533 struct filebuf *fbp)
1535 struct r_search_path_elem **dirs = sps->dirs;
1536 char *buf;
1537 int fd = -1;
1538 const char *current_what = NULL;
1539 int any = 0;
1541 buf = alloca (max_dirnamelen + max_capstrlen + namelen);
1544 struct r_search_path_elem *this_dir = *dirs;
1545 size_t buflen = 0;
1546 size_t cnt;
1547 char *edp;
1548 int here_any = 0;
1549 int err;
1551 /* If we are debugging the search for libraries print the path
1552 now if it hasn't happened now. */
1553 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0)
1554 && current_what != this_dir->what)
1556 current_what = this_dir->what;
1557 print_search_path (dirs, current_what, this_dir->where);
1560 edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1561 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1563 /* Skip this directory if we know it does not exist. */
1564 if (this_dir->status[cnt] == nonexisting)
1565 continue;
1567 buflen =
1568 ((char *) __mempcpy (__mempcpy (edp, capstr[cnt].str,
1569 capstr[cnt].len),
1570 name, namelen)
1571 - buf);
1573 /* Print name we try if this is wanted. */
1574 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1575 INTUSE(_dl_debug_printf) (" trying file=%s\n", buf);
1577 fd = open_verify (buf, fbp);
1578 if (this_dir->status[cnt] == unknown)
1580 if (fd != -1)
1581 this_dir->status[cnt] = existing;
1582 else
1584 /* We failed to open machine dependent library. Let's
1585 test whether there is any directory at all. */
1586 struct stat64 st;
1588 buf[buflen - namelen - 1] = '\0';
1590 if (__xstat64 (_STAT_VER, buf, &st) != 0
1591 || ! S_ISDIR (st.st_mode))
1592 /* The directory does not exist or it is no directory. */
1593 this_dir->status[cnt] = nonexisting;
1594 else
1595 this_dir->status[cnt] = existing;
1599 /* Remember whether we found any existing directory. */
1600 here_any |= this_dir->status[cnt] == existing;
1602 if (fd != -1 && __builtin_expect (preloaded, 0)
1603 && INTUSE(__libc_enable_secure))
1605 /* This is an extra security effort to make sure nobody can
1606 preload broken shared objects which are in the trusted
1607 directories and so exploit the bugs. */
1608 struct stat64 st;
1610 if (__fxstat64 (_STAT_VER, fd, &st) != 0
1611 || (st.st_mode & S_ISUID) == 0)
1613 /* The shared object cannot be tested for being SUID
1614 or this bit is not set. In this case we must not
1615 use this object. */
1616 __close (fd);
1617 fd = -1;
1618 /* We simply ignore the file, signal this by setting
1619 the error value which would have been set by `open'. */
1620 errno = ENOENT;
1625 if (fd != -1)
1627 *realname = (char *) malloc (buflen);
1628 if (*realname != NULL)
1630 memcpy (*realname, buf, buflen);
1631 return fd;
1633 else
1635 /* No memory for the name, we certainly won't be able
1636 to load and link it. */
1637 __close (fd);
1638 return -1;
1641 if (here_any && (err = errno) != ENOENT && err != EACCES)
1642 /* The file exists and is readable, but something went wrong. */
1643 return -1;
1645 /* Remember whether we found anything. */
1646 any |= here_any;
1648 while (*++dirs != NULL);
1650 /* Remove the whole path if none of the directories exists. */
1651 if (__builtin_expect (! any, 0))
1653 /* Paths which were allocated using the minimal malloc() in ld.so
1654 must not be freed using the general free() in libc. */
1655 if (sps->malloced)
1656 free (sps->dirs);
1657 sps->dirs = (void *) -1;
1660 return -1;
1663 /* Map in the shared object file NAME. */
1665 struct link_map *
1666 internal_function
1667 _dl_map_object (struct link_map *loader, const char *name, int preloaded,
1668 int type, int trace_mode, int mode)
1670 int fd;
1671 char *realname;
1672 char *name_copy;
1673 struct link_map *l;
1674 struct filebuf fb;
1676 /* Look for this name among those already loaded. */
1677 for (l = GL(dl_loaded); l; l = l->l_next)
1679 /* If the requested name matches the soname of a loaded object,
1680 use that object. Elide this check for names that have not
1681 yet been opened. */
1682 if (__builtin_expect (l->l_faked, 0) != 0)
1683 continue;
1684 if (!_dl_name_match_p (name, l))
1686 const char *soname;
1688 if (__builtin_expect (l->l_soname_added, 1)
1689 || l->l_info[DT_SONAME] == NULL)
1690 continue;
1692 soname = ((const char *) D_PTR (l, l_info[DT_STRTAB])
1693 + l->l_info[DT_SONAME]->d_un.d_val);
1694 if (strcmp (name, soname) != 0)
1695 continue;
1697 /* We have a match on a new name -- cache it. */
1698 add_name_to_object (l, soname);
1699 l->l_soname_added = 1;
1702 /* We have a match. */
1703 return l;
1706 /* Display information if we are debugging. */
1707 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0)
1708 && loader != NULL)
1709 INTUSE(_dl_debug_printf) ("\nfile=%s; needed by %s\n", name,
1710 loader->l_name[0]
1711 ? loader->l_name : rtld_progname);
1713 if (strchr (name, '/') == NULL)
1715 /* Search for NAME in several places. */
1717 size_t namelen = strlen (name) + 1;
1719 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1720 INTUSE(_dl_debug_printf) ("find library=%s; searching\n", name);
1722 fd = -1;
1724 /* When the object has the RUNPATH information we don't use any
1725 RPATHs. */
1726 if (loader == NULL || loader->l_info[DT_RUNPATH] == NULL)
1728 /* First try the DT_RPATH of the dependent object that caused NAME
1729 to be loaded. Then that object's dependent, and on up. */
1730 for (l = loader; fd == -1 && l; l = l->l_loader)
1732 if (l->l_rpath_dirs.dirs == NULL)
1734 if (l->l_info[DT_RPATH] == NULL)
1736 /* There is no path. */
1737 l->l_rpath_dirs.dirs = (void *) -1;
1738 continue;
1740 else
1742 /* Make sure the cache information is available. */
1743 size_t ptrval = (D_PTR (l, l_info[DT_STRTAB])
1744 + l->l_info[DT_RPATH]->d_un.d_val);
1745 decompose_rpath (&l->l_rpath_dirs,
1746 (const char *) ptrval, l, "RPATH");
1750 if (l->l_rpath_dirs.dirs != (void *) -1)
1751 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1752 &realname, &fb);
1755 /* If dynamically linked, try the DT_RPATH of the executable
1756 itself. */
1757 l = GL(dl_loaded);
1758 if (fd == -1 && l && l->l_type != lt_loaded && l != loader
1759 && l->l_rpath_dirs.dirs != (void *) -1)
1760 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1761 &realname, &fb);
1764 /* Try the LD_LIBRARY_PATH environment variable. */
1765 if (fd == -1 && env_path_list.dirs != (void *) -1)
1766 fd = open_path (name, namelen, preloaded, &env_path_list,
1767 &realname, &fb);
1769 /* Look at the RUNPATH information for this binary.
1771 Note that this is no real loop. 'while' is used only to enable
1772 us to use 'break' instead of a 'goto' to jump to the end. The
1773 loop is always left after the first round. */
1774 while (fd == -1 && loader != NULL
1775 && loader->l_runpath_dirs.dirs != (void *) -1)
1777 if (loader->l_runpath_dirs.dirs == NULL)
1779 if (loader->l_info[DT_RUNPATH] == NULL)
1781 /* No RUNPATH. */
1782 loader->l_runpath_dirs.dirs = (void *) -1;
1783 break;
1785 else
1787 /* Make sure the cache information is available. */
1788 size_t ptrval = (D_PTR (loader, l_info[DT_STRTAB])
1789 + loader->l_info[DT_RUNPATH]->d_un.d_val);
1790 decompose_rpath (&loader->l_runpath_dirs,
1791 (const char *) ptrval, loader, "RUNPATH");
1795 if (loader->l_runpath_dirs.dirs != (void *) -1)
1796 fd = open_path (name, namelen, preloaded,
1797 &loader->l_runpath_dirs, &realname, &fb);
1798 break;
1801 if (fd == -1
1802 && (__builtin_expect (! preloaded, 1)
1803 || ! INTUSE(__libc_enable_secure)))
1805 /* Check the list of libraries in the file /etc/ld.so.cache,
1806 for compatibility with Linux's ldconfig program. */
1807 const char *cached = _dl_load_cache_lookup (name);
1809 if (cached != NULL)
1811 #ifdef SHARED
1812 l = loader ?: GL(dl_loaded);
1813 #else
1814 l = loader;
1815 #endif
1817 /* If the loader has the DF_1_NODEFLIB flag set we must not
1818 use a cache entry from any of these directories. */
1819 if (
1820 #ifndef SHARED
1821 /* 'l' is always != NULL for dynamically linked objects. */
1822 l != NULL &&
1823 #endif
1824 __builtin_expect (l->l_flags_1 & DF_1_NODEFLIB, 0))
1826 const char *dirp = system_dirs;
1827 unsigned int cnt = 0;
1831 if (memcmp (cached, dirp, system_dirs_len[cnt]) == 0)
1833 /* The prefix matches. Don't use the entry. */
1834 cached = NULL;
1835 break;
1838 dirp += system_dirs_len[cnt] + 1;
1839 ++cnt;
1841 while (cnt < nsystem_dirs_len);
1844 if (cached != NULL)
1846 fd = open_verify (cached, &fb);
1847 if (__builtin_expect (fd != -1, 1))
1849 realname = local_strdup (cached);
1850 if (realname == NULL)
1852 __close (fd);
1853 fd = -1;
1860 /* Finally, try the default path. */
1861 if (fd == -1
1862 && ((l = loader ?: GL(dl_loaded)) == NULL
1863 || __builtin_expect (!(l->l_flags_1 & DF_1_NODEFLIB), 1))
1864 && rtld_search_dirs.dirs != (void *) -1)
1865 fd = open_path (name, namelen, preloaded, &rtld_search_dirs,
1866 &realname, &fb);
1868 /* Add another newline when we are tracing the library loading. */
1869 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1870 INTUSE(_dl_debug_printf) ("\n");
1872 else
1874 /* The path may contain dynamic string tokens. */
1875 realname = (loader
1876 ? expand_dynamic_string_token (loader, name)
1877 : local_strdup (name));
1878 if (realname == NULL)
1879 fd = -1;
1880 else
1882 fd = open_verify (realname, &fb);
1883 if (__builtin_expect (fd, 0) == -1)
1884 free (realname);
1888 if (__builtin_expect (fd, 0) == -1)
1890 if (trace_mode
1891 && __builtin_expect (GL(dl_debug_mask) & DL_DEBUG_PRELINK, 0) == 0)
1893 /* We haven't found an appropriate library. But since we
1894 are only interested in the list of libraries this isn't
1895 so severe. Fake an entry with all the information we
1896 have. */
1897 static const Elf_Symndx dummy_bucket = STN_UNDEF;
1899 /* Enter the new object in the list of loaded objects. */
1900 if ((name_copy = local_strdup (name)) == NULL
1901 || (l = _dl_new_object (name_copy, name, type, loader)) == NULL)
1902 INTUSE(_dl_signal_error) (ENOMEM, name, NULL, N_("\
1903 cannot create shared object descriptor"));
1904 /* Signal that this is a faked entry. */
1905 l->l_faked = 1;
1906 /* Since the descriptor is initialized with zero we do not
1907 have do this here.
1908 l->l_reserved = 0; */
1909 l->l_buckets = &dummy_bucket;
1910 l->l_nbuckets = 1;
1911 l->l_relocated = 1;
1913 return l;
1915 else
1916 INTUSE(_dl_signal_error) (errno, name, NULL,
1917 N_("cannot open shared object file"));
1920 return _dl_map_object_from_fd (name, fd, &fb, realname, loader, type, mode);
1922 INTDEF (_dl_map_object)