1 /* Map in a shared object's segments from the file.
2 Copyright (C) 1995, 1996, 1997, 1998, 1999 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 Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
26 #include <elf/ldsodefs.h>
28 #include <sys/param.h>
30 #include <sys/types.h>
31 #include "dynamic-link.h"
32 #include <stdio-common/_itoa.h>
36 /* On some systems, no flag bits are given to specify file mapping. */
41 /* The right way to map in the shared library files is MAP_COPY, which
42 makes a virtual copy of the data at the time of the mmap call; this
43 guarantees the mapped pages will be consistent even if the file is
44 overwritten. Some losing VM systems like Linux's lack MAP_COPY. All we
45 get is MAP_PRIVATE, which copies each page when it is modified; this
46 means if the file is overwritten, we may at some point get some pages
47 from the new version after starting with pages from the old version. */
49 # define MAP_COPY MAP_PRIVATE
52 /* Some systems link their relocatable objects for another base address
53 than 0. We want to know the base address for these such that we can
54 subtract this address from the segment addresses during mapping.
55 This results in a more efficient address space usage. Defaults to
56 zero for almost all systems. */
58 # define MAP_BASE_ADDR(l) 0
63 #if BYTE_ORDER == BIG_ENDIAN
64 # define byteorder ELFDATA2MSB
65 # define byteorder_name "big-endian"
66 #elif BYTE_ORDER == LITTLE_ENDIAN
67 # define byteorder ELFDATA2LSB
68 # define byteorder_name "little-endian"
70 # error "Unknown BYTE_ORDER " BYTE_ORDER
71 # define byteorder ELFDATANONE
74 #define STRING(x) __STRING (x)
77 /* The fd is not examined when using MAP_ANON. */
81 # define ANONFD _dl_zerofd
84 /* Handle situations where we have a preferred location in memory for
85 the shared objects. */
86 #ifdef ELF_PREFERRED_ADDRESS_DATA
87 ELF_PREFERRED_ADDRESS_DATA
;
89 #ifndef ELF_PREFERRED_ADDRESS
90 # define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
92 #ifndef ELF_FIXED_ADDRESS
93 # define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
98 extern const char *_dl_platform
;
99 extern size_t _dl_platformlen
;
101 /* This is the decomposed LD_LIBRARY_PATH search path. */
102 static struct r_search_path_elem
**env_path_list
;
104 /* List of the hardware capabilities we might end up using. */
105 static const struct r_strlenpair
*capstr
;
106 static size_t ncapstr
;
107 static size_t max_capstrlen
;
109 const unsigned char _dl_pf_to_prot
[8] =
114 [PF_R
| PF_W
] = PROT_READ
| PROT_WRITE
,
116 [PF_R
| PF_X
] = PROT_READ
| PROT_EXEC
,
117 [PF_W
| PF_X
] = PROT_WRITE
| PROT_EXEC
,
118 [PF_R
| PF_W
| PF_X
] = PROT_READ
| PROT_WRITE
| PROT_EXEC
122 /* Get the generated information about the trusted directories. */
123 #include "trusted-dirs.h"
125 static const char system_dirs
[] = SYSTEM_DIRS
;
126 static const size_t system_dirs_len
[] =
131 /* This function has no public prototype. */
132 extern ssize_t
__libc_read (int, void *, size_t);
135 /* Local version of `strdup' function. */
137 local_strdup (const char *s
)
139 size_t len
= strlen (s
) + 1;
140 void *new = malloc (len
);
145 return (char *) memcpy (new, s
, len
);
150 _dl_dst_count (const char *name
, int is_path
)
152 const char *const start
= name
;
159 /* $ORIGIN is not expanded for SUID/GUID programs.
161 Note that it is no bug that the strings in the first two `strncmp'
162 calls are longer than the sequence which is actually tested. */
163 if ((((strncmp (&name
[1], "ORIGIN}", 6) == 0
164 && (!__libc_enable_secure
165 || ((name
[7] == '\0' || (is_path
&& name
[7] == ':'))
166 && (name
== start
|| (is_path
&& name
[-1] == ':'))))
168 || (strncmp (&name
[1], "PLATFORM}", 8) == 0 && (len
= 9) != 0))
169 && (name
[len
] == '\0' || name
[len
] == '/'
170 || (is_path
&& name
[len
] == ':')))
172 && ((strncmp (&name
[2], "ORIGIN}", 7) == 0
173 && (!__libc_enable_secure
174 || ((name
[9] == '\0' || (is_path
&& name
[9] == ':'))
175 && (name
== start
|| (is_path
&& name
[-1] == ':'))))
177 || (strncmp (&name
[2], "PLATFORM}", 9) == 0
178 && (len
= 11) != 0))))
181 name
= strchr (name
+ len
, '$');
183 while (name
!= NULL
);
190 _dl_dst_substitute (struct link_map
*l
, const char *name
, char *result
,
193 const char *const start
= name
;
194 char *last_elem
, *wp
;
196 /* Now fill the result path. While copying over the string we keep
197 track of the start of the last path element. When we come accross
198 a DST we copy over the value or (if the value is not available)
199 leave the entire path element out. */
200 last_elem
= wp
= result
;
209 /* Note that it is no bug that the strings in the first two `strncmp'
210 calls are longer than the sequence which is actually tested. */
211 if ((((strncmp (&name
[1], "ORIGIN}", 6) == 0 && (len
= 7) != 0)
212 || (strncmp (&name
[1], "PLATFORM}", 8) == 0 && (len
= 9) != 0))
213 && (name
[len
] == '\0' || name
[len
] == '/'
214 || (is_path
&& name
[len
] == ':')))
216 && ((strncmp (&name
[2], "ORIGIN}", 7) == 0 && (len
= 9) != 0)
217 || (strncmp (&name
[2], "PLATFORM}", 9) == 0
218 && (len
= 11) != 0))))
220 repl
= ((len
== 7 || name
[2] == 'O')
221 ? (__libc_enable_secure
222 && ((name
[len
] != '\0'
223 && (!is_path
|| name
[len
] != ':'))
225 && (!is_path
|| name
[-1] != ':')))
226 ? NULL
: l
->l_origin
)
229 if (repl
!= NULL
&& repl
!= (const char *) -1)
231 wp
= __stpcpy (wp
, repl
);
236 /* We cannot use this path element, the value of the
237 replacement is unknown. */
240 while (*name
!= '\0' && (!is_path
|| *name
!= ':'))
245 /* No DST we recognize. */
248 else if (is_path
&& *name
== ':')
256 while (*name
!= '\0');
264 /* Return copy of argument with all recognized dynamic string tokens
265 ($ORIGIN and $PLATFORM for now) replaced. On some platforms it
266 might not be possible to determine the path from which the object
267 belonging to the map is loaded. In this case the path element
268 containing $ORIGIN is left out. */
270 expand_dynamic_string_token (struct link_map
*l
, const char *s
)
272 /* We make two runs over the string. First we determine how large the
273 resulting string is and then we copy it over. Since this is now
274 frequently executed operation we are looking here not for performance
275 but rather for code size. */
280 /* Determine the number of DST elements. */
281 cnt
= DL_DST_COUNT (s
, 1);
283 /* If we do not have to replace anything simply copy the string. */
285 return local_strdup (s
);
287 /* Determine the length of the substituted string. */
288 total
= DL_DST_REQUIRED (l
, s
, strlen (s
), cnt
);
290 /* Allocate the necessary memory. */
291 result
= (char *) malloc (total
+ 1);
295 return DL_DST_SUBSTITUTE (l
, s
, result
, 1);
299 /* Add `name' to the list of names for a particular shared object.
300 `name' is expected to have been allocated with malloc and will
301 be freed if the shared object already has this name.
302 Returns false if the object already had this name. */
305 add_name_to_object (struct link_map
*l
, const char *name
)
307 struct libname_list
*lnp
, *lastp
;
308 struct libname_list
*newname
;
312 for (lnp
= l
->l_libname
; lnp
!= NULL
; lastp
= lnp
, lnp
= lnp
->next
)
313 if (strcmp (name
, lnp
->name
) == 0)
316 name_len
= strlen (name
) + 1;
317 newname
= malloc (sizeof *newname
+ name_len
);
320 /* No more memory. */
321 _dl_signal_error (ENOMEM
, name
, "cannot allocate name record");
324 /* The object should have a libname set from _dl_new_object. */
325 assert (lastp
!= NULL
);
327 newname
->name
= memcpy (newname
+ 1, name
, name_len
);
328 newname
->next
= NULL
;
329 lastp
->next
= newname
;
332 /* All known directories in sorted order. */
333 static struct r_search_path_elem
*all_dirs
;
335 /* Standard search directories. */
336 static struct r_search_path_elem
**rtld_search_dirs
;
338 static size_t max_dirnamelen
;
340 static inline struct r_search_path_elem
**
341 fillin_rpath (char *rpath
, struct r_search_path_elem
**result
, const char *sep
,
342 int check_trusted
, const char *what
, const char *where
)
347 while ((cp
= __strsep (&rpath
, sep
)) != NULL
)
349 struct r_search_path_elem
*dirp
;
350 size_t len
= strlen (cp
);
352 /* `strsep' can pass an empty string. This has to be
353 interpreted as `use the current directory'. */
356 static const char curwd
[] = "./";
360 /* Remove trailing slashes (except for "/"). */
361 while (len
> 1 && cp
[len
- 1] == '/')
364 /* Now add one if there is none so far. */
365 if (len
> 0 && cp
[len
- 1] != '/')
368 /* Make sure we don't use untrusted directories if we run SUID. */
371 const char *trun
= system_dirs
;
374 /* All trusted directories must be complete names. */
379 idx
< sizeof (system_dirs_len
) / sizeof (system_dirs_len
[0]);
382 if (len
== system_dirs_len
[idx
] && memcmp (trun
, cp
, len
) == 0)
386 trun
+= system_dirs_len
[idx
] + 1;
389 if (idx
== sizeof (system_dirs_len
) / sizeof (system_dirs_len
[0]))
390 /* It's no trusted directory, skip it. */
394 /* See if this directory is already known. */
395 for (dirp
= all_dirs
; dirp
!= NULL
; dirp
= dirp
->next
)
396 if (dirp
->dirnamelen
== len
&& memcmp (cp
, dirp
->dirname
, len
) == 0)
401 /* It is available, see whether it's on our own list. */
403 for (cnt
= 0; cnt
< nelems
; ++cnt
)
404 if (result
[cnt
] == dirp
)
408 result
[nelems
++] = dirp
;
414 /* It's a new directory. Create an entry and add it. */
415 dirp
= (struct r_search_path_elem
*)
416 malloc (sizeof (*dirp
) + ncapstr
* sizeof (enum r_dir_status
));
418 _dl_signal_error (ENOMEM
, NULL
,
419 "cannot create cache for search path");
422 dirp
->dirnamelen
= len
;
424 if (len
> max_dirnamelen
)
425 max_dirnamelen
= len
;
427 /* We have to make sure all the relative directories are never
428 ignored. The current directory might change and all our
429 saved information would be void. */
431 for (cnt
= 0; cnt
< ncapstr
; ++cnt
)
432 dirp
->status
[cnt
] = existing
;
434 for (cnt
= 0; cnt
< ncapstr
; ++cnt
)
435 dirp
->status
[cnt
] = unknown
;
440 dirp
->next
= all_dirs
;
443 /* Put it in the result array. */
444 result
[nelems
++] = dirp
;
448 /* Terminate the array. */
449 result
[nelems
] = NULL
;
455 static struct r_search_path_elem
**
457 decompose_rpath (const char *rpath
, struct link_map
*l
, const char *what
)
459 /* Make a copy we can work with. */
460 const char *where
= l
->l_name
;
463 struct r_search_path_elem
**result
;
466 /* First see whether we must forget the RUNPATH and RPATH from this
468 if (_dl_inhibit_rpath
!= NULL
&& !__libc_enable_secure
)
470 const char *found
= strstr (_dl_inhibit_rpath
, where
);
473 size_t len
= strlen (where
);
474 if ((found
== _dl_inhibit_rpath
|| found
[-1] == ':')
475 && (found
[len
] == '\0' || found
[len
] == ':'))
477 /* This object is on the list of objects for which the
478 RUNPATH and RPATH must not be used. */
479 result
= (struct r_search_path_elem
**)
480 malloc (sizeof (*result
));
482 _dl_signal_error (ENOMEM
, NULL
,
483 "cannot create cache for search path");
491 /* Make a writable copy. At the same time expand possible dynamic
493 copy
= expand_dynamic_string_token (l
, rpath
);
495 _dl_signal_error (ENOMEM
, NULL
, "cannot create RUNPATH/RPATH copy");
497 /* Count the number of necessary elements in the result array. */
499 for (cp
= copy
; *cp
!= '\0'; ++cp
)
503 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
504 number of necessary entries. */
505 result
= (struct r_search_path_elem
**) malloc ((nelems
+ 1 + 1)
508 _dl_signal_error (ENOMEM
, NULL
, "cannot create cache for search path");
510 return fillin_rpath (copy
, result
, ":", 0, what
, where
);
516 _dl_init_paths (const char *llp
)
520 struct r_search_path_elem
*pelem
, **aelem
;
526 /* Fill in the information about the application's RPATH and the
527 directories addressed by the LD_LIBRARY_PATH environment variable. */
529 /* Get the capabilities. */
530 capstr
= _dl_important_hwcaps (_dl_platform
, _dl_platformlen
,
531 &ncapstr
, &max_capstrlen
);
533 /* First set up the rest of the default search directory entries. */
534 aelem
= rtld_search_dirs
= (struct r_search_path_elem
**)
535 malloc ((sizeof (system_dirs_len
) / sizeof (system_dirs_len
[0]) + 1)
536 * sizeof (struct r_search_path_elem
*));
537 if (rtld_search_dirs
== NULL
)
538 _dl_signal_error (ENOMEM
, NULL
, "cannot create search path array");
540 round_size
= ((2 * sizeof (struct r_search_path_elem
) - 1
541 + ncapstr
* sizeof (enum r_dir_status
))
542 / sizeof (struct r_search_path_elem
));
544 rtld_search_dirs
[0] = (struct r_search_path_elem
*)
545 malloc ((sizeof (system_dirs
) / sizeof (system_dirs
[0]))
546 * round_size
* sizeof (struct r_search_path_elem
));
547 if (rtld_search_dirs
[0] == NULL
)
548 _dl_signal_error (ENOMEM
, NULL
, "cannot create cache for search path");
550 pelem
= all_dirs
= rtld_search_dirs
[0];
560 pelem
->what
= "system search path";
563 pelem
->dirname
= strp
;
564 pelem
->dirnamelen
= system_dirs_len
[idx
];
565 strp
+= system_dirs_len
[idx
] + 1;
567 if (pelem
->dirname
[0] != '/')
568 for (cnt
= 0; cnt
< ncapstr
; ++cnt
)
569 pelem
->status
[cnt
] = existing
;
571 for (cnt
= 0; cnt
< ncapstr
; ++cnt
)
572 pelem
->status
[cnt
] = unknown
;
574 pelem
->next
= (++idx
== (sizeof (system_dirs_len
)
575 / sizeof (system_dirs_len
[0]))
576 ? NULL
: (pelem
+ round_size
));
580 while (idx
< sizeof (system_dirs_len
) / sizeof (system_dirs_len
[0]));
582 max_dirnamelen
= SYSTEM_DIRS_MAX_LEN
;
586 /* This points to the map of the main object. */
590 assert (l
->l_type
!= lt_loaded
);
592 if (l
->l_info
[DT_RUNPATH
])
594 /* Allocate room for the search path and fill in information
597 decompose_rpath ((const void *) (l
->l_info
[DT_STRTAB
]->d_un
.d_ptr
598 + l
->l_info
[DT_RUNPATH
]->d_un
.d_val
),
601 /* The RPATH is ignored. */
602 l
->l_rpath_dirs
= NULL
;
606 l
->l_runpath_dirs
= NULL
;
608 if (l
->l_info
[DT_RPATH
])
609 /* Allocate room for the search path and fill in information
612 decompose_rpath ((const void *) (l
->l_info
[DT_STRTAB
]->d_un
.d_ptr
613 + l
->l_info
[DT_RPATH
]->d_un
.d_val
),
616 l
->l_rpath_dirs
= NULL
;
621 if (llp
!= NULL
&& *llp
!= '\0')
624 const char *cp
= llp
;
626 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
631 if (*cp
== ':' || *cp
== ';')
636 env_path_list
= (struct r_search_path_elem
**)
637 malloc ((nllp
+ 1) * sizeof (struct r_search_path_elem
*));
638 if (env_path_list
== NULL
)
639 _dl_signal_error (ENOMEM
, NULL
,
640 "cannot create cache for search path");
642 (void) fillin_rpath (local_strdup (llp
), env_path_list
, ":;",
643 __libc_enable_secure
, "LD_LIBRARY_PATH", NULL
);
648 /* Think twice before changing anything in this function. It is placed
649 here and prepared using the `alloca' magic to prevent it from being
650 inlined. The function is only called in case of an error. But then
651 performance does not count. The function used to be "inlinable" and
652 the compiled did so all the time. This increased the code size for
653 absolutely no good reason. */
654 #define LOSE(code, s) lose (code, fd, name, realname, l, s)
656 __attribute__ ((noreturn
))
657 lose (int code
, int fd
, const char *name
, char *realname
, struct link_map
*l
,
660 /* The use of `alloca' here looks ridiculous but it helps. The goal
661 is to avoid the function from being inlined. There is no official
662 way to do this so we use this trick. gcc never inlines functions
663 which use `alloca'. */
664 int *a
= alloca (sizeof (int));
666 (void) __close (a
[0]);
669 /* Remove the stillborn object from the list and free it. */
671 l
->l_prev
->l_next
= l
->l_next
;
673 l
->l_next
->l_prev
= l
->l_prev
;
677 _dl_signal_error (code
, name
, msg
);
681 /* Map in the shared object NAME, actually located in REALNAME, and already
684 #ifndef EXTERNAL_MAP_FROM_FD
688 _dl_map_object_from_fd (const char *name
, int fd
, char *realname
,
689 struct link_map
*loader
, int l_type
)
691 /* This is the expected ELF header. */
692 #define ELF32_CLASS ELFCLASS32
693 #define ELF64_CLASS ELFCLASS64
694 #ifndef VALID_ELF_HEADER
695 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
696 # define VALID_ELF_OSABI(osabi) (osabi == ELFOSABI_SYSV)
697 # define VALID_ELF_ABIVERSION(ver) (ver == 0)
699 static const unsigned char expected
[EI_PAD
] =
705 [EI_CLASS
] = ELFW(CLASS
),
706 [EI_DATA
] = byteorder
,
707 [EI_VERSION
] = EV_CURRENT
,
708 [EI_OSABI
] = ELFOSABI_SYSV
,
711 struct link_map
*l
= NULL
;
713 inline caddr_t
map_segment (ElfW(Addr
) mapstart
, size_t len
,
714 int prot
, int fixed
, off_t offset
)
716 caddr_t mapat
= __mmap ((caddr_t
) mapstart
, len
, prot
,
717 fixed
|MAP_COPY
|MAP_FILE
,
719 if (mapat
== MAP_FAILED
)
720 LOSE (errno
, "failed to map segment from shared object");
724 const ElfW(Ehdr
) *header
;
725 const ElfW(Phdr
) *phdr
;
726 const ElfW(Phdr
) *ph
;
733 /* Get file information. */
734 if (__fxstat (_STAT_VER
, fd
, &st
) < 0)
735 LOSE (errno
, "cannot stat shared object");
737 /* Look again to see if the real name matched another already loaded. */
738 for (l
= _dl_loaded
; l
; l
= l
->l_next
)
739 if (l
->l_ino
== st
.st_ino
&& l
->l_dev
== st
.st_dev
)
741 /* The object is already loaded.
742 Just bump its reference count and return it. */
745 /* If the name is not in the list of names for this object add
748 add_name_to_object (l
, name
);
753 /* Print debugging message. */
755 _dl_debug_message (1, "file=", name
, "; generating link map\n", NULL
);
757 /* Read the header directly. */
758 readbuf
= alloca (_dl_pagesize
);
759 readlength
= __libc_read (fd
, readbuf
, _dl_pagesize
);
760 if (readlength
< (ssize_t
) sizeof (*header
))
761 LOSE (errno
, "cannot read file data");
762 header
= (void *) readbuf
;
764 /* Check the header for basic validity. */
765 if (__builtin_expect (!VALID_ELF_HEADER (header
->e_ident
, expected
, EI_PAD
),
768 /* Something is wrong. */
769 if (*(Elf32_Word
*) &header
->e_ident
!=
770 #if BYTE_ORDER == LITTLE_ENDIAN
771 ((ELFMAG0
<< (EI_MAG0
* 8)) |
772 (ELFMAG1
<< (EI_MAG1
* 8)) |
773 (ELFMAG2
<< (EI_MAG2
* 8)) |
774 (ELFMAG3
<< (EI_MAG3
* 8)))
776 ((ELFMAG0
<< (EI_MAG3
* 8)) |
777 (ELFMAG1
<< (EI_MAG2
* 8)) |
778 (ELFMAG2
<< (EI_MAG1
* 8)) |
779 (ELFMAG3
<< (EI_MAG0
* 8)))
782 LOSE (0, "invalid ELF header");
783 if (header
->e_ident
[EI_CLASS
] != ELFW(CLASS
))
784 LOSE (0, "ELF file class not " STRING(__ELF_NATIVE_CLASS
) "-bit");
785 if (header
->e_ident
[EI_DATA
] != byteorder
)
786 LOSE (0, "ELF file data encoding not " byteorder_name
);
787 if (header
->e_ident
[EI_VERSION
] != EV_CURRENT
)
788 LOSE (0, "ELF file version ident not " STRING(EV_CURRENT
));
789 /* XXX We should be able so set system specific versions which are
791 if (!VALID_ELF_OSABI (header
->e_ident
[EI_OSABI
]))
792 LOSE (0, "ELF file OS ABI invalid.");
793 if (!VALID_ELF_ABIVERSION (header
->e_ident
[EI_ABIVERSION
]))
794 LOSE (0, "ELF file ABI version invalid.");
795 LOSE (0, "internal error");
798 if (__builtin_expect (header
->e_version
, EV_CURRENT
) != EV_CURRENT
)
799 LOSE (0, "ELF file version not " STRING(EV_CURRENT
));
800 if (! __builtin_expect (elf_machine_matches_host (header
->e_machine
), 1))
801 LOSE (0, "ELF file machine architecture not " ELF_MACHINE_NAME
);
802 if (__builtin_expect (header
->e_phentsize
, sizeof (ElfW(Phdr
)))
803 != sizeof (ElfW(Phdr
)))
804 LOSE (0, "ELF file's phentsize not the expected size");
808 if (_dl_zerofd
== -1)
810 _dl_zerofd
= _dl_sysdep_open_zero_fill ();
811 if (_dl_zerofd
== -1)
814 _dl_signal_error (errno
, NULL
, "cannot open zero fill device");
819 /* Enter the new object in the list of loaded objects. */
820 l
= _dl_new_object (realname
, name
, l_type
, loader
);
821 if (__builtin_expect (! l
, 0))
822 LOSE (ENOMEM
, "cannot create shared object descriptor");
825 /* Extract the remaining details we need from the ELF header
826 and then read in the program header table. */
827 l
->l_entry
= header
->e_entry
;
828 type
= header
->e_type
;
829 l
->l_phnum
= header
->e_phnum
;
831 maplength
= header
->e_phnum
* sizeof (ElfW(Phdr
));
832 if (header
->e_phoff
+ maplength
<= readlength
)
833 phdr
= (void *) (readbuf
+ header
->e_phoff
);
836 phdr
= alloca (maplength
);
837 __lseek (fd
, SEEK_SET
, header
->e_phoff
);
838 if (__libc_read (fd
, (void *) phdr
, maplength
) != maplength
)
839 LOSE (errno
, "cannot read file data");
843 /* Scan the program header table, collecting its load commands. */
846 ElfW(Addr
) mapstart
, mapend
, dataend
, allocend
;
849 } loadcmds
[l
->l_phnum
], *c
;
850 size_t nloadcmds
= 0;
852 /* The struct is initialized to zero so this is not necessary:
856 for (ph
= phdr
; ph
< &phdr
[l
->l_phnum
]; ++ph
)
859 /* These entries tell us where to find things once the file's
860 segments are mapped in. We record the addresses it says
861 verbatim, and later correct for the run-time load address. */
863 l
->l_ld
= (void *) ph
->p_vaddr
;
866 l
->l_phdr
= (void *) ph
->p_vaddr
;
870 /* A load command tells us to map in part of the file.
871 We record the load commands and process them all later. */
872 if (ph
->p_align
% _dl_pagesize
!= 0)
873 LOSE (0, "ELF load command alignment not page-aligned");
874 if ((ph
->p_vaddr
- ph
->p_offset
) % ph
->p_align
)
875 LOSE (0, "ELF load command address/offset not properly aligned");
877 struct loadcmd
*c
= &loadcmds
[nloadcmds
++];
878 c
->mapstart
= ph
->p_vaddr
& ~(ph
->p_align
- 1);
879 c
->mapend
= ((ph
->p_vaddr
+ ph
->p_filesz
+ _dl_pagesize
- 1)
880 & ~(_dl_pagesize
- 1));
881 c
->dataend
= ph
->p_vaddr
+ ph
->p_filesz
;
882 c
->allocend
= ph
->p_vaddr
+ ph
->p_memsz
;
883 c
->mapoff
= ph
->p_offset
& ~(ph
->p_align
- 1);
885 /* Optimize a common case. */
886 if ((PF_R
| PF_W
| PF_X
) == 7
887 && (PROT_READ
| PROT_WRITE
| PROT_EXEC
) == 7)
888 c
->prot
= _dl_pf_to_prot
[ph
->p_flags
& (PF_R
| PF_W
| PF_X
)];
892 if (ph
->p_flags
& PF_R
)
893 c
->prot
|= PROT_READ
;
894 if (ph
->p_flags
& PF_W
)
895 c
->prot
|= PROT_WRITE
;
896 if (ph
->p_flags
& PF_X
)
897 c
->prot
|= PROT_EXEC
;
903 /* Now process the load commands and map segments into memory. */
906 /* Length of the sections to be loaded. */
907 maplength
= loadcmds
[nloadcmds
- 1].allocend
- c
->mapstart
;
909 if (type
== ET_DYN
|| type
== ET_REL
)
911 /* This is a position-independent shared object. We can let the
912 kernel map it anywhere it likes, but we must have space for all
913 the segments in their specified positions relative to the first.
914 So we map the first segment without MAP_FIXED, but with its
915 extent increased to cover all the segments. Then we remove
916 access from excess portion, and there is known sufficient space
917 there to remap from the later segments.
919 As a refinement, sometimes we have an address that we would
920 prefer to map such objects at; but this is only a preference,
921 the OS can do whatever it likes. */
924 mappref
= (ELF_PREFERRED_ADDRESS (loader
, maplength
, c
->mapstart
)
925 - MAP_BASE_ADDR (l
));
926 mapat
= map_segment (mappref
, maplength
, c
->prot
, 0, c
->mapoff
);
927 l
->l_addr
= (ElfW(Addr
)) mapat
- c
->mapstart
;
929 /* Change protection on the excess portion to disallow all access;
930 the portions we do not remap later will be inaccessible as if
931 unallocated. Then jump into the normal segment-mapping loop to
932 handle the portion of the segment past the end of the file
934 __mprotect ((caddr_t
) (l
->l_addr
+ c
->mapend
),
935 loadcmds
[nloadcmds
- 1].allocend
- c
->mapend
,
938 /* Remember which part of the address space this object uses. */
939 l
->l_map_start
= c
->mapstart
+ l
->l_addr
;
940 l
->l_map_end
= l
->l_map_start
+ maplength
;
946 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
948 ELF_FIXED_ADDRESS (loader
, c
->mapstart
);
951 /* Remember which part of the address space this object uses. */
952 l
->l_map_start
= c
->mapstart
+ l
->l_addr
;
953 l
->l_map_end
= l
->l_map_start
+ maplength
;
955 while (c
< &loadcmds
[nloadcmds
])
957 if (c
->mapend
> c
->mapstart
)
958 /* Map the segment contents from the file. */
959 map_segment (l
->l_addr
+ c
->mapstart
, c
->mapend
- c
->mapstart
,
960 c
->prot
, MAP_FIXED
, c
->mapoff
);
964 && c
->mapoff
<= header
->e_phoff
965 && (c
->mapend
- c
->mapstart
+ c
->mapoff
966 >= header
->e_phoff
+ header
->e_phnum
* sizeof (ElfW(Phdr
))))
967 /* Found the program header in this segment. */
968 l
->l_phdr
= (void *) (c
->mapstart
+ header
->e_phoff
- c
->mapoff
);
970 if (c
->allocend
> c
->dataend
)
972 /* Extra zero pages should appear at the end of this segment,
973 after the data mapped from the file. */
974 ElfW(Addr
) zero
, zeroend
, zeropage
;
976 zero
= l
->l_addr
+ c
->dataend
;
977 zeroend
= l
->l_addr
+ c
->allocend
;
978 zeropage
= (zero
+ _dl_pagesize
- 1) & ~(_dl_pagesize
- 1);
980 if (zeroend
< zeropage
)
981 /* All the extra data is in the last page of the segment.
982 We can just zero it. */
987 /* Zero the final part of the last page of the segment. */
988 if ((c
->prot
& PROT_WRITE
) == 0)
991 if (__mprotect ((caddr_t
) (zero
& ~(_dl_pagesize
- 1)),
992 _dl_pagesize
, c
->prot
|PROT_WRITE
) < 0)
993 LOSE (errno
, "cannot change memory protections");
995 memset ((void *) zero
, 0, zeropage
- zero
);
996 if ((c
->prot
& PROT_WRITE
) == 0)
997 __mprotect ((caddr_t
) (zero
& ~(_dl_pagesize
- 1)),
998 _dl_pagesize
, c
->prot
);
1001 if (zeroend
> zeropage
)
1003 /* Map the remaining zero pages in from the zero fill FD. */
1005 mapat
= __mmap ((caddr_t
) zeropage
, zeroend
- zeropage
,
1006 c
->prot
, MAP_ANON
|MAP_PRIVATE
|MAP_FIXED
,
1008 if (mapat
== MAP_FAILED
)
1009 LOSE (errno
, "cannot map zero-fill pages");
1016 if (l
->l_phdr
== NULL
)
1018 /* The program header is not contained in any of the segmenst.
1019 We have to allocate memory ourself and copy it over from
1020 out temporary place. */
1021 ElfW(Phdr
) *newp
= (ElfW(Phdr
) *) malloc (header
->e_phnum
1022 * sizeof (ElfW(Phdr
)));
1024 LOSE (ENOMEM
, "cannot allocate memory for program header");
1026 l
->l_phdr
= memcpy (newp
, phdr
,
1027 (header
->e_phnum
* sizeof (ElfW(Phdr
))));
1028 l
->l_phdr_allocated
= 1;
1031 /* Adjust the PT_PHDR value by the runtime load address. */
1032 (ElfW(Addr
)) l
->l_phdr
+= l
->l_addr
;
1035 /* We are done mapping in the file. We no longer need the descriptor. */
1038 if (l
->l_type
== lt_library
&& type
== ET_EXEC
)
1039 l
->l_type
= lt_executable
;
1044 LOSE (0, "object file has no dynamic section");
1047 (ElfW(Addr
)) l
->l_ld
+= l
->l_addr
;
1049 l
->l_entry
+= l
->l_addr
;
1051 if (_dl_debug_files
)
1053 const size_t nibbles
= sizeof (void *) * 2;
1054 char buf1
[nibbles
+ 1];
1055 char buf2
[nibbles
+ 1];
1056 char buf3
[nibbles
+ 1];
1058 buf1
[nibbles
] = '\0';
1059 buf2
[nibbles
] = '\0';
1060 buf3
[nibbles
] = '\0';
1062 memset (buf1
, '0', nibbles
);
1063 memset (buf2
, '0', nibbles
);
1064 memset (buf3
, '0', nibbles
);
1065 _itoa_word ((unsigned long int) l
->l_ld
, &buf1
[nibbles
], 16, 0);
1066 _itoa_word ((unsigned long int) l
->l_addr
, &buf2
[nibbles
], 16, 0);
1067 _itoa_word (maplength
, &buf3
[nibbles
], 16, 0);
1069 _dl_debug_message (1, " dynamic: 0x", buf1
, " base: 0x", buf2
,
1070 " size: 0x", buf3
, "\n", NULL
);
1071 memset (buf1
, '0', nibbles
);
1072 memset (buf2
, '0', nibbles
);
1073 memset (buf3
, ' ', nibbles
);
1074 _itoa_word ((unsigned long int) l
->l_entry
, &buf1
[nibbles
], 16, 0);
1075 _itoa_word ((unsigned long int) l
->l_phdr
, &buf2
[nibbles
], 16, 0);
1076 _itoa_word (l
->l_phnum
, &buf3
[nibbles
], 10, 0);
1077 _dl_debug_message (1, " entry: 0x", buf1
, " phdr: 0x", buf2
,
1078 " phnum: ", buf3
, "\n\n", NULL
);
1081 elf_get_dynamic_info (l
);
1082 if (l
->l_info
[DT_HASH
])
1085 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
1086 have to do this for the main map. */
1087 if (l
->l_info
[DT_SYMBOLIC
] && &l
->l_searchlist
!= l
->l_scope
[0])
1089 /* Create an appropriate searchlist. It contains only this map.
1091 XXX This is the definition of DT_SYMBOLIC in SysVr4. The old
1092 GNU ld.so implementation had a different interpretation which
1093 is more reasonable. We are prepared to add this possibility
1094 back as part of a GNU extension of the ELF format. */
1095 l
->l_symbolic_searchlist
.r_list
=
1096 (struct link_map
**) malloc (sizeof (struct link_map
*));
1098 if (l
->l_symbolic_searchlist
.r_list
== NULL
)
1099 LOSE (ENOMEM
, "cannot create searchlist");
1101 l
->l_symbolic_searchlist
.r_list
[0] = l
;
1102 l
->l_symbolic_searchlist
.r_nlist
= 1;
1103 l
->l_symbolic_searchlist
.r_duplist
= l
->l_symbolic_searchlist
.r_list
;
1104 l
->l_symbolic_searchlist
.r_nduplist
= 1;
1106 /* Now move the existing entries one back. */
1107 memmove (&l
->l_scope
[1], &l
->l_scope
[0],
1108 sizeof (l
->l_scope
) - sizeof (l
->l_scope
[0]));
1110 /* Now add the new entry. */
1111 l
->l_scope
[0] = &l
->l_symbolic_searchlist
;
1114 /* Finally the file information. */
1115 l
->l_dev
= st
.st_dev
;
1116 l
->l_ino
= st
.st_ino
;
1121 /* Print search path. */
1123 print_search_path (struct r_search_path_elem
**list
,
1124 const char *what
, const char *name
)
1126 char buf
[max_dirnamelen
+ max_capstrlen
];
1129 _dl_debug_message (1, " search path=", NULL
);
1131 while (*list
!= NULL
&& (*list
)->what
== what
) /* Yes, ==. */
1133 char *endp
= __mempcpy (buf
, (*list
)->dirname
, (*list
)->dirnamelen
);
1136 for (cnt
= 0; cnt
< ncapstr
; ++cnt
)
1137 if ((*list
)->status
[cnt
] != nonexisting
)
1139 char *cp
= __mempcpy (endp
, capstr
[cnt
].str
, capstr
[cnt
].len
);
1140 if (cp
== buf
|| (cp
== buf
+ 1 && buf
[0] == '/'))
1144 _dl_debug_message (0, first
? "" : ":", buf
, NULL
);
1152 _dl_debug_message (0, "\t\t(", what
, " from file ",
1153 name
[0] ? name
: _dl_argv
[0], ")\n", NULL
);
1155 _dl_debug_message (0, "\t\t(", what
, ")\n", NULL
);
1158 /* Try to open NAME in one of the directories in DIRS.
1159 Return the fd, or -1. If successful, fill in *REALNAME
1160 with the malloc'd full directory name. */
1163 open_path (const char *name
, size_t namelen
, int preloaded
,
1164 struct r_search_path_elem
**dirs
,
1169 const char *current_what
= NULL
;
1171 if (dirs
== NULL
|| *dirs
== NULL
)
1173 __set_errno (ENOENT
);
1177 buf
= alloca (max_dirnamelen
+ max_capstrlen
+ namelen
);
1180 struct r_search_path_elem
*this_dir
= *dirs
;
1185 /* If we are debugging the search for libraries print the path
1186 now if it hasn't happened now. */
1187 if (_dl_debug_libs
&& current_what
!= this_dir
->what
)
1189 current_what
= this_dir
->what
;
1190 print_search_path (dirs
, current_what
, this_dir
->where
);
1193 edp
= (char *) __mempcpy (buf
, this_dir
->dirname
, this_dir
->dirnamelen
);
1194 for (cnt
= 0; fd
== -1 && cnt
< ncapstr
; ++cnt
)
1196 /* Skip this directory if we know it does not exist. */
1197 if (this_dir
->status
[cnt
] == nonexisting
)
1201 ((char *) __mempcpy (__mempcpy (edp
,
1202 capstr
[cnt
].str
, capstr
[cnt
].len
),
1206 /* Print name we try if this is wanted. */
1208 _dl_debug_message (1, " trying file=", buf
, "\n", NULL
);
1210 fd
= __open (buf
, O_RDONLY
);
1211 if (this_dir
->status
[cnt
] == unknown
)
1214 this_dir
->status
[cnt
] = existing
;
1217 /* We failed to open machine dependent library. Let's
1218 test whether there is any directory at all. */
1221 buf
[buflen
- namelen
- 1] = '\0';
1223 if (__xstat (_STAT_VER
, buf
, &st
) != 0
1224 || ! S_ISDIR (st
.st_mode
))
1225 /* The directory does not exist or it is no directory. */
1226 this_dir
->status
[cnt
] = nonexisting
;
1228 this_dir
->status
[cnt
] = existing
;
1232 if (fd
!= -1 && preloaded
&& __libc_enable_secure
)
1234 /* This is an extra security effort to make sure nobody can
1235 preload broken shared objects which are in the trusted
1236 directories and so exploit the bugs. */
1239 if (__fxstat (_STAT_VER
, fd
, &st
) != 0
1240 || (st
.st_mode
& S_ISUID
) == 0)
1242 /* The shared object cannot be tested for being SUID
1243 or this bit is not set. In this case we must not
1247 /* We simply ignore the file, signal this by setting
1248 the error value which would have been set by `open'. */
1256 *realname
= malloc (buflen
);
1257 if (*realname
!= NULL
)
1259 memcpy (*realname
, buf
, buflen
);
1264 /* No memory for the name, we certainly won't be able
1265 to load and link it. */
1270 if (errno
!= ENOENT
&& errno
!= EACCES
)
1271 /* The file exists and is readable, but something went wrong. */
1274 while (*++dirs
!= NULL
);
1279 /* Map in the shared object file NAME. */
1283 _dl_map_object (struct link_map
*loader
, const char *name
, int preloaded
,
1284 int type
, int trace_mode
)
1291 /* Look for this name among those already loaded. */
1292 for (l
= _dl_loaded
; l
; l
= l
->l_next
)
1294 /* If the requested name matches the soname of a loaded object,
1295 use that object. Elide this check for names that have not
1297 if (l
->l_opencount
<= 0)
1299 if (!_dl_name_match_p (name
, l
))
1303 if (l
->l_info
[DT_SONAME
] == NULL
)
1306 soname
= (const void *) (l
->l_info
[DT_STRTAB
]->d_un
.d_ptr
1307 + l
->l_info
[DT_SONAME
]->d_un
.d_val
);
1308 if (strcmp (name
, soname
) != 0)
1311 /* We have a match on a new name -- cache it. */
1312 add_name_to_object (l
, soname
);
1315 /* We have a match -- bump the reference count and return it. */
1320 /* Display information if we are debugging. */
1321 if (_dl_debug_files
&& loader
!= NULL
)
1322 _dl_debug_message (1, "\nfile=", name
, "; needed by ",
1323 loader
->l_name
[0] ? loader
->l_name
: _dl_argv
[0],
1326 if (strchr (name
, '/') == NULL
)
1328 /* Search for NAME in several places. */
1330 size_t namelen
= strlen (name
) + 1;
1333 _dl_debug_message (1, "find library=", name
, "; searching\n", NULL
);
1337 /* When the object has the RUNPATH information we don't use any
1339 if (loader
!= NULL
&& loader
->l_info
[DT_RUNPATH
] == NULL
)
1341 /* First try the DT_RPATH of the dependent object that caused NAME
1342 to be loaded. Then that object's dependent, and on up. */
1343 for (l
= loader
; fd
== -1 && l
; l
= l
->l_loader
)
1344 if (l
->l_info
[DT_RPATH
])
1346 /* Make sure the cache information is available. */
1347 if (l
->l_rpath_dirs
== NULL
)
1349 size_t ptrval
= (l
->l_info
[DT_STRTAB
]->d_un
.d_ptr
1350 + l
->l_info
[DT_RPATH
]->d_un
.d_val
);
1352 decompose_rpath ((const char *) ptrval
, l
, "RPATH");
1355 if (l
->l_rpath_dirs
!= NULL
)
1356 fd
= open_path (name
, namelen
, preloaded
, l
->l_rpath_dirs
,
1360 /* If dynamically linked, try the DT_RPATH of the executable
1363 if (fd
== -1 && l
&& l
->l_type
!= lt_loaded
&& l
!= loader
1364 && l
->l_rpath_dirs
!= NULL
)
1365 fd
= open_path (name
, namelen
, preloaded
, l
->l_rpath_dirs
,
1369 /* Try the LD_LIBRARY_PATH environment variable. */
1370 if (fd
== -1 && env_path_list
!= NULL
)
1371 fd
= open_path (name
, namelen
, preloaded
, env_path_list
, &realname
);
1373 /* Look at the RUNPATH informaiton for this binary. */
1374 if (loader
!= NULL
&& loader
->l_info
[DT_RUNPATH
])
1376 /* Make sure the cache information is available. */
1377 if (loader
->l_runpath_dirs
== NULL
)
1379 size_t ptrval
= (loader
->l_info
[DT_STRTAB
]->d_un
.d_ptr
1380 + loader
->l_info
[DT_RUNPATH
]->d_un
.d_val
);
1381 loader
->l_runpath_dirs
=
1382 decompose_rpath ((const char *) ptrval
, loader
, "RUNPATH");
1385 if (loader
->l_runpath_dirs
!= NULL
)
1386 fd
= open_path (name
, namelen
, preloaded
, loader
->l_runpath_dirs
,
1392 /* Check the list of libraries in the file /etc/ld.so.cache,
1393 for compatibility with Linux's ldconfig program. */
1394 extern const char *_dl_load_cache_lookup (const char *name
);
1395 const char *cached
= _dl_load_cache_lookup (name
);
1398 fd
= __open (cached
, O_RDONLY
);
1401 realname
= local_strdup (cached
);
1402 if (realname
== NULL
)
1411 /* Finally, try the default path. */
1413 fd
= open_path (name
, namelen
, preloaded
, rtld_search_dirs
, &realname
);
1415 /* Add another newline when we a tracing the library loading. */
1417 _dl_debug_message (1, "\n", NULL
);
1421 /* The path may contain dynamic string tokens. */
1423 ? expand_dynamic_string_token (loader
, name
)
1424 : local_strdup (name
));
1425 if (realname
== NULL
)
1429 fd
= __open (realname
, O_RDONLY
);
1439 /* We haven't found an appropriate library. But since we
1440 are only interested in the list of libraries this isn't
1441 so severe. Fake an entry with all the information we
1443 static const Elf_Symndx dummy_bucket
= STN_UNDEF
;
1445 /* Enter the new object in the list of loaded objects. */
1446 if ((name_copy
= local_strdup (name
)) == NULL
1447 || (l
= _dl_new_object (name_copy
, name
, type
, loader
)) == NULL
)
1448 _dl_signal_error (ENOMEM
, name
,
1449 "cannot create shared object descriptor");
1450 /* We use an opencount of 0 as a sign for the faked entry.
1451 Since the descriptor is initialized with zero we do not
1454 l->l_reserved = 0; */
1455 l
->l_buckets
= &dummy_bucket
;
1462 _dl_signal_error (errno
, name
, "cannot open shared object file");
1465 return _dl_map_object_from_fd (name
, fd
, realname
, loader
, type
);