(DO_SET_THREAD_AREA): Don't use INLINE_SYSCALL for set_thread_area syscall.
[glibc.git] / elf / dl-load.c
blob1d10541f522bec901c0138c22f55df9b3f276d5b
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];
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))
206 != 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,
243 0)) != 0)
244 repl = GL(dl_platform);
246 if (repl != NULL && repl != (const char *) -1)
248 wp = __stpcpy (wp, repl);
249 name += len;
251 else if (len > 1)
253 /* We cannot use this path element, the value of the
254 replacement is unknown. */
255 wp = last_elem;
256 name += len;
257 while (*name != '\0' && (!is_path || *name != ':'))
258 ++name;
260 else
261 /* No DST we recognize. */
262 *wp++ = '$';
264 else
266 *wp++ = *name++;
267 if (is_path && *name == ':')
268 last_elem = wp;
271 while (*name != '\0');
273 *wp = '\0';
275 return result;
277 INTDEF (_dl_dst_substitute)
280 /* Return copy of argument with all recognized dynamic string tokens
281 ($ORIGIN and $PLATFORM for now) replaced. On some platforms it
282 might not be possible to determine the path from which the object
283 belonging to the map is loaded. In this case the path element
284 containing $ORIGIN is left out. */
285 static char *
286 expand_dynamic_string_token (struct link_map *l, const char *s)
288 /* We make two runs over the string. First we determine how large the
289 resulting string is and then we copy it over. Since this is now
290 frequently executed operation we are looking here not for performance
291 but rather for code size. */
292 size_t cnt;
293 size_t total;
294 char *result;
296 /* Determine the number of DST elements. */
297 cnt = DL_DST_COUNT (s, 1);
299 /* If we do not have to replace anything simply copy the string. */
300 if (__builtin_expect (cnt, 0) == 0)
301 return local_strdup (s);
303 /* Determine the length of the substituted string. */
304 total = DL_DST_REQUIRED (l, s, strlen (s), cnt);
306 /* Allocate the necessary memory. */
307 result = (char *) malloc (total + 1);
308 if (result == NULL)
309 return NULL;
311 return INTUSE(_dl_dst_substitute) (l, s, result, 1);
315 /* Add `name' to the list of names for a particular shared object.
316 `name' is expected to have been allocated with malloc and will
317 be freed if the shared object already has this name.
318 Returns false if the object already had this name. */
319 static void
320 internal_function
321 add_name_to_object (struct link_map *l, const char *name)
323 struct libname_list *lnp, *lastp;
324 struct libname_list *newname;
325 size_t name_len;
327 lastp = NULL;
328 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
329 if (strcmp (name, lnp->name) == 0)
330 return;
332 name_len = strlen (name) + 1;
333 newname = (struct libname_list *) malloc (sizeof *newname + name_len);
334 if (newname == NULL)
336 /* No more memory. */
337 INTUSE(_dl_signal_error) (ENOMEM, name, NULL,
338 N_("cannot allocate name record"));
339 return;
341 /* The object should have a libname set from _dl_new_object. */
342 assert (lastp != NULL);
344 newname->name = memcpy (newname + 1, name, name_len);
345 newname->next = NULL;
346 newname->dont_free = 0;
347 lastp->next = newname;
350 /* Standard search directories. */
351 static struct r_search_path_struct rtld_search_dirs;
353 static size_t max_dirnamelen;
355 static inline struct r_search_path_elem **
356 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
357 int check_trusted, const char *what, const char *where)
359 char *cp;
360 size_t nelems = 0;
362 while ((cp = __strsep (&rpath, sep)) != NULL)
364 struct r_search_path_elem *dirp;
365 size_t len = strlen (cp);
367 /* `strsep' can pass an empty string. This has to be
368 interpreted as `use the current directory'. */
369 if (len == 0)
371 static const char curwd[] = "./";
372 cp = (char *) curwd;
375 /* Remove trailing slashes (except for "/"). */
376 while (len > 1 && cp[len - 1] == '/')
377 --len;
379 /* Now add one if there is none so far. */
380 if (len > 0 && cp[len - 1] != '/')
381 cp[len++] = '/';
383 /* Make sure we don't use untrusted directories if we run SUID. */
384 if (__builtin_expect (check_trusted, 0))
386 const char *trun = system_dirs;
387 size_t idx;
388 int unsecure = 1;
390 /* All trusted directories must be complete names. */
391 if (cp[0] == '/')
393 for (idx = 0; idx < nsystem_dirs_len; ++idx)
395 if (len == system_dirs_len[idx]
396 && memcmp (trun, cp, len) == 0)
398 /* Found it. */
399 unsecure = 0;
400 break;
403 trun += system_dirs_len[idx] + 1;
407 if (unsecure)
408 /* Simply drop this directory. */
409 continue;
412 /* See if this directory is already known. */
413 for (dirp = GL(dl_all_dirs); dirp != NULL; dirp = dirp->next)
414 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
415 break;
417 if (dirp != NULL)
419 /* It is available, see whether it's on our own list. */
420 size_t cnt;
421 for (cnt = 0; cnt < nelems; ++cnt)
422 if (result[cnt] == dirp)
423 break;
425 if (cnt == nelems)
426 result[nelems++] = dirp;
428 else
430 size_t cnt;
431 enum r_dir_status init_val;
432 size_t where_len = where ? strlen (where) + 1 : 0;
434 /* It's a new directory. Create an entry and add it. */
435 dirp = (struct r_search_path_elem *)
436 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status)
437 + where_len + len + 1);
438 if (dirp == NULL)
439 INTUSE(_dl_signal_error) (ENOMEM, NULL, NULL,
440 N_("cannot create cache for search path"));
442 dirp->dirname = ((char *) dirp + sizeof (*dirp)
443 + ncapstr * sizeof (enum r_dir_status));
444 *((char *) __mempcpy ((char *) dirp->dirname, cp, len)) = '\0';
445 dirp->dirnamelen = len;
447 if (len > max_dirnamelen)
448 max_dirnamelen = len;
450 /* We have to make sure all the relative directories are
451 never ignored. The current directory might change and
452 all our saved information would be void. */
453 init_val = cp[0] != '/' ? existing : unknown;
454 for (cnt = 0; cnt < ncapstr; ++cnt)
455 dirp->status[cnt] = init_val;
457 dirp->what = what;
458 if (__builtin_expect (where != NULL, 1))
459 dirp->where = memcpy ((char *) dirp + sizeof (*dirp) + len + 1
460 + (ncapstr * sizeof (enum r_dir_status)),
461 where, where_len);
462 else
463 dirp->where = NULL;
465 dirp->next = GL(dl_all_dirs);
466 GL(dl_all_dirs) = dirp;
468 /* Put it in the result array. */
469 result[nelems++] = dirp;
473 /* Terminate the array. */
474 result[nelems] = NULL;
476 return result;
480 static void
481 internal_function
482 decompose_rpath (struct r_search_path_struct *sps,
483 const char *rpath, struct link_map *l, const char *what)
485 /* Make a copy we can work with. */
486 const char *where = l->l_name;
487 char *copy;
488 char *cp;
489 struct r_search_path_elem **result;
490 size_t nelems;
491 /* Initialize to please the compiler. */
492 const char *errstring = NULL;
494 /* First see whether we must forget the RUNPATH and RPATH from this
495 object. */
496 if (__builtin_expect (GL(dl_inhibit_rpath) != NULL, 0)
497 && !INTUSE(__libc_enable_secure))
499 const char *inhp = GL(dl_inhibit_rpath);
503 const char *wp = where;
505 while (*inhp == *wp && *wp != '\0')
507 ++inhp;
508 ++wp;
511 if (*wp == '\0' && (*inhp == '\0' || *inhp == ':'))
513 /* This object is on the list of objects for which the
514 RUNPATH and RPATH must not be used. */
515 result = (struct r_search_path_elem **)
516 malloc (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 result[0] = NULL;
527 sps->dirs = result;
528 sps->malloced = 1;
530 return;
533 while (*inhp != '\0')
534 if (*inhp++ == ':')
535 break;
537 while (*inhp != '\0');
540 /* Make a writable copy. At the same time expand possible dynamic
541 string tokens. */
542 copy = expand_dynamic_string_token (l, rpath);
543 if (copy == NULL)
545 errstring = N_("cannot create RUNPATH/RPATH copy");
546 goto signal_error;
549 /* Count the number of necessary elements in the result array. */
550 nelems = 0;
551 for (cp = copy; *cp != '\0'; ++cp)
552 if (*cp == ':')
553 ++nelems;
555 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
556 number of necessary entries. */
557 result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
558 * sizeof (*result));
559 if (result == NULL)
560 goto signal_error_cache;
562 fillin_rpath (copy, result, ":", 0, what, where);
564 /* Free the copied RPATH string. `fillin_rpath' make own copies if
565 necessary. */
566 free (copy);
568 sps->dirs = result;
569 /* The caller will change this value if we haven't used a real malloc. */
570 sps->malloced = 1;
574 void
575 internal_function
576 _dl_init_paths (const char *llp)
578 size_t idx;
579 const char *strp;
580 struct r_search_path_elem *pelem, **aelem;
581 size_t round_size;
582 #ifdef SHARED
583 struct link_map *l;
584 #endif
585 /* Initialize to please the compiler. */
586 const char *errstring = NULL;
588 /* Fill in the information about the application's RPATH and the
589 directories addressed by the LD_LIBRARY_PATH environment variable. */
591 /* Get the capabilities. */
592 capstr = _dl_important_hwcaps (GL(dl_platform), GL(dl_platformlen),
593 &ncapstr, &max_capstrlen);
595 /* First set up the rest of the default search directory entries. */
596 aelem = rtld_search_dirs.dirs = (struct r_search_path_elem **)
597 malloc ((nsystem_dirs_len + 1) * sizeof (struct r_search_path_elem *));
598 if (rtld_search_dirs.dirs == NULL)
600 errstring = N_("cannot create search path array");
601 signal_error:
602 INTUSE(_dl_signal_error) (ENOMEM, NULL, NULL, errstring);
605 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
606 + ncapstr * sizeof (enum r_dir_status))
607 / sizeof (struct r_search_path_elem));
609 rtld_search_dirs.dirs[0] = (struct r_search_path_elem *)
610 malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]))
611 * round_size * sizeof (struct r_search_path_elem));
612 if (rtld_search_dirs.dirs[0] == NULL)
614 errstring = N_("cannot create cache for search path");
615 goto signal_error;
618 rtld_search_dirs.malloced = 0;
619 pelem = GL(dl_all_dirs) = rtld_search_dirs.dirs[0];
620 strp = system_dirs;
621 idx = 0;
625 size_t cnt;
627 *aelem++ = pelem;
629 pelem->what = "system search path";
630 pelem->where = NULL;
632 pelem->dirname = strp;
633 pelem->dirnamelen = system_dirs_len[idx];
634 strp += system_dirs_len[idx] + 1;
636 /* System paths must be absolute. */
637 assert (pelem->dirname[0] == '/');
638 for (cnt = 0; cnt < ncapstr; ++cnt)
639 pelem->status[cnt] = unknown;
641 pelem->next = (++idx == nsystem_dirs_len ? NULL : (pelem + round_size));
643 pelem += round_size;
645 while (idx < nsystem_dirs_len);
647 max_dirnamelen = SYSTEM_DIRS_MAX_LEN;
648 *aelem = NULL;
650 #ifdef SHARED
651 /* This points to the map of the main object. */
652 l = GL(dl_loaded);
653 if (l != NULL)
655 assert (l->l_type != lt_loaded);
657 if (l->l_info[DT_RUNPATH])
659 /* Allocate room for the search path and fill in information
660 from RUNPATH. */
661 decompose_rpath (&l->l_runpath_dirs,
662 (const void *) (D_PTR (l, l_info[DT_STRTAB])
663 + l->l_info[DT_RUNPATH]->d_un.d_val),
664 l, "RUNPATH");
666 /* The RPATH is ignored. */
667 l->l_rpath_dirs.dirs = (void *) -1;
669 else
671 l->l_runpath_dirs.dirs = (void *) -1;
673 if (l->l_info[DT_RPATH])
675 /* Allocate room for the search path and fill in information
676 from RPATH. */
677 decompose_rpath (&l->l_rpath_dirs,
678 (const void *) (D_PTR (l, l_info[DT_STRTAB])
679 + l->l_info[DT_RPATH]->d_un.d_val),
680 l, "RPATH");
681 l->l_rpath_dirs.malloced = 0;
683 else
684 l->l_rpath_dirs.dirs = (void *) -1;
687 #endif /* SHARED */
689 if (llp != NULL && *llp != '\0')
691 size_t nllp;
692 const char *cp = llp;
693 char *llp_tmp = strdupa (llp);
695 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
696 elements it has. */
697 nllp = 1;
698 while (*cp)
700 if (*cp == ':' || *cp == ';')
701 ++nllp;
702 ++cp;
705 env_path_list.dirs = (struct r_search_path_elem **)
706 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
707 if (env_path_list.dirs == NULL)
709 errstring = N_("cannot create cache for search path");
710 goto signal_error;
713 (void) fillin_rpath (llp_tmp, env_path_list.dirs, ":;",
714 INTUSE(__libc_enable_secure), "LD_LIBRARY_PATH",
715 NULL);
717 if (env_path_list.dirs[0] == NULL)
719 free (env_path_list.dirs);
720 env_path_list.dirs = (void *) -1;
723 env_path_list.malloced = 0;
725 else
726 env_path_list.dirs = (void *) -1;
728 /* Remember the last search directory added at startup. */
729 GL(dl_init_all_dirs) = GL(dl_all_dirs);
733 /* Think twice before changing anything in this function. It is placed
734 here and prepared using the `alloca' magic to prevent it from being
735 inlined. The function is only called in case of an error. But then
736 performance does not count. The function used to be "inlinable" and
737 the compiled did so all the time. This increased the code size for
738 absolutely no good reason. */
739 static void
740 __attribute__ ((noreturn))
741 lose (int code, int fd, const char *name, char *realname, struct link_map *l,
742 const char *msg)
744 /* The use of `alloca' here looks ridiculous but it helps. The goal
745 is to avoid the function from being inlined. There is no official
746 way to do this so we use this trick. gcc never inlines functions
747 which use `alloca'. */
748 int *a = (int *) alloca (sizeof (int));
749 a[0] = fd;
750 /* The file might already be closed. */
751 if (a[0] != -1)
752 (void) __close (a[0]);
753 if (l != NULL)
755 /* Remove the stillborn object from the list and free it. */
756 assert (l->l_next == NULL);
757 if (l->l_prev == NULL)
758 /* No other module loaded. This happens only in the static library,
759 or in rtld under --verify. */
760 GL(dl_loaded) = NULL;
761 else
762 l->l_prev->l_next = NULL;
763 --GL(dl_nloaded);
764 free (l);
766 free (realname);
767 INTUSE(_dl_signal_error) (code, name, NULL, msg);
771 /* Map in the shared object NAME, actually located in REALNAME, and already
772 opened on FD. */
774 #ifndef EXTERNAL_MAP_FROM_FD
775 static
776 #endif
777 struct link_map *
778 _dl_map_object_from_fd (const char *name, int fd, struct filebuf *fbp,
779 char *realname, struct link_map *loader, int l_type,
780 int mode)
782 struct link_map *l = NULL;
783 const ElfW(Ehdr) *header;
784 const ElfW(Phdr) *phdr;
785 const ElfW(Phdr) *ph;
786 size_t maplength;
787 int type;
788 struct stat64 st;
789 /* Initialize to keep the compiler happy. */
790 const char *errstring = NULL;
791 int errval = 0;
793 /* Get file information. */
794 if (__builtin_expect (__fxstat64 (_STAT_VER, fd, &st) < 0, 0))
796 errstring = N_("cannot stat shared object");
797 call_lose_errno:
798 errval = errno;
799 call_lose:
800 lose (errval, fd, name, realname, l, errstring);
803 /* Look again to see if the real name matched another already loaded. */
804 for (l = GL(dl_loaded); l; l = l->l_next)
805 if (l->l_ino == st.st_ino && l->l_dev == st.st_dev)
807 /* The object is already loaded.
808 Just bump its reference count and return it. */
809 __close (fd);
811 /* If the name is not in the list of names for this object add
812 it. */
813 free (realname);
814 add_name_to_object (l, name);
816 return l;
819 if (mode & RTLD_NOLOAD)
820 /* We are not supposed to load the object unless it is already
821 loaded. So return now. */
822 return NULL;
824 /* Print debugging message. */
825 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0))
826 INTUSE(_dl_debug_printf) ("file=%s; generating link map\n", name);
828 /* This is the ELF header. We read it in `open_verify'. */
829 header = (void *) fbp->buf;
831 #ifndef MAP_ANON
832 # define MAP_ANON 0
833 if (_dl_zerofd == -1)
835 _dl_zerofd = _dl_sysdep_open_zero_fill ();
836 if (_dl_zerofd == -1)
838 __close (fd);
839 INTUSE(_dl_signal_error) (errno, NULL, NULL,
840 N_("cannot open zero fill device"));
843 #endif
845 /* Enter the new object in the list of loaded objects. */
846 l = _dl_new_object (realname, name, l_type, loader);
847 if (__builtin_expect (! l, 0))
849 errstring = N_("cannot create shared object descriptor");
850 goto call_lose_errno;
853 /* Extract the remaining details we need from the ELF header
854 and then read in the program header table. */
855 l->l_entry = header->e_entry;
856 type = header->e_type;
857 l->l_phnum = header->e_phnum;
859 maplength = header->e_phnum * sizeof (ElfW(Phdr));
860 if (header->e_phoff + maplength <= (size_t) fbp->len)
861 phdr = (void *) (fbp->buf + header->e_phoff);
862 else
864 phdr = alloca (maplength);
865 __lseek (fd, header->e_phoff, SEEK_SET);
866 if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
868 errstring = N_("cannot read file data");
869 goto call_lose_errno;
874 /* Scan the program header table, collecting its load commands. */
875 struct loadcmd
877 ElfW(Addr) mapstart, mapend, dataend, allocend;
878 off_t mapoff;
879 int prot;
880 } loadcmds[l->l_phnum], *c;
881 size_t nloadcmds = 0;
883 /* The struct is initialized to zero so this is not necessary:
884 l->l_ld = 0;
885 l->l_phdr = 0;
886 l->l_addr = 0; */
887 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
888 switch (ph->p_type)
890 /* These entries tell us where to find things once the file's
891 segments are mapped in. We record the addresses it says
892 verbatim, and later correct for the run-time load address. */
893 case PT_DYNAMIC:
894 l->l_ld = (void *) ph->p_vaddr;
895 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
896 break;
898 case PT_PHDR:
899 l->l_phdr = (void *) ph->p_vaddr;
900 break;
902 case PT_LOAD:
903 /* A load command tells us to map in part of the file.
904 We record the load commands and process them all later. */
905 if (__builtin_expect ((ph->p_align & (GL(dl_pagesize) - 1)) != 0,
908 errstring = N_("ELF load command alignment not page-aligned");
909 goto call_lose;
911 if (__builtin_expect (((ph->p_vaddr - ph->p_offset)
912 & (ph->p_align - 1)) != 0, 0))
914 errstring
915 = N_("ELF load command address/offset not properly aligned");
916 goto call_lose;
920 struct loadcmd *c = &loadcmds[nloadcmds++];
921 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
922 c->mapend = ((ph->p_vaddr + ph->p_filesz + GL(dl_pagesize) - 1)
923 & ~(GL(dl_pagesize) - 1));
924 c->dataend = ph->p_vaddr + ph->p_filesz;
925 c->allocend = ph->p_vaddr + ph->p_memsz;
926 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
928 /* Optimize a common case. */
929 #if (PF_R | PF_W | PF_X) == 7 && (PROT_READ | PROT_WRITE | PROT_EXEC) == 7
930 c->prot = (PF_TO_PROT
931 >> ((ph->p_flags & (PF_R | PF_W | PF_X)) * 4)) & 0xf;
932 #else
933 c->prot = 0;
934 if (ph->p_flags & PF_R)
935 c->prot |= PROT_READ;
936 if (ph->p_flags & PF_W)
937 c->prot |= PROT_WRITE;
938 if (ph->p_flags & PF_X)
939 c->prot |= PROT_EXEC;
940 #endif
942 break;
944 case PT_TLS:
945 #ifdef USE_TLS
946 if (ph->p_memsz > 0)
948 l->l_tls_blocksize = ph->p_memsz;
949 l->l_tls_align = ph->p_align;
950 l->l_tls_initimage_size = ph->p_filesz;
951 /* Since we don't know the load address yet only store the
952 offset. We will adjust it later. */
953 l->l_tls_initimage = (void *) ph->p_vaddr;
955 /* Assign the next available module ID. */
956 l->l_tls_modid = _dl_next_tls_modid ();
958 #else
959 /* Uh-oh, the binary expects TLS support but we cannot
960 provide it. */
961 _dl_fatal_printf ("cannot handle file '%s' with TLS data\n", name);
962 #endif
963 break;
966 /* Now process the load commands and map segments into memory. */
967 c = loadcmds;
969 /* Length of the sections to be loaded. */
970 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
972 if (__builtin_expect (type, ET_DYN) == ET_DYN)
974 /* This is a position-independent shared object. We can let the
975 kernel map it anywhere it likes, but we must have space for all
976 the segments in their specified positions relative to the first.
977 So we map the first segment without MAP_FIXED, but with its
978 extent increased to cover all the segments. Then we remove
979 access from excess portion, and there is known sufficient space
980 there to remap from the later segments.
982 As a refinement, sometimes we have an address that we would
983 prefer to map such objects at; but this is only a preference,
984 the OS can do whatever it likes. */
985 ElfW(Addr) mappref;
986 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
987 - MAP_BASE_ADDR (l));
989 /* Remember which part of the address space this object uses. */
990 l->l_map_start = (ElfW(Addr)) __mmap ((void *) mappref, maplength,
991 c->prot, MAP_COPY | MAP_FILE,
992 fd, c->mapoff);
993 if (__builtin_expect ((void *) l->l_map_start == MAP_FAILED, 0))
995 map_error:
996 errstring = N_("failed to map segment from shared object");
997 goto call_lose_errno;
1000 l->l_map_end = l->l_map_start + maplength;
1001 l->l_addr = l->l_map_start - c->mapstart;
1003 /* Change protection on the excess portion to disallow all access;
1004 the portions we do not remap later will be inaccessible as if
1005 unallocated. Then jump into the normal segment-mapping loop to
1006 handle the portion of the segment past the end of the file
1007 mapping. */
1008 __mprotect ((caddr_t) (l->l_addr + c->mapend),
1009 loadcmds[nloadcmds - 1].allocend - c->mapend,
1010 PROT_NONE);
1012 goto postmap;
1014 else
1016 /* This object is loaded at a fixed address. This must never
1017 happen for objects loaded with dlopen(). */
1018 if (__builtin_expect (mode & __RTLD_DLOPEN, 0))
1020 errstring = N_("cannot dynamically load executable");
1021 goto call_lose;
1024 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
1025 fixed. */
1026 ELF_FIXED_ADDRESS (loader, c->mapstart);
1029 /* Remember which part of the address space this object uses. */
1030 l->l_map_start = c->mapstart + l->l_addr;
1031 l->l_map_end = l->l_map_start + maplength;
1033 while (c < &loadcmds[nloadcmds])
1035 if (c->mapend > c->mapstart
1036 /* Map the segment contents from the file. */
1037 && (__mmap ((void *) (l->l_addr + c->mapstart),
1038 c->mapend - c->mapstart, c->prot,
1039 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff)
1040 == MAP_FAILED))
1041 goto map_error;
1043 postmap:
1044 if (l->l_phdr == 0
1045 && (ElfW(Off)) c->mapoff <= header->e_phoff
1046 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
1047 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
1048 /* Found the program header in this segment. */
1049 l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff);
1051 if (c->allocend > c->dataend)
1053 /* Extra zero pages should appear at the end of this segment,
1054 after the data mapped from the file. */
1055 ElfW(Addr) zero, zeroend, zeropage;
1057 zero = l->l_addr + c->dataend;
1058 zeroend = l->l_addr + c->allocend;
1059 zeropage = ((zero + GL(dl_pagesize) - 1)
1060 & ~(GL(dl_pagesize) - 1));
1062 if (zeroend < zeropage)
1063 /* All the extra data is in the last page of the segment.
1064 We can just zero it. */
1065 zeropage = zeroend;
1067 if (zeropage > zero)
1069 /* Zero the final part of the last page of the segment. */
1070 if ((c->prot & PROT_WRITE) == 0)
1072 /* Dag nab it. */
1073 if (__builtin_expect (__mprotect ((caddr_t)
1074 (zero
1075 & ~(GL(dl_pagesize)
1076 - 1)),
1077 GL(dl_pagesize),
1078 c->prot|PROT_WRITE) < 0,
1081 errstring = N_("cannot change memory protections");
1082 goto call_lose_errno;
1085 memset ((void *) zero, '\0', zeropage - zero);
1086 if ((c->prot & PROT_WRITE) == 0)
1087 __mprotect ((caddr_t) (zero & ~(GL(dl_pagesize) - 1)),
1088 GL(dl_pagesize), c->prot);
1091 if (zeroend > zeropage)
1093 /* Map the remaining zero pages in from the zero fill FD. */
1094 caddr_t mapat;
1095 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
1096 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
1097 ANONFD, 0);
1098 if (__builtin_expect (mapat == MAP_FAILED, 0))
1100 errstring = N_("cannot map zero-fill pages");
1101 goto call_lose_errno;
1106 ++c;
1109 if (l->l_phdr == NULL)
1111 /* The program header is not contained in any of the segments.
1112 We have to allocate memory ourself and copy it over from
1113 out temporary place. */
1114 ElfW(Phdr) *newp = (ElfW(Phdr) *) malloc (header->e_phnum
1115 * sizeof (ElfW(Phdr)));
1116 if (newp == NULL)
1118 errstring = N_("cannot allocate memory for program header");
1119 goto call_lose_errno;
1122 l->l_phdr = memcpy (newp, phdr,
1123 (header->e_phnum * sizeof (ElfW(Phdr))));
1124 l->l_phdr_allocated = 1;
1126 else
1127 /* Adjust the PT_PHDR value by the runtime load address. */
1128 (ElfW(Addr)) l->l_phdr += l->l_addr;
1131 #ifdef USE_TLS
1132 /* Adjust the address of the TLS initialization image. */
1133 if (l->l_tls_initimage != NULL)
1134 l->l_tls_initimage = (char *) l->l_tls_initimage + l->l_addr;
1135 #endif
1137 /* We are done mapping in the file. We no longer need the descriptor. */
1138 __close (fd);
1139 /* Signal that we closed the file. */
1140 fd = -1;
1142 if (l->l_type == lt_library && type == ET_EXEC)
1143 l->l_type = lt_executable;
1145 if (l->l_ld == 0)
1147 if (__builtin_expect (type == ET_DYN, 0))
1149 errstring = N_("object file has no dynamic section");
1150 goto call_lose;
1153 else
1154 (ElfW(Addr)) l->l_ld += l->l_addr;
1156 l->l_entry += l->l_addr;
1158 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0))
1159 INTUSE(_dl_debug_printf) ("\
1160 dynamic: 0x%0*lx base: 0x%0*lx size: 0x%0*Zx\n\
1161 entry: 0x%0*lx phdr: 0x%0*lx phnum: %*u\n\n",
1162 (int) sizeof (void *) * 2,
1163 (unsigned long int) l->l_ld,
1164 (int) sizeof (void *) * 2,
1165 (unsigned long int) l->l_addr,
1166 (int) sizeof (void *) * 2, maplength,
1167 (int) sizeof (void *) * 2,
1168 (unsigned long int) l->l_entry,
1169 (int) sizeof (void *) * 2,
1170 (unsigned long int) l->l_phdr,
1171 (int) sizeof (void *) * 2, l->l_phnum);
1173 elf_get_dynamic_info (l);
1175 /* Make sure we are not dlopen'ing an object
1176 that has the DF_1_NOOPEN flag set. */
1177 if ((__builtin_expect (l->l_flags_1 & DF_1_NOOPEN, 0)
1178 #ifdef USE_TLS
1179 || __builtin_expect (l->l_flags & DF_STATIC_TLS, 0)
1180 #endif
1182 && (mode & __RTLD_DLOPEN))
1184 /* We are not supposed to load this object. Free all resources. */
1185 __munmap ((void *) l->l_map_start, l->l_map_end - l->l_map_start);
1187 if (!l->l_libname->dont_free)
1188 free (l->l_libname);
1190 if (l->l_phdr_allocated)
1191 free ((void *) l->l_phdr);
1193 errstring = N_("shared object cannot be dlopen()ed");
1194 goto call_lose;
1197 if (l->l_info[DT_HASH])
1198 _dl_setup_hash (l);
1200 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
1201 have to do this for the main map. */
1202 if (__builtin_expect (l->l_info[DT_SYMBOLIC] != NULL, 0)
1203 && &l->l_searchlist != l->l_scope[0])
1205 /* Create an appropriate searchlist. It contains only this map.
1207 XXX This is the definition of DT_SYMBOLIC in SysVr4. The old
1208 GNU ld.so implementation had a different interpretation which
1209 is more reasonable. We are prepared to add this possibility
1210 back as part of a GNU extension of the ELF format. */
1211 l->l_symbolic_searchlist.r_list =
1212 (struct link_map **) malloc (sizeof (struct link_map *));
1214 if (l->l_symbolic_searchlist.r_list == NULL)
1216 errstring = N_("cannot create searchlist");
1217 goto call_lose_errno;
1220 l->l_symbolic_searchlist.r_list[0] = l;
1221 l->l_symbolic_searchlist.r_nlist = 1;
1223 /* Now move the existing entries one back. */
1224 memmove (&l->l_scope[1], &l->l_scope[0],
1225 (l->l_scope_max - 1) * sizeof (l->l_scope[0]));
1227 /* Now add the new entry. */
1228 l->l_scope[0] = &l->l_symbolic_searchlist;
1231 /* Remember whether this object must be initialized first. */
1232 if (l->l_flags_1 & DF_1_INITFIRST)
1233 GL(dl_initfirst) = l;
1235 /* Finally the file information. */
1236 l->l_dev = st.st_dev;
1237 l->l_ino = st.st_ino;
1239 /* When we profile the SONAME might be needed for something else but
1240 loading. Add it right away. */
1241 if (__builtin_expect (GL(dl_profile) != NULL, 0)
1242 && l->l_info[DT_SONAME] != NULL)
1243 add_name_to_object (l, ((const char *) D_PTR (l, l_info[DT_STRTAB])
1244 + l->l_info[DT_SONAME]->d_un.d_val));
1246 return l;
1249 /* Print search path. */
1250 static void
1251 print_search_path (struct r_search_path_elem **list,
1252 const char *what, const char *name)
1254 char buf[max_dirnamelen + max_capstrlen];
1255 int first = 1;
1257 INTUSE(_dl_debug_printf) (" search path=");
1259 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
1261 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
1262 size_t cnt;
1264 for (cnt = 0; cnt < ncapstr; ++cnt)
1265 if ((*list)->status[cnt] != nonexisting)
1267 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
1268 if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
1269 cp[0] = '\0';
1270 else
1271 cp[-1] = '\0';
1273 _dl_debug_printf_c (first ? "%s" : ":%s", buf);
1274 first = 0;
1277 ++list;
1280 if (name != NULL)
1281 _dl_debug_printf_c ("\t\t(%s from file %s)\n", what,
1282 name[0] ? name : rtld_progname);
1283 else
1284 _dl_debug_printf_c ("\t\t(%s)\n", what);
1287 /* Open a file and verify it is an ELF file for this architecture. We
1288 ignore only ELF files for other architectures. Non-ELF files and
1289 ELF files with different header information cause fatal errors since
1290 this could mean there is something wrong in the installation and the
1291 user might want to know about this. */
1292 static int
1293 open_verify (const char *name, struct filebuf *fbp)
1295 /* This is the expected ELF header. */
1296 #define ELF32_CLASS ELFCLASS32
1297 #define ELF64_CLASS ELFCLASS64
1298 #ifndef VALID_ELF_HEADER
1299 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
1300 # define VALID_ELF_OSABI(osabi) (osabi == ELFOSABI_SYSV)
1301 # define VALID_ELF_ABIVERSION(ver) (ver == 0)
1302 #endif
1303 static const unsigned char expected[EI_PAD] =
1305 [EI_MAG0] = ELFMAG0,
1306 [EI_MAG1] = ELFMAG1,
1307 [EI_MAG2] = ELFMAG2,
1308 [EI_MAG3] = ELFMAG3,
1309 [EI_CLASS] = ELFW(CLASS),
1310 [EI_DATA] = byteorder,
1311 [EI_VERSION] = EV_CURRENT,
1312 [EI_OSABI] = ELFOSABI_SYSV,
1313 [EI_ABIVERSION] = 0
1315 static const struct
1317 ElfW(Word) vendorlen;
1318 ElfW(Word) datalen;
1319 ElfW(Word) type;
1320 char vendor[4];
1321 } expected_note = { 4, 16, 1, "GNU" };
1322 int fd;
1323 /* Initialize it to make the compiler happy. */
1324 const char *errstring = NULL;
1325 int errval = 0;
1327 /* Open the file. We always open files read-only. */
1328 fd = __open (name, O_RDONLY);
1329 if (fd != -1)
1331 ElfW(Ehdr) *ehdr;
1332 ElfW(Phdr) *phdr, *ph;
1333 ElfW(Word) *abi_note, abi_note_buf[8];
1334 unsigned int osversion;
1335 size_t maplength;
1337 /* We successfully openened the file. Now verify it is a file
1338 we can use. */
1339 __set_errno (0);
1340 fbp->len = __libc_read (fd, fbp->buf, sizeof (fbp->buf));
1342 /* This is where the ELF header is loaded. */
1343 assert (sizeof (fbp->buf) > sizeof (ElfW(Ehdr)));
1344 ehdr = (ElfW(Ehdr) *) fbp->buf;
1346 /* Now run the tests. */
1347 if (__builtin_expect (fbp->len < (ssize_t) sizeof (ElfW(Ehdr)), 0))
1349 errval = errno;
1350 errstring = (errval == 0
1351 ? N_("file too short") : N_("cannot read file data"));
1352 call_lose:
1353 lose (errval, fd, name, NULL, NULL, errstring);
1356 /* See whether the ELF header is what we expect. */
1357 if (__builtin_expect (! VALID_ELF_HEADER (ehdr->e_ident, expected,
1358 EI_PAD), 0))
1360 /* Something is wrong. */
1361 if (*(Elf32_Word *) &ehdr->e_ident !=
1362 #if BYTE_ORDER == LITTLE_ENDIAN
1363 ((ELFMAG0 << (EI_MAG0 * 8)) |
1364 (ELFMAG1 << (EI_MAG1 * 8)) |
1365 (ELFMAG2 << (EI_MAG2 * 8)) |
1366 (ELFMAG3 << (EI_MAG3 * 8)))
1367 #else
1368 ((ELFMAG0 << (EI_MAG3 * 8)) |
1369 (ELFMAG1 << (EI_MAG2 * 8)) |
1370 (ELFMAG2 << (EI_MAG1 * 8)) |
1371 (ELFMAG3 << (EI_MAG0 * 8)))
1372 #endif
1374 errstring = N_("invalid ELF header");
1375 else if (ehdr->e_ident[EI_CLASS] != ELFW(CLASS))
1376 /* This is not a fatal error. On architectures where
1377 32-bit and 64-bit binaries can be run this might
1378 happen. */
1379 goto close_and_out;
1380 else if (ehdr->e_ident[EI_DATA] != byteorder)
1382 if (BYTE_ORDER == BIG_ENDIAN)
1383 errstring = N_("ELF file data encoding not big-endian");
1384 else
1385 errstring = N_("ELF file data encoding not little-endian");
1387 else if (ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1388 errstring
1389 = N_("ELF file version ident does not match current one");
1390 /* XXX We should be able so set system specific versions which are
1391 allowed here. */
1392 else if (!VALID_ELF_OSABI (ehdr->e_ident[EI_OSABI]))
1393 errstring = N_("ELF file OS ABI invalid");
1394 else if (!VALID_ELF_ABIVERSION (ehdr->e_ident[EI_ABIVERSION]))
1395 errstring = N_("ELF file ABI version invalid");
1396 else
1397 /* Otherwise we don't know what went wrong. */
1398 errstring = N_("internal error");
1400 goto call_lose;
1403 if (__builtin_expect (ehdr->e_version, EV_CURRENT) != EV_CURRENT)
1405 errstring = N_("ELF file version does not match current one");
1406 goto call_lose;
1408 if (! __builtin_expect (elf_machine_matches_host (ehdr), 1))
1409 goto close_and_out;
1410 else if (__builtin_expect (ehdr->e_phentsize, sizeof (ElfW(Phdr)))
1411 != sizeof (ElfW(Phdr)))
1413 errstring = N_("ELF file's phentsize not the expected size");
1414 goto call_lose;
1416 else if (__builtin_expect (ehdr->e_type, ET_DYN) != ET_DYN
1417 && __builtin_expect (ehdr->e_type, ET_EXEC) != ET_EXEC)
1419 errstring = N_("only ET_DYN and ET_EXEC can be loaded");
1420 goto call_lose;
1423 maplength = ehdr->e_phnum * sizeof (ElfW(Phdr));
1424 if (ehdr->e_phoff + maplength <= (size_t) fbp->len)
1425 phdr = (void *) (fbp->buf + ehdr->e_phoff);
1426 else
1428 phdr = alloca (maplength);
1429 __lseek (fd, ehdr->e_phoff, SEEK_SET);
1430 if ((size_t) __libc_read (fd, (void *) phdr, maplength) != maplength)
1432 read_error:
1433 errval = errno;
1434 errstring = N_("cannot read file data");
1435 goto call_lose;
1439 /* Check .note.ABI-tag if present. */
1440 for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph)
1441 if (ph->p_type == PT_NOTE && ph->p_filesz == 32 && ph->p_align >= 4)
1443 if (ph->p_offset + 32 <= (size_t) fbp->len)
1444 abi_note = (void *) (fbp->buf + ph->p_offset);
1445 else
1447 __lseek (fd, ph->p_offset, SEEK_SET);
1448 if (__libc_read (fd, (void *) abi_note_buf, 32) != 32)
1449 goto read_error;
1451 abi_note = abi_note_buf;
1454 if (memcmp (abi_note, &expected_note, sizeof (expected_note)))
1455 continue;
1457 osversion = (abi_note[5] & 0xff) * 65536
1458 + (abi_note[6] & 0xff) * 256
1459 + (abi_note[7] & 0xff);
1460 if (abi_note[4] != __ABI_TAG_OS
1461 || (GL(dl_osversion) && GL(dl_osversion) < osversion))
1463 close_and_out:
1464 __close (fd);
1465 __set_errno (ENOENT);
1466 fd = -1;
1469 break;
1473 return fd;
1476 /* Try to open NAME in one of the directories in *DIRSP.
1477 Return the fd, or -1. If successful, fill in *REALNAME
1478 with the malloc'd full directory name. If it turns out
1479 that none of the directories in *DIRSP exists, *DIRSP is
1480 replaced with (void *) -1, and the old value is free()d
1481 if MAY_FREE_DIRS is true. */
1483 static int
1484 open_path (const char *name, size_t namelen, int preloaded,
1485 struct r_search_path_struct *sps, char **realname,
1486 struct filebuf *fbp)
1488 struct r_search_path_elem **dirs = sps->dirs;
1489 char *buf;
1490 int fd = -1;
1491 const char *current_what = NULL;
1492 int any = 0;
1494 buf = alloca (max_dirnamelen + max_capstrlen + namelen);
1497 struct r_search_path_elem *this_dir = *dirs;
1498 size_t buflen = 0;
1499 size_t cnt;
1500 char *edp;
1501 int here_any = 0;
1502 int err;
1504 /* If we are debugging the search for libraries print the path
1505 now if it hasn't happened now. */
1506 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0)
1507 && current_what != this_dir->what)
1509 current_what = this_dir->what;
1510 print_search_path (dirs, current_what, this_dir->where);
1513 edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1514 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1516 /* Skip this directory if we know it does not exist. */
1517 if (this_dir->status[cnt] == nonexisting)
1518 continue;
1520 buflen =
1521 ((char *) __mempcpy (__mempcpy (edp, capstr[cnt].str,
1522 capstr[cnt].len),
1523 name, namelen)
1524 - buf);
1526 /* Print name we try if this is wanted. */
1527 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1528 INTUSE(_dl_debug_printf) (" trying file=%s\n", buf);
1530 fd = open_verify (buf, fbp);
1531 if (this_dir->status[cnt] == unknown)
1533 if (fd != -1)
1534 this_dir->status[cnt] = existing;
1535 else
1537 /* We failed to open machine dependent library. Let's
1538 test whether there is any directory at all. */
1539 struct stat64 st;
1541 buf[buflen - namelen - 1] = '\0';
1543 if (__xstat64 (_STAT_VER, buf, &st) != 0
1544 || ! S_ISDIR (st.st_mode))
1545 /* The directory does not exist or it is no directory. */
1546 this_dir->status[cnt] = nonexisting;
1547 else
1548 this_dir->status[cnt] = existing;
1552 /* Remember whether we found any existing directory. */
1553 here_any |= this_dir->status[cnt] == existing;
1555 if (fd != -1 && __builtin_expect (preloaded, 0)
1556 && INTUSE(__libc_enable_secure))
1558 /* This is an extra security effort to make sure nobody can
1559 preload broken shared objects which are in the trusted
1560 directories and so exploit the bugs. */
1561 struct stat64 st;
1563 if (__fxstat64 (_STAT_VER, fd, &st) != 0
1564 || (st.st_mode & S_ISUID) == 0)
1566 /* The shared object cannot be tested for being SUID
1567 or this bit is not set. In this case we must not
1568 use this object. */
1569 __close (fd);
1570 fd = -1;
1571 /* We simply ignore the file, signal this by setting
1572 the error value which would have been set by `open'. */
1573 errno = ENOENT;
1578 if (fd != -1)
1580 *realname = (char *) malloc (buflen);
1581 if (*realname != NULL)
1583 memcpy (*realname, buf, buflen);
1584 return fd;
1586 else
1588 /* No memory for the name, we certainly won't be able
1589 to load and link it. */
1590 __close (fd);
1591 return -1;
1594 if (here_any && (err = errno) != ENOENT && err != EACCES)
1595 /* The file exists and is readable, but something went wrong. */
1596 return -1;
1598 /* Remember whether we found anything. */
1599 any |= here_any;
1601 while (*++dirs != NULL);
1603 /* Remove the whole path if none of the directories exists. */
1604 if (__builtin_expect (! any, 0))
1606 /* Paths which were allocated using the minimal malloc() in ld.so
1607 must not be freed using the general free() in libc. */
1608 if (sps->malloced)
1609 free (sps->dirs);
1610 sps->dirs = (void *) -1;
1613 return -1;
1616 /* Map in the shared object file NAME. */
1618 struct link_map *
1619 internal_function
1620 _dl_map_object (struct link_map *loader, const char *name, int preloaded,
1621 int type, int trace_mode, int mode)
1623 int fd;
1624 char *realname;
1625 char *name_copy;
1626 struct link_map *l;
1627 struct filebuf fb;
1629 /* Look for this name among those already loaded. */
1630 for (l = GL(dl_loaded); l; l = l->l_next)
1632 /* If the requested name matches the soname of a loaded object,
1633 use that object. Elide this check for names that have not
1634 yet been opened. */
1635 if (__builtin_expect (l->l_faked, 0) != 0)
1636 continue;
1637 if (!_dl_name_match_p (name, l))
1639 const char *soname;
1641 if (__builtin_expect (l->l_soname_added, 1)
1642 || l->l_info[DT_SONAME] == NULL)
1643 continue;
1645 soname = ((const char *) D_PTR (l, l_info[DT_STRTAB])
1646 + l->l_info[DT_SONAME]->d_un.d_val);
1647 if (strcmp (name, soname) != 0)
1648 continue;
1650 /* We have a match on a new name -- cache it. */
1651 add_name_to_object (l, soname);
1652 l->l_soname_added = 1;
1655 /* We have a match. */
1656 return l;
1659 /* Display information if we are debugging. */
1660 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0)
1661 && loader != NULL)
1662 INTUSE(_dl_debug_printf) ("\nfile=%s; needed by %s\n", name,
1663 loader->l_name[0]
1664 ? loader->l_name : rtld_progname);
1666 if (strchr (name, '/') == NULL)
1668 /* Search for NAME in several places. */
1670 size_t namelen = strlen (name) + 1;
1672 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1673 INTUSE(_dl_debug_printf) ("find library=%s; searching\n", name);
1675 fd = -1;
1677 /* When the object has the RUNPATH information we don't use any
1678 RPATHs. */
1679 if (loader == NULL || loader->l_info[DT_RUNPATH] == NULL)
1681 /* First try the DT_RPATH of the dependent object that caused NAME
1682 to be loaded. Then that object's dependent, and on up. */
1683 for (l = loader; fd == -1 && l; l = l->l_loader)
1685 if (l->l_rpath_dirs.dirs == NULL)
1687 if (l->l_info[DT_RPATH] == NULL)
1689 /* There is no path. */
1690 l->l_rpath_dirs.dirs = (void *) -1;
1691 continue;
1693 else
1695 /* Make sure the cache information is available. */
1696 size_t ptrval = (D_PTR (l, l_info[DT_STRTAB])
1697 + l->l_info[DT_RPATH]->d_un.d_val);
1698 decompose_rpath (&l->l_rpath_dirs,
1699 (const char *) ptrval, l, "RPATH");
1703 if (l->l_rpath_dirs.dirs != (void *) -1)
1704 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1705 &realname, &fb);
1708 /* If dynamically linked, try the DT_RPATH of the executable
1709 itself. */
1710 l = GL(dl_loaded);
1711 if (fd == -1 && l && l->l_type != lt_loaded && l != loader
1712 && l->l_rpath_dirs.dirs != (void *) -1)
1713 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1714 &realname, &fb);
1717 /* Try the LD_LIBRARY_PATH environment variable. */
1718 if (fd == -1 && env_path_list.dirs != (void *) -1)
1719 fd = open_path (name, namelen, preloaded, &env_path_list,
1720 &realname, &fb);
1722 /* Look at the RUNPATH information for this binary.
1724 Note that this is no real loop. 'while' is used only to enable
1725 us to use 'break' instead of a 'goto' to jump to the end. The
1726 loop is always left after the first round. */
1727 while (fd == -1 && loader != NULL
1728 && loader->l_runpath_dirs.dirs != (void *) -1)
1730 if (loader->l_runpath_dirs.dirs == NULL)
1732 if (loader->l_info[DT_RUNPATH] == NULL)
1734 /* No RUNPATH. */
1735 loader->l_runpath_dirs.dirs = (void *) -1;
1736 break;
1738 else
1740 /* Make sure the cache information is available. */
1741 size_t ptrval = (D_PTR (loader, l_info[DT_STRTAB])
1742 + loader->l_info[DT_RUNPATH]->d_un.d_val);
1743 decompose_rpath (&loader->l_runpath_dirs,
1744 (const char *) ptrval, loader, "RUNPATH");
1748 if (loader->l_runpath_dirs.dirs != (void *) -1)
1749 fd = open_path (name, namelen, preloaded,
1750 &loader->l_runpath_dirs, &realname, &fb);
1751 break;
1754 if (fd == -1
1755 && (__builtin_expect (! preloaded, 1)
1756 || ! INTUSE(__libc_enable_secure)))
1758 /* Check the list of libraries in the file /etc/ld.so.cache,
1759 for compatibility with Linux's ldconfig program. */
1760 const char *cached = _dl_load_cache_lookup (name);
1762 if (cached != NULL)
1764 #ifdef SHARED
1765 l = loader ?: GL(dl_loaded);
1766 #else
1767 l = loader;
1768 #endif
1770 /* If the loader has the DF_1_NODEFLIB flag set we must not
1771 use a cache entry from any of these directories. */
1772 if (
1773 #ifndef SHARED
1774 /* 'l' is always != NULL for dynamically linked objects. */
1775 l != NULL &&
1776 #endif
1777 __builtin_expect (l->l_flags_1 & DF_1_NODEFLIB, 0))
1779 const char *dirp = system_dirs;
1780 unsigned int cnt = 0;
1784 if (memcmp (cached, dirp, system_dirs_len[cnt]) == 0)
1786 /* The prefix matches. Don't use the entry. */
1787 cached = NULL;
1788 break;
1791 dirp += system_dirs_len[cnt] + 1;
1792 ++cnt;
1794 while (cnt < nsystem_dirs_len);
1797 if (cached != NULL)
1799 fd = open_verify (cached, &fb);
1800 if (__builtin_expect (fd != -1, 1))
1802 realname = local_strdup (cached);
1803 if (realname == NULL)
1805 __close (fd);
1806 fd = -1;
1813 /* Finally, try the default path. */
1814 if (fd == -1
1815 && ((l = loader ?: GL(dl_loaded)) == NULL
1816 || __builtin_expect (!(l->l_flags_1 & DF_1_NODEFLIB), 1))
1817 && rtld_search_dirs.dirs != (void *) -1)
1818 fd = open_path (name, namelen, preloaded, &rtld_search_dirs,
1819 &realname, &fb);
1821 /* Add another newline when we are tracing the library loading. */
1822 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1823 INTUSE(_dl_debug_printf) ("\n");
1825 else
1827 /* The path may contain dynamic string tokens. */
1828 realname = (loader
1829 ? expand_dynamic_string_token (loader, name)
1830 : local_strdup (name));
1831 if (realname == NULL)
1832 fd = -1;
1833 else
1835 fd = open_verify (realname, &fb);
1836 if (__builtin_expect (fd, 0) == -1)
1837 free (realname);
1841 if (__builtin_expect (fd, 0) == -1)
1843 if (trace_mode
1844 && __builtin_expect (GL(dl_debug_mask) & DL_DEBUG_PRELINK, 0) == 0)
1846 /* We haven't found an appropriate library. But since we
1847 are only interested in the list of libraries this isn't
1848 so severe. Fake an entry with all the information we
1849 have. */
1850 static const Elf_Symndx dummy_bucket = STN_UNDEF;
1852 /* Enter the new object in the list of loaded objects. */
1853 if ((name_copy = local_strdup (name)) == NULL
1854 || (l = _dl_new_object (name_copy, name, type, loader)) == NULL)
1855 INTUSE(_dl_signal_error) (ENOMEM, name, NULL, N_("\
1856 cannot create shared object descriptor"));
1857 /* Signal that this is a faked entry. */
1858 l->l_faked = 1;
1859 /* Since the descriptor is initialized with zero we do not
1860 have do this here.
1861 l->l_reserved = 0; */
1862 l->l_buckets = &dummy_bucket;
1863 l->l_nbuckets = 1;
1864 l->l_relocated = 1;
1866 return l;
1868 else
1869 INTUSE(_dl_signal_error) (errno, name, NULL,
1870 N_("cannot open shared object file"));
1873 return _dl_map_object_from_fd (name, fd, &fb, realname, loader, type, mode);
1875 INTDEF (_dl_map_object)