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