Update.
[glibc.git] / elf / dl-load.c
blobe67ade2d590f8b19b7b45976cd62698f9fe42b0f
1 /* Map in a shared object's segments from the file.
2 Copyright (C) 1995, 1996, 1997, 1998 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>
35 /* On some systems, no flag bits are given to specify file mapping. */
36 #ifndef MAP_FILE
37 #define MAP_FILE 0
38 #endif
40 /* The right way to map in the shared library files is MAP_COPY, which
41 makes a virtual copy of the data at the time of the mmap call; this
42 guarantees the mapped pages will be consistent even if the file is
43 overwritten. Some losing VM systems like Linux's lack MAP_COPY. All we
44 get is MAP_PRIVATE, which copies each page when it is modified; this
45 means if the file is overwritten, we may at some point get some pages
46 from the new version after starting with pages from the old version. */
47 #ifndef MAP_COPY
48 #define MAP_COPY MAP_PRIVATE
49 #endif
51 /* Some systems link their relocatable objects for another base address
52 than 0. We want to know the base address for these such that we can
53 subtract this address from the segment addresses during mapping.
54 This results in a more efficient address space usage. Defaults to
55 zero for almost all systems. */
56 #ifndef MAP_BASE_ADDR
57 #define MAP_BASE_ADDR(l) 0
58 #endif
61 #include <endian.h>
62 #if BYTE_ORDER == BIG_ENDIAN
63 #define byteorder ELFDATA2MSB
64 #define byteorder_name "big-endian"
65 #elif BYTE_ORDER == LITTLE_ENDIAN
66 #define byteorder ELFDATA2LSB
67 #define byteorder_name "little-endian"
68 #else
69 #error "Unknown BYTE_ORDER " BYTE_ORDER
70 #define byteorder ELFDATANONE
71 #endif
73 #define STRING(x) __STRING (x)
75 #ifdef MAP_ANON
76 /* The fd is not examined when using MAP_ANON. */
77 #define ANONFD -1
78 #else
79 int _dl_zerofd = -1;
80 #define ANONFD _dl_zerofd
81 #endif
83 /* Handle situations where we have a preferred location in memory for
84 the shared objects. */
85 #ifdef ELF_PREFERRED_ADDRESS_DATA
86 ELF_PREFERRED_ADDRESS_DATA;
87 #endif
88 #ifndef ELF_PREFERRED_ADDRESS
89 #define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
90 #endif
91 #ifndef ELF_FIXED_ADDRESS
92 #define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
93 #endif
95 size_t _dl_pagesize;
97 extern const char *_dl_platform;
98 extern size_t _dl_platformlen;
100 /* This is a fake list to store the RPATH information for static
101 binaries. */
102 static struct r_search_path_elem **fake_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;
110 /* This function has no public prototype. */
111 extern ssize_t __libc_read (int, void *, size_t);
114 /* Local version of `strdup' function. */
115 static inline char *
116 local_strdup (const char *s)
118 size_t len = strlen (s) + 1;
119 void *new = malloc (len);
121 if (new == NULL)
122 return NULL;
124 return (char *) memcpy (new, s, len);
127 /* Add `name' to the list of names for a particular shared object.
128 `name' is expected to have been allocated with malloc and will
129 be freed if the shared object already has this name.
130 Returns false if the object already had this name. */
131 static int
132 internal_function
133 add_name_to_object (struct link_map *l, char *name)
135 struct libname_list *lnp, *lastp;
136 struct libname_list *newname;
138 if (name == NULL)
140 /* No more memory. */
141 _dl_signal_error (ENOMEM, NULL, "could not allocate name string");
142 return 0;
145 lastp = NULL;
146 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
147 if (strcmp (name, lnp->name) == 0)
149 free (name);
150 return 0;
153 newname = malloc (sizeof *newname);
154 if (newname == NULL)
156 /* No more memory. */
157 _dl_signal_error (ENOMEM, name, "cannot allocate name record");
158 free (name);
159 return 0;
161 /* The object should have a libname set from _dl_new_object. */
162 assert (lastp != NULL);
164 newname->name = name;
165 newname->next = NULL;
166 lastp->next = newname;
167 return 1;
170 /* All known directories in sorted order. */
171 static struct r_search_path_elem *all_dirs;
173 /* Standard search directories. */
174 static struct r_search_path_elem **rtld_search_dirs;
176 static size_t max_dirnamelen;
178 static inline struct r_search_path_elem **
179 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
180 const char **trusted, const char *what, const char *where)
182 char *cp;
183 size_t nelems = 0;
185 while ((cp = __strsep (&rpath, sep)) != NULL)
187 struct r_search_path_elem *dirp;
188 size_t len = strlen (cp);
190 /* `strsep' can pass an empty string. This has to be
191 interpreted as `use the current directory'. */
192 if (len == 0)
194 static char curwd[2];
195 cp = strcpy (curwd, ".");
198 /* Remove trailing slashes. */
199 while (len > 1 && cp[len - 1] == '/')
200 --len;
202 /* Make sure we don't use untrusted directories if we run SUID. */
203 if (trusted != NULL)
205 const char **trun = trusted;
207 /* All trusted directory must be complete name. */
208 if (cp[0] != '/')
209 continue;
211 while (*trun != NULL
212 && (memcmp (*trun, cp, len) != 0
213 || ((*trun)[len] != '/' && (*trun)[len + 1] != '\0')))
214 ++trun;
216 if (*trun == NULL)
217 /* It's no trusted directory, skip it. */
218 continue;
221 /* Now add one. */
222 if (len > 0)
223 cp[len++] = '/';
225 /* See if this directory is already known. */
226 for (dirp = all_dirs; dirp != NULL; dirp = dirp->next)
227 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
228 break;
230 if (dirp != NULL)
232 /* It is available, see whether it's on our own list. */
233 size_t cnt;
234 for (cnt = 0; cnt < nelems; ++cnt)
235 if (result[cnt] == dirp)
236 break;
238 if (cnt == nelems)
239 result[nelems++] = dirp;
241 else
243 size_t cnt;
245 /* It's a new directory. Create an entry and add it. */
246 dirp = (struct r_search_path_elem *)
247 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status));
248 if (dirp == NULL)
249 _dl_signal_error (ENOMEM, NULL,
250 "cannot create cache for search path");
252 dirp->dirname = cp;
253 dirp->dirnamelen = len;
255 if (len > max_dirnamelen)
256 max_dirnamelen = len;
258 /* We have to make sure all the relative directories are never
259 ignored. The current directory might change and all our
260 saved information would be void. */
261 if (cp[0] != '/')
262 for (cnt = 0; cnt < ncapstr; ++cnt)
263 dirp->status[cnt] = existing;
264 else
265 for (cnt = 0; cnt < ncapstr; ++cnt)
266 dirp->status[cnt] = unknown;
268 dirp->what = what;
269 dirp->where = where;
271 dirp->next = all_dirs;
272 all_dirs = dirp;
274 /* Put it in the result array. */
275 result[nelems++] = dirp;
279 /* Terminate the array. */
280 result[nelems] = NULL;
282 return result;
286 static struct r_search_path_elem **
287 internal_function
288 decompose_rpath (const char *rpath, size_t additional_room, const char *where)
290 /* Make a copy we can work with. */
291 char *copy;
292 char *cp;
293 struct r_search_path_elem **result;
294 size_t nelems;
296 /* First see whether we must forget the RPATH from this object. */
297 if (_dl_inhibit_rpath != NULL && !__libc_enable_secure)
299 const char *found = strstr (_dl_inhibit_rpath, where);
300 if (found != NULL)
302 size_t len = strlen (where);
303 if ((found == _dl_inhibit_rpath || found[-1] == ':')
304 && (found[len] == '\0' || found[len] == ':'))
306 /* This object is on the list of objects for which the RPATH
307 must not be used. */
308 result = (struct r_search_path_elem **)
309 malloc ((additional_room + 1) * sizeof (*result));
310 if (result == NULL)
311 _dl_signal_error (ENOMEM, NULL,
312 "cannot create cache for search path");
313 result[0] = NULL;
315 return result;
320 /* Count the number of necessary elements in the result array. */
321 copy = local_strdup (rpath);
322 nelems = 0;
323 for (cp = copy; *cp != '\0'; ++cp)
324 if (*cp == ':')
325 ++nelems;
327 /* Allocate room for the result. NELEMS + 1 + ADDITIONAL_ROOM is an upper
328 limit for the number of necessary entries. */
329 result = (struct r_search_path_elem **) malloc ((nelems + 1
330 + additional_room + 1)
331 * sizeof (*result));
332 if (result == NULL)
333 _dl_signal_error (ENOMEM, NULL, "cannot create cache for search path");
335 return fillin_rpath (copy, result, ":", NULL, "RPATH", where);
339 void
340 internal_function
341 _dl_init_paths (const char *llp)
343 static const char *system_dirs[] =
345 #include "trusted-dirs.h"
346 NULL
348 const char **strp;
349 struct r_search_path_elem *pelem, **aelem;
350 size_t round_size;
352 /* We have in `search_path' the information about the RPATH of the
353 dynamic loader. Now fill in the information about the applications
354 RPATH and the directories addressed by the LD_LIBRARY_PATH environment
355 variable. */
356 struct link_map *l;
358 /* Number of elements in the library path. */
359 size_t nllp;
361 /* First determine how many elements the LD_LIBRARY_PATH contents has. */
362 if (llp != NULL && *llp != '\0')
364 /* Simply count the number of colons. */
365 const char *cp = llp;
366 nllp = 1;
367 while (*cp)
369 if (*cp == ':' || *cp == ';')
370 ++nllp;
371 ++cp;
374 else
375 nllp = 0;
377 /* Get the capabilities. */
378 capstr = _dl_important_hwcaps (_dl_platform, _dl_platformlen,
379 &ncapstr, &max_capstrlen);
381 /* First set up the rest of the default search directory entries. */
382 aelem = rtld_search_dirs = (struct r_search_path_elem **)
383 malloc ((ncapstr + 1) * sizeof (struct r_search_path_elem *));
385 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
386 + ncapstr * sizeof (enum r_dir_status))
387 / sizeof (struct r_search_path_elem));
389 rtld_search_dirs[0] = (struct r_search_path_elem *)
390 malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]) - 1)
391 * round_size * sizeof (struct r_search_path_elem));
392 if (rtld_search_dirs[0] == NULL)
393 _dl_signal_error (ENOMEM, NULL, "cannot create cache for search path");
395 pelem = all_dirs= rtld_search_dirs[0];
396 for (strp = system_dirs; *strp != NULL; ++strp, pelem += round_size)
398 size_t cnt;
400 *aelem++ = pelem;
402 pelem->next = *(strp + 1) == NULL ? NULL : (pelem + round_size);
404 pelem->what = "system search path";
405 pelem->where = NULL;
407 pelem->dirnamelen = strlen (pelem->dirname = *strp);
408 if (pelem->dirnamelen > max_dirnamelen)
409 max_dirnamelen = pelem->dirnamelen;
411 if (pelem->dirname[0] != '/')
412 for (cnt = 0; cnt < ncapstr; ++cnt)
413 pelem->status[cnt] = existing;
414 else
415 for (cnt = 0; cnt < ncapstr; ++cnt)
416 pelem->status[cnt] = unknown;
418 *aelem = NULL;
420 l = _dl_loaded;
421 if (l != NULL)
423 if (l->l_type != lt_loaded && l->l_info[DT_RPATH])
425 /* Allocate room for the search path and fill in information
426 from RPATH. */
427 l->l_rpath_dirs =
428 decompose_rpath ((const char *)
429 (l->l_addr + l->l_info[DT_STRTAB]->d_un.d_ptr
430 + l->l_info[DT_RPATH]->d_un.d_val),
431 nllp, l->l_name);
433 else
435 /* If we have no LD_LIBRARY_PATH and no RPATH we must tell
436 this somehow to prevent we look this up again and again. */
437 if (nllp == 0)
438 l->l_rpath_dirs = (struct r_search_path_elem **) -1l;
439 else
441 l->l_rpath_dirs = (struct r_search_path_elem **)
442 malloc ((nllp + 1) * sizeof (*l->l_rpath_dirs));
443 if (l->l_rpath_dirs == NULL)
444 _dl_signal_error (ENOMEM, NULL,
445 "cannot create cache for search path");
446 l->l_rpath_dirs[0] = NULL;
450 /* We don't need to search the list of fake entries which is searched
451 when no dynamic objects were loaded at this time. */
452 fake_path_list = NULL;
454 if (nllp > 0)
456 char *copy = local_strdup (llp);
458 /* Decompose the LD_LIBRARY_PATH and fill in the result.
459 First search for the next place to enter elements. */
460 struct r_search_path_elem **result = l->l_rpath_dirs;
461 while (*result != NULL)
462 ++result;
464 /* We need to take care that the LD_LIBRARY_PATH environment
465 variable can contain a semicolon. */
466 (void) fillin_rpath (copy, result, ":;",
467 __libc_enable_secure ? system_dirs : NULL,
468 "LD_LIBRARY_PATH", NULL);
471 else
473 /* This is a statically linked program but we still have to
474 take care for the LD_LIBRARY_PATH environment variable. We
475 use a fake link_map entry. This will only contain the
476 l_rpath_dirs information. */
478 if (nllp == 0)
479 fake_path_list = NULL;
480 else
482 fake_path_list = (struct r_search_path_elem **)
483 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
484 if (fake_path_list == NULL)
485 _dl_signal_error (ENOMEM, NULL,
486 "cannot create cache for search path");
488 (void) fillin_rpath (local_strdup (llp), fake_path_list, ":;",
489 __libc_enable_secure ? system_dirs : NULL,
490 "LD_LIBRARY_PATH", NULL);
496 /* Map in the shared object NAME, actually located in REALNAME, and already
497 opened on FD. */
499 struct link_map *
500 _dl_map_object_from_fd (char *name, int fd, char *realname,
501 struct link_map *loader, int l_type)
503 struct link_map *l = NULL;
505 #define LOSE(s) lose (0, (s))
506 void lose (int code, const char *msg)
508 (void) __close (fd);
509 if (l)
511 /* Remove the stillborn object from the list and free it. */
512 if (l->l_prev)
513 l->l_prev->l_next = l->l_next;
514 if (l->l_next)
515 l->l_next->l_prev = l->l_prev;
516 free (l);
518 free (realname);
519 _dl_signal_error (code, name, msg);
520 free (name); /* Hmmm. Can this leak memory? Better
521 than a segfault, anyway. */
524 inline caddr_t map_segment (ElfW(Addr) mapstart, size_t len,
525 int prot, int fixed, off_t offset)
527 caddr_t mapat = __mmap ((caddr_t) mapstart, len, prot,
528 fixed|MAP_COPY|MAP_FILE,
529 fd, offset);
530 if (mapat == MAP_FAILED)
531 lose (errno, "failed to map segment from shared object");
532 return mapat;
535 const ElfW(Ehdr) *header;
536 const ElfW(Phdr) *phdr;
537 const ElfW(Phdr) *ph;
538 size_t maplength;
539 int type;
540 char *readbuf;
541 ssize_t readlength;
543 /* Look again to see if the real name matched another already loaded. */
544 for (l = _dl_loaded; l; l = l->l_next)
545 if (! strcmp (realname, l->l_name))
547 /* The object is already loaded.
548 Just bump its reference count and return it. */
549 __close (fd);
551 /* If the name is not in the list of names for this object add
552 it. */
553 free (realname);
554 add_name_to_object (l, name);
555 ++l->l_opencount;
556 return l;
559 /* Print debugging message. */
560 if (_dl_debug_files)
561 _dl_debug_message (1, "file=", name, "; generating link map\n", NULL);
563 /* Read the header directly. */
564 readbuf = alloca (_dl_pagesize);
565 readlength = __libc_read (fd, readbuf, _dl_pagesize);
566 if (readlength < sizeof(*header))
567 lose (errno, "cannot read file data");
568 header = (void *) readbuf;
570 /* Check the header for basic validity. */
571 if (*(Elf32_Word *) &header->e_ident !=
572 #if BYTE_ORDER == LITTLE_ENDIAN
573 ((ELFMAG0 << (EI_MAG0 * 8)) |
574 (ELFMAG1 << (EI_MAG1 * 8)) |
575 (ELFMAG2 << (EI_MAG2 * 8)) |
576 (ELFMAG3 << (EI_MAG3 * 8)))
577 #else
578 ((ELFMAG0 << (EI_MAG3 * 8)) |
579 (ELFMAG1 << (EI_MAG2 * 8)) |
580 (ELFMAG2 << (EI_MAG1 * 8)) |
581 (ELFMAG3 << (EI_MAG0 * 8)))
582 #endif
584 LOSE ("invalid ELF header");
585 #define ELF32_CLASS ELFCLASS32
586 #define ELF64_CLASS ELFCLASS64
587 if (header->e_ident[EI_CLASS] != ELFW(CLASS))
588 LOSE ("ELF file class not " STRING(__ELF_NATIVE_CLASS) "-bit");
589 if (header->e_ident[EI_DATA] != byteorder)
590 LOSE ("ELF file data encoding not " byteorder_name);
591 if (header->e_ident[EI_VERSION] != EV_CURRENT)
592 LOSE ("ELF file version ident not " STRING(EV_CURRENT));
593 if (header->e_version != EV_CURRENT)
594 LOSE ("ELF file version not " STRING(EV_CURRENT));
595 if (! elf_machine_matches_host (header->e_machine))
596 LOSE ("ELF file machine architecture not " ELF_MACHINE_NAME);
597 if (header->e_phentsize != sizeof (ElfW(Phdr)))
598 LOSE ("ELF file's phentsize not the expected size");
600 #ifndef MAP_ANON
601 #define MAP_ANON 0
602 if (_dl_zerofd == -1)
604 _dl_zerofd = _dl_sysdep_open_zero_fill ();
605 if (_dl_zerofd == -1)
607 __close (fd);
608 _dl_signal_error (errno, NULL, "cannot open zero fill device");
611 #endif
613 /* Enter the new object in the list of loaded objects. */
614 l = _dl_new_object (realname, name, l_type);
615 if (! l)
616 lose (ENOMEM, "cannot create shared object descriptor");
617 l->l_opencount = 1;
618 l->l_loader = loader;
620 /* Extract the remaining details we need from the ELF header
621 and then read in the program header table. */
622 l->l_entry = header->e_entry;
623 type = header->e_type;
624 l->l_phnum = header->e_phnum;
626 maplength = header->e_phnum * sizeof (ElfW(Phdr));
627 if (header->e_phoff + maplength <= readlength)
628 phdr = (void *) (readbuf + header->e_phoff);
629 else
631 phdr = alloca (maplength);
632 __lseek (fd, SEEK_SET, header->e_phoff);
633 if (__libc_read (fd, (void *) phdr, maplength) != maplength)
634 lose (errno, "cannot read file data");
638 /* Scan the program header table, collecting its load commands. */
639 struct loadcmd
641 ElfW(Addr) mapstart, mapend, dataend, allocend;
642 off_t mapoff;
643 int prot;
644 } loadcmds[l->l_phnum], *c;
645 size_t nloadcmds = 0;
647 l->l_ld = 0;
648 l->l_phdr = 0;
649 l->l_addr = 0;
650 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
651 switch (ph->p_type)
653 /* These entries tell us where to find things once the file's
654 segments are mapped in. We record the addresses it says
655 verbatim, and later correct for the run-time load address. */
656 case PT_DYNAMIC:
657 l->l_ld = (void *) ph->p_vaddr;
658 break;
659 case PT_PHDR:
660 l->l_phdr = (void *) ph->p_vaddr;
661 break;
663 case PT_LOAD:
664 /* A load command tells us to map in part of the file.
665 We record the load commands and process them all later. */
666 if (ph->p_align % _dl_pagesize != 0)
667 LOSE ("ELF load command alignment not page-aligned");
668 if ((ph->p_vaddr - ph->p_offset) % ph->p_align)
669 LOSE ("ELF load command address/offset not properly aligned");
671 struct loadcmd *c = &loadcmds[nloadcmds++];
672 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
673 c->mapend = ((ph->p_vaddr + ph->p_filesz + _dl_pagesize - 1)
674 & ~(_dl_pagesize - 1));
675 c->dataend = ph->p_vaddr + ph->p_filesz;
676 c->allocend = ph->p_vaddr + ph->p_memsz;
677 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
678 c->prot = 0;
679 if (ph->p_flags & PF_R)
680 c->prot |= PROT_READ;
681 if (ph->p_flags & PF_W)
682 c->prot |= PROT_WRITE;
683 if (ph->p_flags & PF_X)
684 c->prot |= PROT_EXEC;
685 break;
689 /* Now process the load commands and map segments into memory. */
690 c = loadcmds;
692 /* Length of the sections to be loaded. */
693 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
695 if (type == ET_DYN || type == ET_REL)
697 /* This is a position-independent shared object. We can let the
698 kernel map it anywhere it likes, but we must have space for all
699 the segments in their specified positions relative to the first.
700 So we map the first segment without MAP_FIXED, but with its
701 extent increased to cover all the segments. Then we remove
702 access from excess portion, and there is known sufficient space
703 there to remap from the later segments.
705 As a refinement, sometimes we have an address that we would
706 prefer to map such objects at; but this is only a preference,
707 the OS can do whatever it likes. */
708 caddr_t mapat;
709 ElfW(Addr) mappref;
710 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
711 - MAP_BASE_ADDR (l));
712 mapat = map_segment (mappref, maplength, c->prot, 0, c->mapoff);
713 l->l_addr = (ElfW(Addr)) mapat - c->mapstart;
715 /* Change protection on the excess portion to disallow all access;
716 the portions we do not remap later will be inaccessible as if
717 unallocated. Then jump into the normal segment-mapping loop to
718 handle the portion of the segment past the end of the file
719 mapping. */
720 __mprotect ((caddr_t) (l->l_addr + c->mapend),
721 loadcmds[nloadcmds - 1].allocend - c->mapend,
723 goto postmap;
725 else
727 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
728 fixed. */
729 ELF_FIXED_ADDRESS (loader, c->mapstart);
732 while (c < &loadcmds[nloadcmds])
734 if (c->mapend > c->mapstart)
735 /* Map the segment contents from the file. */
736 map_segment (l->l_addr + c->mapstart, c->mapend - c->mapstart,
737 c->prot, MAP_FIXED, c->mapoff);
739 postmap:
740 if (c->allocend > c->dataend)
742 /* Extra zero pages should appear at the end of this segment,
743 after the data mapped from the file. */
744 ElfW(Addr) zero, zeroend, zeropage;
746 zero = l->l_addr + c->dataend;
747 zeroend = l->l_addr + c->allocend;
748 zeropage = (zero + _dl_pagesize - 1) & ~(_dl_pagesize - 1);
750 if (zeroend < zeropage)
751 /* All the extra data is in the last page of the segment.
752 We can just zero it. */
753 zeropage = zeroend;
755 if (zeropage > zero)
757 /* Zero the final part of the last page of the segment. */
758 if ((c->prot & PROT_WRITE) == 0)
760 /* Dag nab it. */
761 if (__mprotect ((caddr_t) (zero & ~(_dl_pagesize - 1)),
762 _dl_pagesize, c->prot|PROT_WRITE) < 0)
763 lose (errno, "cannot change memory protections");
765 memset ((void *) zero, 0, zeropage - zero);
766 if ((c->prot & PROT_WRITE) == 0)
767 __mprotect ((caddr_t) (zero & ~(_dl_pagesize - 1)),
768 _dl_pagesize, c->prot);
771 if (zeroend > zeropage)
773 /* Map the remaining zero pages in from the zero fill FD. */
774 caddr_t mapat;
775 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
776 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
777 ANONFD, 0);
778 if (mapat == MAP_FAILED)
779 lose (errno, "cannot map zero-fill pages");
783 ++c;
786 if (l->l_phdr == 0)
788 /* There was no PT_PHDR specified. We need to find the phdr in the
789 load image ourselves. We assume it is in fact in the load image
790 somewhere, and that the first load command starts at the
791 beginning of the file and thus contains the ELF file header. */
792 ElfW(Addr) bof = l->l_addr + loadcmds[0].mapstart;
793 assert (loadcmds[0].mapoff == 0);
794 l->l_phdr = (void *) (bof + ((const ElfW(Ehdr) *) bof)->e_phoff);
796 else
797 /* Adjust the PT_PHDR value by the runtime load address. */
798 (ElfW(Addr)) l->l_phdr += l->l_addr;
801 /* We are done mapping in the file. We no longer need the descriptor. */
802 __close (fd);
804 if (l->l_type == lt_library && type == ET_EXEC)
805 l->l_type = lt_executable;
807 if (l->l_ld == 0)
809 if (type == ET_DYN)
810 LOSE ("object file has no dynamic section");
812 else
813 (ElfW(Addr)) l->l_ld += l->l_addr;
815 l->l_entry += l->l_addr;
817 if (_dl_debug_files)
819 const size_t nibbles = sizeof (void *) * 2;
820 char buf1[nibbles + 1];
821 char buf2[nibbles + 1];
822 char buf3[nibbles + 1];
824 buf1[nibbles] = '\0';
825 buf2[nibbles] = '\0';
826 buf3[nibbles] = '\0';
828 memset (buf1, '0', nibbles);
829 memset (buf2, '0', nibbles);
830 memset (buf3, '0', nibbles);
831 _itoa_word ((unsigned long int) l->l_ld, &buf1[nibbles], 16, 0);
832 _itoa_word ((unsigned long int) l->l_addr, &buf2[nibbles], 16, 0);
833 _itoa_word (maplength, &buf3[nibbles], 16, 0);
835 _dl_debug_message (1, " dynamic: 0x", buf1, " base: 0x", buf2,
836 " size: 0x", buf3, "\n", NULL);
837 memset (buf1, '0', nibbles);
838 memset (buf2, '0', nibbles);
839 memset (buf3, ' ', nibbles);
840 _itoa_word ((unsigned long int) l->l_entry, &buf1[nibbles], 16, 0);
841 _itoa_word ((unsigned long int) l->l_phdr, &buf2[nibbles], 16, 0);
842 _itoa_word (l->l_phnum, &buf3[nibbles], 10, 0);
843 _dl_debug_message (1, " entry: 0x", buf1, " phdr: 0x", buf2,
844 " phnum: ", buf3, "\n\n", NULL);
847 elf_get_dynamic_info (l->l_ld, l->l_info);
848 if (l->l_info[DT_HASH])
849 _dl_setup_hash (l);
851 return l;
854 /* Print search path. */
855 static void
856 print_search_path (struct r_search_path_elem **list,
857 const char *what, const char *name)
859 char buf[max_dirnamelen + max_capstrlen];
860 int first = 1;
862 _dl_debug_message (1, " search path=", NULL);
864 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
866 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
867 size_t cnt;
869 for (cnt = 0; cnt < ncapstr; ++cnt)
870 if ((*list)->status[cnt] != nonexisting)
872 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
873 cp[-1] = '\0';
874 _dl_debug_message (0, first ? "" : ":", buf, NULL);
875 first = 0;
878 ++list;
881 if (name != NULL)
882 _dl_debug_message (0, "\t\t(", what, " from file ",
883 name[0] ? name : _dl_argv[0], ")\n", NULL);
884 else
885 _dl_debug_message (0, "\t\t(", what, ")\n", NULL);
888 /* Try to open NAME in one of the directories in DIRS.
889 Return the fd, or -1. If successful, fill in *REALNAME
890 with the malloc'd full directory name. */
892 static int
893 open_path (const char *name, size_t namelen, int preloaded,
894 struct r_search_path_elem **dirs,
895 char **realname)
897 char *buf;
898 int fd = -1;
899 const char *current_what = NULL;
901 if (dirs == NULL || *dirs == NULL)
903 __set_errno (ENOENT);
904 return -1;
907 buf = __alloca (max_dirnamelen + max_capstrlen + namelen + 1);
910 struct r_search_path_elem *this_dir = *dirs;
911 size_t buflen = 0;
912 size_t cnt;
914 /* If we are debugging the search for libraries print the path
915 now if it hasn't happened now. */
916 if (_dl_debug_libs && current_what != this_dir->what)
918 current_what = this_dir->what;
919 print_search_path (dirs, current_what, this_dir->where);
922 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
924 /* Skip this directory if we know it does not exist. */
925 if (this_dir->status[cnt] == nonexisting)
926 continue;
928 buflen =
929 ((char *) __mempcpy (__mempcpy (__mempcpy (buf, this_dir->dirname,
930 this_dir->dirnamelen),
931 capstr[cnt].str, capstr[cnt].len),
932 name, namelen)
933 - buf);
935 /* Print name we try if this is wanted. */
936 if (_dl_debug_libs)
937 _dl_debug_message (1, " trying file=", buf, "\n", NULL);
939 fd = __open (buf, O_RDONLY);
940 if (this_dir->status[cnt] == unknown)
941 if (fd != -1)
942 this_dir->status[cnt] = existing;
943 else
945 /* We failed to open machine dependent library. Let's
946 test whether there is any directory at all. */
947 struct stat st;
949 buf[this_dir->dirnamelen
950 + MAX (capstr[cnt].len - 1, 0)] = '\0';
952 if (__xstat (_STAT_VER, buf, &st) != 0
953 || ! S_ISDIR (st.st_mode))
954 /* The directory does not exist ot it is no directory. */
955 this_dir->status[cnt] = nonexisting;
956 else
957 this_dir->status[cnt] = existing;
960 if (fd != -1 && preloaded && __libc_enable_secure)
962 /* This is an extra security effort to make sure nobody can
963 preload broken shared objects which are in the trusted
964 directories and so exploit the bugs. */
965 struct stat st;
967 if (__fxstat (_STAT_VER, fd, &st) != 0
968 || (st.st_mode & S_ISUID) == 0)
970 /* The shared object cannot be tested for being SUID
971 or this bit is not set. In this case we must not
972 use this object. */
973 __close (fd);
974 fd = -1;
975 /* We simply ignore the file, signal this by setting
976 the error value which would have been set by `open'. */
977 errno = ENOENT;
982 if (fd != -1)
984 *realname = malloc (buflen);
985 if (*realname != NULL)
987 memcpy (*realname, buf, buflen);
988 return fd;
990 else
992 /* No memory for the name, we certainly won't be able
993 to load and link it. */
994 __close (fd);
995 return -1;
998 if (errno != ENOENT && errno != EACCES)
999 /* The file exists and is readable, but something went wrong. */
1000 return -1;
1002 while (*++dirs != NULL);
1004 return -1;
1007 /* Map in the shared object file NAME. */
1009 struct link_map *
1010 internal_function
1011 _dl_map_object (struct link_map *loader, const char *name, int preloaded,
1012 int type, int trace_mode)
1014 int fd;
1015 char *realname;
1016 char *name_copy;
1017 struct link_map *l;
1019 /* Look for this name among those already loaded. */
1020 for (l = _dl_loaded; l; l = l->l_next)
1022 /* If the requested name matches the soname of a loaded object,
1023 use that object. Elide this check for names that have not
1024 yet been opened. */
1025 if (l->l_opencount <= 0)
1026 continue;
1027 if (!_dl_name_match_p (name, l))
1029 const char *soname;
1031 if (l->l_info[DT_SONAME] == NULL)
1032 continue;
1034 soname = (const char *) (l->l_addr
1035 + l->l_info[DT_STRTAB]->d_un.d_ptr
1036 + l->l_info[DT_SONAME]->d_un.d_val);
1037 if (strcmp (name, soname) != 0)
1038 continue;
1040 /* We have a match on a new name -- cache it. */
1041 add_name_to_object (l, local_strdup (soname));
1044 /* We have a match -- bump the reference count and return it. */
1045 ++l->l_opencount;
1046 return l;
1049 /* Display information if we are debugging. */
1050 if (_dl_debug_files && loader != NULL)
1051 _dl_debug_message (1, "\nfile=", name, "; needed by ",
1052 loader->l_name[0] ? loader->l_name : _dl_argv[0],
1053 "\n", NULL);
1055 if (strchr (name, '/') == NULL)
1057 /* Search for NAME in several places. */
1059 size_t namelen = strlen (name) + 1;
1061 if (_dl_debug_libs)
1062 _dl_debug_message (1, "find library=", name, "; searching\n", NULL);
1064 fd = -1;
1066 /* First try the DT_RPATH of the dependent object that caused NAME
1067 to be loaded. Then that object's dependent, and on up. */
1068 for (l = loader; fd == -1 && l; l = l->l_loader)
1069 if (l && l->l_info[DT_RPATH])
1071 /* Make sure the cache information is available. */
1072 if (l->l_rpath_dirs == NULL)
1074 size_t ptrval = (l->l_addr
1075 + l->l_info[DT_STRTAB]->d_un.d_ptr
1076 + l->l_info[DT_RPATH]->d_un.d_val);
1077 l->l_rpath_dirs =
1078 decompose_rpath ((const char *) ptrval, 0, l->l_name);
1081 if (l->l_rpath_dirs != (struct r_search_path_elem **) -1l)
1082 fd = open_path (name, namelen, preloaded, l->l_rpath_dirs,
1083 &realname);
1086 /* If dynamically linked, try the DT_RPATH of the executable itself
1087 and the LD_LIBRARY_PATH environment variable. */
1088 l = _dl_loaded;
1089 if (fd == -1 && l && l->l_type != lt_loaded
1090 && l->l_rpath_dirs != (struct r_search_path_elem **) -1l)
1091 fd = open_path (name, namelen, preloaded, l->l_rpath_dirs, &realname);
1093 /* This is used if a static binary uses dynamic loading and there
1094 is a LD_LIBRARY_PATH given. */
1095 if (fd == -1 && fake_path_list != NULL)
1096 fd = open_path (name, namelen, preloaded, fake_path_list, &realname);
1098 if (fd == -1)
1100 /* Check the list of libraries in the file /etc/ld.so.cache,
1101 for compatibility with Linux's ldconfig program. */
1102 extern const char *_dl_load_cache_lookup (const char *name);
1103 const char *cached = _dl_load_cache_lookup (name);
1104 if (cached)
1106 fd = __open (cached, O_RDONLY);
1107 if (fd != -1)
1109 realname = local_strdup (cached);
1110 if (realname == NULL)
1112 __close (fd);
1113 fd = -1;
1119 /* Finally, try the default path. */
1120 if (fd == -1)
1121 fd = open_path (name, namelen, preloaded, rtld_search_dirs, &realname);
1123 /* Add another newline when we a tracing the library loading. */
1124 if (_dl_debug_libs)
1125 _dl_debug_message (1, "\n", NULL);
1127 else
1129 fd = __open (name, O_RDONLY);
1130 if (fd != -1)
1132 realname = local_strdup (name);
1133 if (realname == NULL)
1135 __close (fd);
1136 fd = -1;
1141 if (fd != -1)
1143 name_copy = local_strdup (name);
1144 if (name_copy == NULL)
1146 __close (fd);
1147 fd = -1;
1151 if (fd == -1)
1153 if (trace_mode)
1155 /* We haven't found an appropriate library. But since we
1156 are only interested in the list of libraries this isn't
1157 so severe. Fake an entry with all the information we
1158 have. */
1159 static const ElfW(Symndx) dummy_bucket = STN_UNDEF;
1161 /* Enter the new object in the list of loaded objects. */
1162 if ((name_copy = local_strdup (name)) == NULL
1163 || (l = _dl_new_object (name_copy, name, type)) == NULL)
1164 _dl_signal_error (ENOMEM, name,
1165 "cannot create shared object descriptor");
1166 /* We use an opencount of 0 as a sign for the faked entry. */
1167 l->l_opencount = 0;
1168 l->l_reserved = 0;
1169 l->l_buckets = &dummy_bucket;
1170 l->l_nbuckets = 1;
1171 l->l_relocated = 1;
1173 return l;
1175 else
1176 _dl_signal_error (errno, name, "cannot open shared object file");
1179 return _dl_map_object_from_fd (name_copy, fd, realname, loader, type);