Update.
[glibc.git] / elf / dl-load.c
blobcc3ac6e15eff3c9ae7abc09a09048f1c2fdeeb6a
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. */
20 #include <elf.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <elf/ldsodefs.h>
27 #include <sys/mman.h>
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include "dynamic-link.h"
32 #include <stdio-common/_itoa.h>
34 #include <dl-origin.h>
37 /* On some systems, no flag bits are given to specify file mapping. */
38 #ifndef MAP_FILE
39 #define MAP_FILE 0
40 #endif
42 /* The right way to map in the shared library files is MAP_COPY, which
43 makes a virtual copy of the data at the time of the mmap call; this
44 guarantees the mapped pages will be consistent even if the file is
45 overwritten. Some losing VM systems like Linux's lack MAP_COPY. All we
46 get is MAP_PRIVATE, which copies each page when it is modified; this
47 means if the file is overwritten, we may at some point get some pages
48 from the new version after starting with pages from the old version. */
49 #ifndef MAP_COPY
50 #define MAP_COPY MAP_PRIVATE
51 #endif
53 /* Some systems link their relocatable objects for another base address
54 than 0. We want to know the base address for these such that we can
55 subtract this address from the segment addresses during mapping.
56 This results in a more efficient address space usage. Defaults to
57 zero for almost all systems. */
58 #ifndef MAP_BASE_ADDR
59 #define MAP_BASE_ADDR(l) 0
60 #endif
63 #include <endian.h>
64 #if BYTE_ORDER == BIG_ENDIAN
65 #define byteorder ELFDATA2MSB
66 #define byteorder_name "big-endian"
67 #elif BYTE_ORDER == LITTLE_ENDIAN
68 #define byteorder ELFDATA2LSB
69 #define byteorder_name "little-endian"
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 size_t _dl_pagesize;
99 extern const char *_dl_platform;
100 extern size_t _dl_platformlen;
102 /* This is the decomposed LD_LIBRARY_PATH search path. */
103 static struct r_search_path_elem **env_path_list;
105 /* List of the hardware capabilities we might end up using. */
106 static const struct r_strlenpair *capstr;
107 static size_t ncapstr;
108 static size_t max_capstrlen;
111 /* This function has no public prototype. */
112 extern ssize_t __libc_read (int, void *, size_t);
115 /* Local version of `strdup' function. */
116 static inline char *
117 local_strdup (const char *s)
119 size_t len = strlen (s) + 1;
120 void *new = malloc (len);
122 if (new == NULL)
123 return NULL;
125 return (char *) memcpy (new, s, len);
128 /* Return copy of argument with all recognized dynamic string tokens
129 ($ORIGIN and $PLATFORM for now) replaced. On some platforms it
130 might not be possible to determine the path from which the object
131 belonging to the map is loaded. In this case the path element
132 containing $ORIGIN is left out. */
133 static char *
134 expand_dynamic_string_token (struct link_map *l, const char *s)
136 /* We make two runs over the string. First we determine how large the
137 resulting string is and then we copy it over. Since this is now
138 frequently executed operation we are looking here not for performance
139 but rather for code size. */
140 const char *st, *sf;
141 size_t cnt = 0;
142 size_t origin_len;
143 size_t total;
144 char *result, *last_elem, *wp;
146 st = s;
147 sf = strchr (s, '$');
148 while (sf != NULL)
150 size_t len = 1;
152 if (((strncmp (&sf[1], "ORIGIN", 6) == 0 && (len = 7) != 0)
153 || (strncmp (&sf[1], "PLATFORM", 8) == 0 && (len = 9) != 0))
154 && (s[len] == '\0' || s[len] == '/' || s[len] == ':'))
155 ++cnt;
157 st = sf + len;
158 sf = strchr (st, '$');
161 /* If we do not have to replace anything simply copy the string. */
162 if (cnt == 0)
163 return local_strdup (s);
165 /* Now we make a guess how many extra characters on top of the length
166 of S we need to represent the result. We know that we have CNT
167 replacements. Each at most can use
168 MAX (strlen (ORIGIN), strlen (_dl_platform))
169 minus 7 (which is the length of "$ORIGIN").
171 First get the origin string if it is not available yet. This can
172 only happen for the map of the executable. */
173 if (l->l_origin == NULL)
175 assert (l->l_name[0] == '\0');
176 l->l_origin = get_origin ();
177 origin_len = (l->l_origin && l->l_origin != (char *) -1
178 ? strlen (l->l_origin) : 0);
180 else
181 origin_len = l->l_origin == (char *) -1 ? 0 : strlen (l->l_origin);
183 total = strlen (s) + cnt * (MAX (origin_len, _dl_platformlen) - 7);
184 result = (char *) malloc (total + 1);
185 if (result == NULL)
186 return NULL;
188 /* Now fill the result path. While copying over the string we keep
189 track of the start of the last path element. When we come accross
190 a DST we copy over the value or (if the value is not available)
191 leave the entire path element out. */
192 last_elem = wp = result;
195 if (*s == '$')
197 const char *repl;
198 size_t len;
200 if (((strncmp (&s[1], "ORIGIN", 6) == 0 && (len = 7) != 0)
201 || (strncmp (&s[1], "PLATFORM", 8) == 0 && (len = 9) != 0))
202 && (s[len] == '\0' || s[len] == '/' || s[len] == ':'))
204 if ((repl = len == 7 ? l->l_origin : _dl_platform) != NULL
205 && repl != (const char *) -1)
207 wp = __stpcpy (wp, repl);
208 s += len;
210 else
212 /* We cannot use this path element, the value of the
213 replacement is unknown. */
214 wp = last_elem;
215 s += len;
216 while (*s != '\0' && *s != ':')
217 ++s;
220 else
221 /* No SDK we recognize. */
222 *wp++ = *s++;
224 else if (*s == ':')
226 *wp++ = *s++;
227 last_elem = wp;
229 else
230 *wp++ = *s++;
232 while (*s != '\0');
234 *wp = '\0';
236 return result;
239 /* Add `name' to the list of names for a particular shared object.
240 `name' is expected to have been allocated with malloc and will
241 be freed if the shared object already has this name.
242 Returns false if the object already had this name. */
243 static void
244 internal_function
245 add_name_to_object (struct link_map *l, const char *name)
247 struct libname_list *lnp, *lastp;
248 struct libname_list *newname;
249 size_t name_len;
251 lastp = NULL;
252 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
253 if (strcmp (name, lnp->name) == 0)
254 return;
256 name_len = strlen (name) + 1;
257 newname = malloc (sizeof *newname + name_len);
258 if (newname == NULL)
260 /* No more memory. */
261 _dl_signal_error (ENOMEM, name, "cannot allocate name record");
262 return;
264 /* The object should have a libname set from _dl_new_object. */
265 assert (lastp != NULL);
267 newname->name = memcpy (newname + 1, name, name_len);
268 newname->next = NULL;
269 lastp->next = newname;
272 /* All known directories in sorted order. */
273 static struct r_search_path_elem *all_dirs;
275 /* Standard search directories. */
276 static struct r_search_path_elem **rtld_search_dirs;
278 static size_t max_dirnamelen;
280 static inline struct r_search_path_elem **
281 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
282 const char **trusted, const char *what, const char *where)
284 char *cp;
285 size_t nelems = 0;
287 while ((cp = __strsep (&rpath, sep)) != NULL)
289 struct r_search_path_elem *dirp;
290 size_t len = strlen (cp);
292 /* `strsep' can pass an empty string. This has to be
293 interpreted as `use the current directory'. */
294 if (len == 0)
296 static char curwd[] = "./";
297 cp = curwd;
300 /* Remove trailing slashes (except for "/"). */
301 while (len > 1 && cp[len - 1] == '/')
302 --len;
304 /* Make sure we don't use untrusted directories if we run SUID. */
305 if (trusted != NULL)
307 const char **trun = trusted;
309 /* All trusted directories must be complete names. */
310 if (cp[0] != '/')
311 continue;
313 while (*trun != NULL
314 && (memcmp (*trun, cp, len) != 0
315 || (*trun)[len] != '/'
316 || (*trun)[len + 1] != '\0'))
317 ++trun;
319 if (*trun == NULL)
320 /* It's no trusted directory, skip it. */
321 continue;
324 /* Now add one if there is none so far. */
325 if (len > 0 && cp[len - 1] != '/')
326 cp[len++] = '/';
328 /* See if this directory is already known. */
329 for (dirp = all_dirs; dirp != NULL; dirp = dirp->next)
330 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
331 break;
333 if (dirp != NULL)
335 /* It is available, see whether it's on our own list. */
336 size_t cnt;
337 for (cnt = 0; cnt < nelems; ++cnt)
338 if (result[cnt] == dirp)
339 break;
341 if (cnt == nelems)
342 result[nelems++] = dirp;
344 else
346 size_t cnt;
348 /* It's a new directory. Create an entry and add it. */
349 dirp = (struct r_search_path_elem *)
350 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status));
351 if (dirp == NULL)
352 _dl_signal_error (ENOMEM, NULL,
353 "cannot create cache for search path");
355 dirp->dirname = cp;
356 dirp->dirnamelen = len;
358 if (len > max_dirnamelen)
359 max_dirnamelen = len;
361 /* We have to make sure all the relative directories are never
362 ignored. The current directory might change and all our
363 saved information would be void. */
364 if (cp[0] != '/')
365 for (cnt = 0; cnt < ncapstr; ++cnt)
366 dirp->status[cnt] = existing;
367 else
368 for (cnt = 0; cnt < ncapstr; ++cnt)
369 dirp->status[cnt] = unknown;
371 dirp->what = what;
372 dirp->where = where;
374 dirp->next = all_dirs;
375 all_dirs = dirp;
377 /* Put it in the result array. */
378 result[nelems++] = dirp;
382 /* Terminate the array. */
383 result[nelems] = NULL;
385 return result;
389 static struct r_search_path_elem **
390 internal_function
391 decompose_rpath (const char *rpath, struct link_map *l)
393 /* Make a copy we can work with. */
394 const char *where = l->l_name;
395 char *copy;
396 char *cp;
397 struct r_search_path_elem **result;
398 size_t nelems;
400 /* First see whether we must forget the RPATH from this object. */
401 if (_dl_inhibit_rpath != NULL && !__libc_enable_secure)
403 const char *found = strstr (_dl_inhibit_rpath, where);
404 if (found != NULL)
406 size_t len = strlen (where);
407 if ((found == _dl_inhibit_rpath || found[-1] == ':')
408 && (found[len] == '\0' || found[len] == ':'))
410 /* This object is on the list of objects for which the RPATH
411 must not be used. */
412 result = (struct r_search_path_elem **)
413 malloc (sizeof (*result));
414 if (result == NULL)
415 _dl_signal_error (ENOMEM, NULL,
416 "cannot create cache for search path");
417 result[0] = NULL;
419 return result;
424 /* Make a writable copy. At the same time expand possible dynamic
425 string tokens. */
426 copy = expand_dynamic_string_token (l, rpath);
427 if (copy == NULL)
428 _dl_signal_error (ENOMEM, NULL, "cannot create RPATH copy");
430 /* Count the number of necessary elements in the result array. */
431 nelems = 0;
432 for (cp = copy; *cp != '\0'; ++cp)
433 if (*cp == ':')
434 ++nelems;
436 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
437 number of necessary entries. */
438 result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
439 * sizeof (*result));
440 if (result == NULL)
441 _dl_signal_error (ENOMEM, NULL, "cannot create cache for search path");
443 return fillin_rpath (copy, result, ":", NULL, "RPATH", where);
447 void
448 internal_function
449 _dl_init_paths (const char *llp)
451 static const char *system_dirs[] =
453 #include "trusted-dirs.h"
454 NULL
456 const char **strp;
457 struct r_search_path_elem *pelem, **aelem;
458 size_t round_size;
459 #ifdef PIC
460 struct link_map *l;
461 #endif
463 /* Fill in the information about the application's RPATH and the
464 directories addressed by the LD_LIBRARY_PATH environment variable. */
466 /* Get the capabilities. */
467 capstr = _dl_important_hwcaps (_dl_platform, _dl_platformlen,
468 &ncapstr, &max_capstrlen);
470 /* First set up the rest of the default search directory entries. */
471 aelem = rtld_search_dirs = (struct r_search_path_elem **)
472 malloc ((ncapstr + 1) * sizeof (struct r_search_path_elem *));
473 if (rtld_search_dirs == NULL)
474 _dl_signal_error (ENOMEM, NULL, "cannot create search path array");
476 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
477 + ncapstr * sizeof (enum r_dir_status))
478 / sizeof (struct r_search_path_elem));
480 rtld_search_dirs[0] = (struct r_search_path_elem *)
481 malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]) - 1)
482 * round_size * sizeof (struct r_search_path_elem));
483 if (rtld_search_dirs[0] == NULL)
484 _dl_signal_error (ENOMEM, NULL, "cannot create cache for search path");
486 pelem = all_dirs = rtld_search_dirs[0];
487 for (strp = system_dirs; *strp != NULL; ++strp, pelem += round_size)
489 size_t cnt;
491 *aelem++ = pelem;
493 pelem->next = *(strp + 1) == NULL ? NULL : (pelem + round_size);
495 pelem->what = "system search path";
496 pelem->where = NULL;
498 pelem->dirnamelen = strlen (pelem->dirname = *strp);
499 if (pelem->dirnamelen > max_dirnamelen)
500 max_dirnamelen = pelem->dirnamelen;
502 if (pelem->dirname[0] != '/')
503 for (cnt = 0; cnt < ncapstr; ++cnt)
504 pelem->status[cnt] = existing;
505 else
506 for (cnt = 0; cnt < ncapstr; ++cnt)
507 pelem->status[cnt] = unknown;
509 *aelem = NULL;
511 #ifdef PIC
512 /* This points to the map of the main object. */
513 l = _dl_loaded;
514 if (l != NULL)
516 assert (l->l_type != lt_loaded);
518 if (l->l_info[DT_RPATH])
519 /* Allocate room for the search path and fill in information
520 from RPATH. */
521 l->l_rpath_dirs =
522 decompose_rpath ((const char *)
523 (l->l_addr + l->l_info[DT_STRTAB]->d_un.d_ptr
524 + l->l_info[DT_RPATH]->d_un.d_val), l);
525 else
526 l->l_rpath_dirs = NULL;
528 #endif /* PIC */
530 if (llp != NULL && *llp != '\0')
532 size_t nllp;
533 const char *cp = llp;
535 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
536 elements it has. */
537 nllp = 1;
538 while (*cp)
540 if (*cp == ':' || *cp == ';')
541 ++nllp;
542 ++cp;
545 env_path_list = (struct r_search_path_elem **)
546 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
547 if (env_path_list == NULL)
548 _dl_signal_error (ENOMEM, NULL,
549 "cannot create cache for search path");
551 (void) fillin_rpath (local_strdup (llp), env_path_list, ":;",
552 __libc_enable_secure ? system_dirs : NULL,
553 "LD_LIBRARY_PATH", NULL);
558 /* Map in the shared object NAME, actually located in REALNAME, and already
559 opened on FD. */
561 #ifndef EXTERNAL_MAP_FROM_FD
562 static
563 #endif
564 struct link_map *
565 _dl_map_object_from_fd (const char *name, int fd, char *realname,
566 struct link_map *loader, int l_type)
568 struct link_map *l = NULL;
570 #define LOSE(s) lose (0, (s))
571 void lose (int code, const char *msg)
573 (void) __close (fd);
574 if (l)
576 /* Remove the stillborn object from the list and free it. */
577 if (l->l_prev)
578 l->l_prev->l_next = l->l_next;
579 if (l->l_next)
580 l->l_next->l_prev = l->l_prev;
581 free (l);
583 free (realname);
584 _dl_signal_error (code, name, msg);
587 inline caddr_t map_segment (ElfW(Addr) mapstart, size_t len,
588 int prot, int fixed, off_t offset)
590 caddr_t mapat = __mmap ((caddr_t) mapstart, len, prot,
591 fixed|MAP_COPY|MAP_FILE,
592 fd, offset);
593 if (mapat == MAP_FAILED)
594 lose (errno, "failed to map segment from shared object");
595 return mapat;
598 const ElfW(Ehdr) *header;
599 const ElfW(Phdr) *phdr;
600 const ElfW(Phdr) *ph;
601 size_t maplength;
602 int type;
603 char *readbuf;
604 ssize_t readlength;
606 /* Look again to see if the real name matched another already loaded. */
607 for (l = _dl_loaded; l; l = l->l_next)
608 if (! strcmp (realname, l->l_name))
610 /* The object is already loaded.
611 Just bump its reference count and return it. */
612 __close (fd);
614 /* If the name is not in the list of names for this object add
615 it. */
616 free (realname);
617 add_name_to_object (l, name);
618 ++l->l_opencount;
619 return l;
622 /* Print debugging message. */
623 if (_dl_debug_files)
624 _dl_debug_message (1, "file=", name, "; generating link map\n", NULL);
626 /* Read the header directly. */
627 readbuf = alloca (_dl_pagesize);
628 readlength = __libc_read (fd, readbuf, _dl_pagesize);
629 if (readlength < (ssize_t) sizeof(*header))
630 lose (errno, "cannot read file data");
631 header = (void *) readbuf;
633 /* Check the header for basic validity. */
634 if (*(Elf32_Word *) &header->e_ident !=
635 #if BYTE_ORDER == LITTLE_ENDIAN
636 ((ELFMAG0 << (EI_MAG0 * 8)) |
637 (ELFMAG1 << (EI_MAG1 * 8)) |
638 (ELFMAG2 << (EI_MAG2 * 8)) |
639 (ELFMAG3 << (EI_MAG3 * 8)))
640 #else
641 ((ELFMAG0 << (EI_MAG3 * 8)) |
642 (ELFMAG1 << (EI_MAG2 * 8)) |
643 (ELFMAG2 << (EI_MAG1 * 8)) |
644 (ELFMAG3 << (EI_MAG0 * 8)))
645 #endif
647 LOSE ("invalid ELF header");
648 #define ELF32_CLASS ELFCLASS32
649 #define ELF64_CLASS ELFCLASS64
650 if (header->e_ident[EI_CLASS] != ELFW(CLASS))
651 LOSE ("ELF file class not " STRING(__ELF_NATIVE_CLASS) "-bit");
652 if (header->e_ident[EI_DATA] != byteorder)
653 LOSE ("ELF file data encoding not " byteorder_name);
654 if (header->e_ident[EI_VERSION] != EV_CURRENT)
655 LOSE ("ELF file version ident not " STRING(EV_CURRENT));
656 /* XXX We should be able so set system specific versions which are
657 allowed here. */
658 if (header->e_ident[EI_OSABI] != ELFOSABI_SYSV)
659 LOSE ("ELF file OS ABI not " STRING(ELFOSABI_SYSV));
660 if (header->e_ident[EI_ABIVERSION] != 0)
661 LOSE ("ELF file ABI version not 0");
662 if (header->e_version != EV_CURRENT)
663 LOSE ("ELF file version not " STRING(EV_CURRENT));
664 if (! elf_machine_matches_host (header->e_machine))
665 LOSE ("ELF file machine architecture not " ELF_MACHINE_NAME);
666 if (header->e_phentsize != sizeof (ElfW(Phdr)))
667 LOSE ("ELF file's phentsize not the expected size");
669 #ifndef MAP_ANON
670 #define MAP_ANON 0
671 if (_dl_zerofd == -1)
673 _dl_zerofd = _dl_sysdep_open_zero_fill ();
674 if (_dl_zerofd == -1)
676 __close (fd);
677 _dl_signal_error (errno, NULL, "cannot open zero fill device");
680 #endif
682 /* Enter the new object in the list of loaded objects. */
683 l = _dl_new_object (realname, name, l_type, loader);
684 if (! l)
685 lose (ENOMEM, "cannot create shared object descriptor");
686 l->l_opencount = 1;
688 /* Extract the remaining details we need from the ELF header
689 and then read in the program header table. */
690 l->l_entry = header->e_entry;
691 type = header->e_type;
692 l->l_phnum = header->e_phnum;
694 maplength = header->e_phnum * sizeof (ElfW(Phdr));
695 if (header->e_phoff + maplength <= readlength)
696 phdr = (void *) (readbuf + header->e_phoff);
697 else
699 phdr = alloca (maplength);
700 __lseek (fd, SEEK_SET, header->e_phoff);
701 if (__libc_read (fd, (void *) phdr, maplength) != maplength)
702 lose (errno, "cannot read file data");
706 /* Scan the program header table, collecting its load commands. */
707 struct loadcmd
709 ElfW(Addr) mapstart, mapend, dataend, allocend;
710 off_t mapoff;
711 int prot;
712 } loadcmds[l->l_phnum], *c;
713 size_t nloadcmds = 0;
715 l->l_ld = 0;
716 l->l_phdr = 0;
717 l->l_addr = 0;
718 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
719 switch (ph->p_type)
721 /* These entries tell us where to find things once the file's
722 segments are mapped in. We record the addresses it says
723 verbatim, and later correct for the run-time load address. */
724 case PT_DYNAMIC:
725 l->l_ld = (void *) ph->p_vaddr;
726 break;
727 case PT_PHDR:
728 l->l_phdr = (void *) ph->p_vaddr;
729 break;
731 case PT_LOAD:
732 /* A load command tells us to map in part of the file.
733 We record the load commands and process them all later. */
734 if (ph->p_align % _dl_pagesize != 0)
735 LOSE ("ELF load command alignment not page-aligned");
736 if ((ph->p_vaddr - ph->p_offset) % ph->p_align)
737 LOSE ("ELF load command address/offset not properly aligned");
739 struct loadcmd *c = &loadcmds[nloadcmds++];
740 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
741 c->mapend = ((ph->p_vaddr + ph->p_filesz + _dl_pagesize - 1)
742 & ~(_dl_pagesize - 1));
743 c->dataend = ph->p_vaddr + ph->p_filesz;
744 c->allocend = ph->p_vaddr + ph->p_memsz;
745 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
746 c->prot = 0;
747 if (ph->p_flags & PF_R)
748 c->prot |= PROT_READ;
749 if (ph->p_flags & PF_W)
750 c->prot |= PROT_WRITE;
751 if (ph->p_flags & PF_X)
752 c->prot |= PROT_EXEC;
753 break;
757 /* Now process the load commands and map segments into memory. */
758 c = loadcmds;
760 /* Length of the sections to be loaded. */
761 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
763 if (type == ET_DYN || type == ET_REL)
765 /* This is a position-independent shared object. We can let the
766 kernel map it anywhere it likes, but we must have space for all
767 the segments in their specified positions relative to the first.
768 So we map the first segment without MAP_FIXED, but with its
769 extent increased to cover all the segments. Then we remove
770 access from excess portion, and there is known sufficient space
771 there to remap from the later segments.
773 As a refinement, sometimes we have an address that we would
774 prefer to map such objects at; but this is only a preference,
775 the OS can do whatever it likes. */
776 caddr_t mapat;
777 ElfW(Addr) mappref;
778 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
779 - MAP_BASE_ADDR (l));
780 mapat = map_segment (mappref, maplength, c->prot, 0, c->mapoff);
781 l->l_addr = (ElfW(Addr)) mapat - c->mapstart;
783 /* Change protection on the excess portion to disallow all access;
784 the portions we do not remap later will be inaccessible as if
785 unallocated. Then jump into the normal segment-mapping loop to
786 handle the portion of the segment past the end of the file
787 mapping. */
788 __mprotect ((caddr_t) (l->l_addr + c->mapend),
789 loadcmds[nloadcmds - 1].allocend - c->mapend,
792 /* Remember which part of the address space this object uses. */
793 l->l_map_start = c->mapstart + l->l_addr;
794 l->l_map_end = l->l_map_start + maplength;
796 goto postmap;
798 else
800 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
801 fixed. */
802 ELF_FIXED_ADDRESS (loader, c->mapstart);
805 /* Remember which part of the address space this object uses. */
806 l->l_map_start = c->mapstart + l->l_addr;
807 l->l_map_end = l->l_map_start + maplength;
809 while (c < &loadcmds[nloadcmds])
811 if (c->mapend > c->mapstart)
812 /* Map the segment contents from the file. */
813 map_segment (l->l_addr + c->mapstart, c->mapend - c->mapstart,
814 c->prot, MAP_FIXED, c->mapoff);
816 postmap:
817 if (c->allocend > c->dataend)
819 /* Extra zero pages should appear at the end of this segment,
820 after the data mapped from the file. */
821 ElfW(Addr) zero, zeroend, zeropage;
823 zero = l->l_addr + c->dataend;
824 zeroend = l->l_addr + c->allocend;
825 zeropage = (zero + _dl_pagesize - 1) & ~(_dl_pagesize - 1);
827 if (zeroend < zeropage)
828 /* All the extra data is in the last page of the segment.
829 We can just zero it. */
830 zeropage = zeroend;
832 if (zeropage > zero)
834 /* Zero the final part of the last page of the segment. */
835 if ((c->prot & PROT_WRITE) == 0)
837 /* Dag nab it. */
838 if (__mprotect ((caddr_t) (zero & ~(_dl_pagesize - 1)),
839 _dl_pagesize, c->prot|PROT_WRITE) < 0)
840 lose (errno, "cannot change memory protections");
842 memset ((void *) zero, 0, zeropage - zero);
843 if ((c->prot & PROT_WRITE) == 0)
844 __mprotect ((caddr_t) (zero & ~(_dl_pagesize - 1)),
845 _dl_pagesize, c->prot);
848 if (zeroend > zeropage)
850 /* Map the remaining zero pages in from the zero fill FD. */
851 caddr_t mapat;
852 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
853 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
854 ANONFD, 0);
855 if (mapat == MAP_FAILED)
856 lose (errno, "cannot map zero-fill pages");
860 ++c;
863 if (l->l_phdr == 0)
865 /* There was no PT_PHDR specified. We need to find the phdr in the
866 load image ourselves. We assume it is in fact in the load image
867 somewhere, and that the first load command starts at the
868 beginning of the file and thus contains the ELF file header. */
869 ElfW(Addr) bof = l->l_addr + loadcmds[0].mapstart;
870 assert (loadcmds[0].mapoff == 0);
871 l->l_phdr = (void *) (bof + ((const ElfW(Ehdr) *) bof)->e_phoff);
873 else
874 /* Adjust the PT_PHDR value by the runtime load address. */
875 (ElfW(Addr)) l->l_phdr += l->l_addr;
878 /* We are done mapping in the file. We no longer need the descriptor. */
879 __close (fd);
881 if (l->l_type == lt_library && type == ET_EXEC)
882 l->l_type = lt_executable;
884 if (l->l_ld == 0)
886 if (type == ET_DYN)
887 LOSE ("object file has no dynamic section");
889 else
890 (ElfW(Addr)) l->l_ld += l->l_addr;
892 l->l_entry += l->l_addr;
894 if (_dl_debug_files)
896 const size_t nibbles = sizeof (void *) * 2;
897 char buf1[nibbles + 1];
898 char buf2[nibbles + 1];
899 char buf3[nibbles + 1];
901 buf1[nibbles] = '\0';
902 buf2[nibbles] = '\0';
903 buf3[nibbles] = '\0';
905 memset (buf1, '0', nibbles);
906 memset (buf2, '0', nibbles);
907 memset (buf3, '0', nibbles);
908 _itoa_word ((unsigned long int) l->l_ld, &buf1[nibbles], 16, 0);
909 _itoa_word ((unsigned long int) l->l_addr, &buf2[nibbles], 16, 0);
910 _itoa_word (maplength, &buf3[nibbles], 16, 0);
912 _dl_debug_message (1, " dynamic: 0x", buf1, " base: 0x", buf2,
913 " size: 0x", buf3, "\n", NULL);
914 memset (buf1, '0', nibbles);
915 memset (buf2, '0', nibbles);
916 memset (buf3, ' ', nibbles);
917 _itoa_word ((unsigned long int) l->l_entry, &buf1[nibbles], 16, 0);
918 _itoa_word ((unsigned long int) l->l_phdr, &buf2[nibbles], 16, 0);
919 _itoa_word (l->l_phnum, &buf3[nibbles], 10, 0);
920 _dl_debug_message (1, " entry: 0x", buf1, " phdr: 0x", buf2,
921 " phnum: ", buf3, "\n\n", NULL);
924 elf_get_dynamic_info (l->l_ld, l->l_info);
925 if (l->l_info[DT_HASH])
926 _dl_setup_hash (l);
928 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
929 have to do this for the main map. */
930 if (l->l_info[DT_SYMBOLIC] && &l->l_searchlist != l->l_scope[0])
932 /* Create an appropriate searchlist. It contains only this map.
934 XXX This is the definition of DT_SYMBOLIC in SysVr4. The old
935 GNU ld.so implementation had a different interpretation which
936 is more reasonable. We are prepared to add this possibility
937 back as part of a GNU extension of the ELF format. */
938 l->l_symbolic_searchlist.r_list =
939 (struct link_map **) malloc (sizeof (struct link_map *));
941 if (l->l_symbolic_searchlist.r_list == NULL)
942 lose (ENOMEM, "cannot create searchlist");
944 l->l_symbolic_searchlist.r_list[0] = l;
945 l->l_symbolic_searchlist.r_nlist = 1;
946 l->l_symbolic_searchlist.r_duplist = l->l_symbolic_searchlist.r_list;
947 l->l_symbolic_searchlist.r_nduplist = 1;
949 /* Now move the existing entries one back. */
950 memmove (&l->l_scope[1], &l->l_scope[0],
951 3 * sizeof (struct r_scope_elem *));
953 /* Now add the new entry. */
954 l->l_scope[0] = &l->l_symbolic_searchlist;
957 return l;
960 /* Print search path. */
961 static void
962 print_search_path (struct r_search_path_elem **list,
963 const char *what, const char *name)
965 char buf[max_dirnamelen + max_capstrlen];
966 int first = 1;
968 _dl_debug_message (1, " search path=", NULL);
970 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
972 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
973 size_t cnt;
975 for (cnt = 0; cnt < ncapstr; ++cnt)
976 if ((*list)->status[cnt] != nonexisting)
978 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
979 if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
980 cp[0] = '\0';
981 else
982 cp[-1] = '\0';
983 _dl_debug_message (0, first ? "" : ":", buf, NULL);
984 first = 0;
987 ++list;
990 if (name != NULL)
991 _dl_debug_message (0, "\t\t(", what, " from file ",
992 name[0] ? name : _dl_argv[0], ")\n", NULL);
993 else
994 _dl_debug_message (0, "\t\t(", what, ")\n", NULL);
997 /* Try to open NAME in one of the directories in DIRS.
998 Return the fd, or -1. If successful, fill in *REALNAME
999 with the malloc'd full directory name. */
1001 static int
1002 open_path (const char *name, size_t namelen, int preloaded,
1003 struct r_search_path_elem **dirs,
1004 char **realname)
1006 char *buf;
1007 int fd = -1;
1008 const char *current_what = NULL;
1010 if (dirs == NULL || *dirs == NULL)
1012 __set_errno (ENOENT);
1013 return -1;
1016 buf = __alloca (max_dirnamelen + max_capstrlen + namelen);
1019 struct r_search_path_elem *this_dir = *dirs;
1020 size_t buflen = 0;
1021 size_t cnt;
1022 char *edp;
1024 /* If we are debugging the search for libraries print the path
1025 now if it hasn't happened now. */
1026 if (_dl_debug_libs && current_what != this_dir->what)
1028 current_what = this_dir->what;
1029 print_search_path (dirs, current_what, this_dir->where);
1032 edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1033 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1035 /* Skip this directory if we know it does not exist. */
1036 if (this_dir->status[cnt] == nonexisting)
1037 continue;
1039 buflen =
1040 ((char *) __mempcpy (__mempcpy (edp,
1041 capstr[cnt].str, capstr[cnt].len),
1042 name, namelen)
1043 - buf);
1045 /* Print name we try if this is wanted. */
1046 if (_dl_debug_libs)
1047 _dl_debug_message (1, " trying file=", buf, "\n", NULL);
1049 fd = __open (buf, O_RDONLY);
1050 if (this_dir->status[cnt] == unknown)
1052 if (fd != -1)
1053 this_dir->status[cnt] = existing;
1054 else
1056 /* We failed to open machine dependent library. Let's
1057 test whether there is any directory at all. */
1058 struct stat st;
1060 buf[buflen - namelen - 1] = '\0';
1062 if (__xstat (_STAT_VER, buf, &st) != 0
1063 || ! S_ISDIR (st.st_mode))
1064 /* The directory does not exist or it is no directory. */
1065 this_dir->status[cnt] = nonexisting;
1066 else
1067 this_dir->status[cnt] = existing;
1071 if (fd != -1 && preloaded && __libc_enable_secure)
1073 /* This is an extra security effort to make sure nobody can
1074 preload broken shared objects which are in the trusted
1075 directories and so exploit the bugs. */
1076 struct stat st;
1078 if (__fxstat (_STAT_VER, fd, &st) != 0
1079 || (st.st_mode & S_ISUID) == 0)
1081 /* The shared object cannot be tested for being SUID
1082 or this bit is not set. In this case we must not
1083 use this object. */
1084 __close (fd);
1085 fd = -1;
1086 /* We simply ignore the file, signal this by setting
1087 the error value which would have been set by `open'. */
1088 errno = ENOENT;
1093 if (fd != -1)
1095 *realname = malloc (buflen);
1096 if (*realname != NULL)
1098 memcpy (*realname, buf, buflen);
1099 return fd;
1101 else
1103 /* No memory for the name, we certainly won't be able
1104 to load and link it. */
1105 __close (fd);
1106 return -1;
1109 if (errno != ENOENT && errno != EACCES)
1110 /* The file exists and is readable, but something went wrong. */
1111 return -1;
1113 while (*++dirs != NULL);
1115 return -1;
1118 /* Map in the shared object file NAME. */
1120 struct link_map *
1121 internal_function
1122 _dl_map_object (struct link_map *loader, const char *name, int preloaded,
1123 int type, int trace_mode)
1125 int fd;
1126 char *realname;
1127 char *name_copy;
1128 struct link_map *l;
1130 /* Look for this name among those already loaded. */
1131 for (l = _dl_loaded; l; l = l->l_next)
1133 /* If the requested name matches the soname of a loaded object,
1134 use that object. Elide this check for names that have not
1135 yet been opened. */
1136 if (l->l_opencount <= 0)
1137 continue;
1138 if (!_dl_name_match_p (name, l))
1140 const char *soname;
1142 if (l->l_info[DT_SONAME] == NULL)
1143 continue;
1145 soname = (const char *) (l->l_addr
1146 + l->l_info[DT_STRTAB]->d_un.d_ptr
1147 + l->l_info[DT_SONAME]->d_un.d_val);
1148 if (strcmp (name, soname) != 0)
1149 continue;
1151 /* We have a match on a new name -- cache it. */
1152 add_name_to_object (l, soname);
1155 /* We have a match -- bump the reference count and return it. */
1156 ++l->l_opencount;
1157 return l;
1160 /* Display information if we are debugging. */
1161 if (_dl_debug_files && loader != NULL)
1162 _dl_debug_message (1, "\nfile=", name, "; needed by ",
1163 loader->l_name[0] ? loader->l_name : _dl_argv[0],
1164 "\n", NULL);
1166 if (strchr (name, '/') == NULL)
1168 /* Search for NAME in several places. */
1170 size_t namelen = strlen (name) + 1;
1172 if (_dl_debug_libs)
1173 _dl_debug_message (1, "find library=", name, "; searching\n", NULL);
1175 fd = -1;
1177 /* First try the DT_RPATH of the dependent object that caused NAME
1178 to be loaded. Then that object's dependent, and on up. */
1179 for (l = loader; fd == -1 && l; l = l->l_loader)
1180 if (l && l->l_info[DT_RPATH])
1182 /* Make sure the cache information is available. */
1183 if (l->l_rpath_dirs == NULL)
1185 size_t ptrval = (l->l_addr
1186 + l->l_info[DT_STRTAB]->d_un.d_ptr
1187 + l->l_info[DT_RPATH]->d_un.d_val);
1188 l->l_rpath_dirs =
1189 decompose_rpath ((const char *) ptrval, l);
1192 if (l->l_rpath_dirs != NULL)
1193 fd = open_path (name, namelen, preloaded, l->l_rpath_dirs,
1194 &realname);
1197 /* If dynamically linked, try the DT_RPATH of the executable itself. */
1198 l = _dl_loaded;
1199 if (fd == -1 && l && l->l_type != lt_loaded && l != loader
1200 && l->l_rpath_dirs != NULL)
1201 fd = open_path (name, namelen, preloaded, l->l_rpath_dirs, &realname);
1203 /* Try the LD_LIBRARY_PATH environment variable. */
1204 if (fd == -1 && env_path_list != NULL)
1205 fd = open_path (name, namelen, preloaded, env_path_list, &realname);
1207 if (fd == -1)
1209 /* Check the list of libraries in the file /etc/ld.so.cache,
1210 for compatibility with Linux's ldconfig program. */
1211 extern const char *_dl_load_cache_lookup (const char *name);
1212 const char *cached = _dl_load_cache_lookup (name);
1213 if (cached)
1215 fd = __open (cached, O_RDONLY);
1216 if (fd != -1)
1218 realname = local_strdup (cached);
1219 if (realname == NULL)
1221 __close (fd);
1222 fd = -1;
1228 /* Finally, try the default path. */
1229 if (fd == -1)
1230 fd = open_path (name, namelen, preloaded, rtld_search_dirs, &realname);
1232 /* Add another newline when we a tracing the library loading. */
1233 if (_dl_debug_libs)
1234 _dl_debug_message (1, "\n", NULL);
1236 else
1238 /* The path may contain dynamic string tokens. */
1239 realname = (loader
1240 ? expand_dynamic_string_token (loader, name)
1241 : local_strdup (name));
1242 if (realname == NULL)
1243 fd = -1;
1244 else
1246 fd = __open (realname, O_RDONLY);
1247 if (fd == -1)
1248 free (realname);
1252 if (fd == -1)
1254 if (trace_mode)
1256 /* We haven't found an appropriate library. But since we
1257 are only interested in the list of libraries this isn't
1258 so severe. Fake an entry with all the information we
1259 have. */
1260 static const ElfW(Symndx) dummy_bucket = STN_UNDEF;
1262 /* Enter the new object in the list of loaded objects. */
1263 if ((name_copy = local_strdup (name)) == NULL
1264 || (l = _dl_new_object (name_copy, name, type, loader)) == NULL)
1265 _dl_signal_error (ENOMEM, name,
1266 "cannot create shared object descriptor");
1267 /* We use an opencount of 0 as a sign for the faked entry. */
1268 l->l_opencount = 0;
1269 l->l_reserved = 0;
1270 l->l_buckets = &dummy_bucket;
1271 l->l_nbuckets = 1;
1272 l->l_relocated = 1;
1274 return l;
1276 else
1277 _dl_signal_error (errno, name, "cannot open shared object file");
1280 return _dl_map_object_from_fd (name, fd, realname, loader, type);