]> 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,96,97,98,99,2000 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 <libintl.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <ldsodefs.h>
28 #include <sys/mman.h>
29 #include <sys/param.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include "dynamic-link.h"
33 #include <stdio-common/_itoa.h>
34
35 #include <dl-dst.h>
36
37 /* On some systems, no flag bits are given to specify file mapping. */
38 #ifndef MAP_FILE
39 # define MAP_FILE 0
40 #endif
41
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
52
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
61
62
63 #include <endian.h>
64 #if BYTE_ORDER == BIG_ENDIAN
65 # define byteorder ELFDATA2MSB
66 #elif BYTE_ORDER == LITTLE_ENDIAN
67 # define byteorder ELFDATA2LSB
68 #else
69 # error "Unknown BYTE_ORDER " BYTE_ORDER
70 # define byteorder ELFDATANONE
71 #endif
72
73 #define STRING(x) __STRING (x)
74
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
82
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
94
95 size_t _dl_pagesize;
96
97 extern const char *_dl_platform;
98 extern size_t _dl_platformlen;
99
100 /* This is the decomposed LD_LIBRARY_PATH search path. */
101 static struct r_search_path_struct env_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 const unsigned char _dl_pf_to_prot[8] =
109 {
110 [0] = PROT_NONE,
111 [PF_R] = PROT_READ,
112 [PF_W] = PROT_WRITE,
113 [PF_R | PF_W] = PROT_READ | PROT_WRITE,
114 [PF_X] = PROT_EXEC,
115 [PF_R | PF_X] = PROT_READ | PROT_EXEC,
116 [PF_W | PF_X] = PROT_WRITE | PROT_EXEC,
117 [PF_R | PF_W | PF_X] = PROT_READ | PROT_WRITE | PROT_EXEC
118 };
119
120
121 /* Get the generated information about the trusted directories. */
122 #include "trusted-dirs.h"
123
124 static const char system_dirs[] = SYSTEM_DIRS;
125 static const size_t system_dirs_len[] =
126 {
127 SYSTEM_DIRS_LEN
128 };
129 #define nsystem_dirs_len \
130 (sizeof (system_dirs_len) / sizeof (system_dirs_len[0]))
131
132
133 /* Local version of `strdup' function. */
134 static inline char *
135 local_strdup (const char *s)
136 {
137 size_t len = strlen (s) + 1;
138 void *new = malloc (len);
139
140 if (new == NULL)
141 return NULL;
142
143 return (char *) memcpy (new, s, len);
144 }
145
146
147 size_t
148 _dl_dst_count (const char *name, int is_path)
149 {
150 const char *const start = name;
151 size_t cnt = 0;
152
153 do
154 {
155 size_t len = 1;
156
157 /* $ORIGIN is not expanded for SUID/GUID programs.
158
159 Note that it is no bug that the strings in the first two `strncmp'
160 calls are longer than the sequence which is actually tested. */
161 if ((((strncmp (&name[1], "ORIGIN}", 6) == 0
162 && (!__libc_enable_secure
163 || ((name[7] == '\0' || (is_path && name[7] == ':'))
164 && (name == start || (is_path && name[-1] == ':'))))
165 && (len = 7) != 0)
166 || (strncmp (&name[1], "PLATFORM}", 8) == 0 && (len = 9) != 0))
167 && (name[len] == '\0' || name[len] == '/'
168 || (is_path && name[len] == ':')))
169 || (name[1] == '{'
170 && ((strncmp (&name[2], "ORIGIN}", 7) == 0
171 && (!__libc_enable_secure
172 || ((name[9] == '\0' || (is_path && name[9] == ':'))
173 && (name == start || (is_path && name[-1] == ':'))))
174 && (len = 9) != 0)
175 || (strncmp (&name[2], "PLATFORM}", 9) == 0
176 && (len = 11) != 0))))
177 ++cnt;
178
179 name = strchr (name + len, '$');
180 }
181 while (name != NULL);
182
183 return cnt;
184 }
185
186
187 char *
188 _dl_dst_substitute (struct link_map *l, const char *name, char *result,
189 int is_path)
190 {
191 const char *const start = name;
192 char *last_elem, *wp;
193
194 /* Now fill the result path. While copying over the string we keep
195 track of the start of the last path element. When we come accross
196 a DST we copy over the value or (if the value is not available)
197 leave the entire path element out. */
198 last_elem = wp = result;
199
200 do
201 {
202 if (*name == '$')
203 {
204 const char *repl;
205 size_t len;
206
207 /* Note that it is no bug that the strings in the first two `strncmp'
208 calls are longer than the sequence which is actually tested. */
209 if ((((strncmp (&name[1], "ORIGIN}", 6) == 0 && (len = 7) != 0)
210 || (strncmp (&name[1], "PLATFORM}", 8) == 0 && (len = 9) != 0))
211 && (name[len] == '\0' || name[len] == '/'
212 || (is_path && name[len] == ':')))
213 || (name[1] == '{'
214 && ((strncmp (&name[2], "ORIGIN}", 7) == 0 && (len = 9) != 0)
215 || (strncmp (&name[2], "PLATFORM}", 9) == 0
216 && (len = 11) != 0))))
217 {
218 repl = ((len == 7 || name[2] == 'O')
219 ? (__libc_enable_secure
220 && ((name[len] != '\0'
221 && (!is_path || name[len] != ':'))
222 || (name != start
223 && (!is_path || name[-1] != ':')))
224 ? NULL : l->l_origin)
225 : _dl_platform);
226
227 if (repl != NULL && repl != (const char *) -1)
228 {
229 wp = __stpcpy (wp, repl);
230 name += len;
231 }
232 else
233 {
234 /* We cannot use this path element, the value of the
235 replacement is unknown. */
236 wp = last_elem;
237 name += len;
238 while (*name != '\0' && (!is_path || *name != ':'))
239 ++name;
240 }
241 }
242 else
243 /* No DST we recognize. */
244 *wp++ = *name++;
245 }
246 else if (is_path && *name == ':')
247 {
248 *wp++ = *name++;
249 last_elem = wp;
250 }
251 else
252 *wp++ = *name++;
253 }
254 while (*name != '\0');
255
256 *wp = '\0';
257
258 return result;
259 }
260
261
262 /* Return copy of argument with all recognized dynamic string tokens
263 ($ORIGIN and $PLATFORM for now) replaced. On some platforms it
264 might not be possible to determine the path from which the object
265 belonging to the map is loaded. In this case the path element
266 containing $ORIGIN is left out. */
267 static char *
268 expand_dynamic_string_token (struct link_map *l, const char *s)
269 {
270 /* We make two runs over the string. First we determine how large the
271 resulting string is and then we copy it over. Since this is now
272 frequently executed operation we are looking here not for performance
273 but rather for code size. */
274 size_t cnt;
275 size_t total;
276 char *result;
277
278 /* Determine the number of DST elements. */
279 cnt = DL_DST_COUNT (s, 1);
280
281 /* If we do not have to replace anything simply copy the string. */
282 if (cnt == 0)
283 return local_strdup (s);
284
285 /* Determine the length of the substituted string. */
286 total = DL_DST_REQUIRED (l, s, strlen (s), cnt);
287
288 /* Allocate the necessary memory. */
289 result = (char *) malloc (total + 1);
290 if (result == NULL)
291 return NULL;
292
293 return DL_DST_SUBSTITUTE (l, s, result, 1);
294 }
295
296
297 /* Add `name' to the list of names for a particular shared object.
298 `name' is expected to have been allocated with malloc and will
299 be freed if the shared object already has this name.
300 Returns false if the object already had this name. */
301 static void
302 internal_function
303 add_name_to_object (struct link_map *l, const char *name)
304 {
305 struct libname_list *lnp, *lastp;
306 struct libname_list *newname;
307 size_t name_len;
308
309 lastp = NULL;
310 for (lnp = l->l_libname; lnp != NULL; lastp = lnp, lnp = lnp->next)
311 if (strcmp (name, lnp->name) == 0)
312 return;
313
314 name_len = strlen (name) + 1;
315 newname = (struct libname_list *) malloc (sizeof *newname + name_len);
316 if (newname == NULL)
317 {
318 /* No more memory. */
319 _dl_signal_error (ENOMEM, name, N_("cannot allocate name record"));
320 return;
321 }
322 /* The object should have a libname set from _dl_new_object. */
323 assert (lastp != NULL);
324
325 newname->name = memcpy (newname + 1, name, name_len);
326 newname->next = NULL;
327 newname->dont_free = 0;
328 lastp->next = newname;
329 }
330
331 /* All known directories in sorted order. */
332 struct r_search_path_elem *_dl_all_dirs;
333
334 /* All directories after startup. */
335 struct r_search_path_elem *_dl_init_all_dirs;
336
337 /* Standard search directories. */
338 static struct r_search_path_struct rtld_search_dirs;
339
340 static size_t max_dirnamelen;
341
342 static inline struct r_search_path_elem **
343 fillin_rpath (char *rpath, struct r_search_path_elem **result, const char *sep,
344 int check_trusted, const char *what, const char *where)
345 {
346 char *cp;
347 size_t nelems = 0;
348
349 while ((cp = __strsep (&rpath, sep)) != NULL)
350 {
351 struct r_search_path_elem *dirp;
352 size_t len = strlen (cp);
353
354 /* `strsep' can pass an empty string. This has to be
355 interpreted as `use the current directory'. */
356 if (len == 0)
357 {
358 static const char curwd[] = "./";
359 cp = (char *) curwd;
360 }
361
362 /* Remove trailing slashes (except for "/"). */
363 while (len > 1 && cp[len - 1] == '/')
364 --len;
365
366 /* Now add one if there is none so far. */
367 if (len > 0 && cp[len - 1] != '/')
368 cp[len++] = '/';
369
370 /* See if this directory is already known. */
371 for (dirp = _dl_all_dirs; dirp != NULL; dirp = dirp->next)
372 if (dirp->dirnamelen == len && memcmp (cp, dirp->dirname, len) == 0)
373 break;
374
375 if (dirp != NULL)
376 {
377 /* It is available, see whether it's on our own list. */
378 size_t cnt;
379 for (cnt = 0; cnt < nelems; ++cnt)
380 if (result[cnt] == dirp)
381 break;
382
383 if (cnt == nelems)
384 result[nelems++] = dirp;
385 }
386 else
387 {
388 size_t cnt;
389 enum r_dir_status init_val;
390 size_t where_len = where ? strlen (where) + 1 : 0;
391
392 /* It's a new directory. Create an entry and add it. */
393 dirp = (struct r_search_path_elem *)
394 malloc (sizeof (*dirp) + ncapstr * sizeof (enum r_dir_status)
395 + where_len + len + 1);
396 if (dirp == NULL)
397 _dl_signal_error (ENOMEM, NULL,
398 N_("cannot create cache for search path"));
399
400 dirp->dirname = ((char *) dirp + sizeof (*dirp)
401 + ncapstr * sizeof (enum r_dir_status));
402 memcpy ((char *) dirp->dirname, cp, len + 1);
403 dirp->dirnamelen = len;
404
405 if (len > max_dirnamelen)
406 max_dirnamelen = len;
407
408 /* Make sure we don't use untrusted directories if we run SUID. */
409 if (__builtin_expect (check_trusted, 0))
410 {
411 const char *trun = system_dirs;
412 size_t idx;
413
414 /* By default we don't trust anything. */
415 init_val = nonexisting;
416
417 /* All trusted directories must be complete names. */
418 if (cp[0] == '/')
419 {
420 for (idx = 0; idx < nsystem_dirs_len; ++idx)
421 {
422 if (len == system_dirs_len[idx]
423 && memcmp (trun, cp, len) == 0)
424 /* Found it. */
425 break;
426
427 trun += system_dirs_len[idx] + 1;
428 }
429
430 if (idx < nsystem_dirs_len)
431 /* It's a trusted directory so allow checking for it. */
432 init_val = unknown;
433 }
434 }
435 else
436 /* We don't have to check for trusted directories and can
437 accept everything. We have to make sure all the
438 relative directories are never ignored. The current
439 directory might change and all our saved information
440 would be void. */
441 init_val = cp[0] != '/' ? existing : unknown;
442
443 for (cnt = 0; cnt < ncapstr; ++cnt)
444 dirp->status[cnt] = init_val;
445
446 dirp->what = what;
447 if (__builtin_expect (where != NULL, 1))
448 dirp->where = memcpy ((char *) dirp + sizeof (*dirp) + len + 1
449 + ncapstr * sizeof (enum r_dir_status),
450 where, where_len);
451 else
452 dirp->where = NULL;
453
454 dirp->next = _dl_all_dirs;
455 _dl_all_dirs = dirp;
456
457 /* Put it in the result array. */
458 result[nelems++] = dirp;
459 }
460 }
461
462 /* Terminate the array. */
463 result[nelems] = NULL;
464
465 return result;
466 }
467
468
469 static void
470 internal_function
471 decompose_rpath (struct r_search_path_struct *sps,
472 const char *rpath, struct link_map *l, const char *what)
473 {
474 /* Make a copy we can work with. */
475 const char *where = l->l_name;
476 char *copy;
477 char *cp;
478 struct r_search_path_elem **result;
479 size_t nelems;
480
481 /* First see whether we must forget the RUNPATH and RPATH from this
482 object. */
483 if (__builtin_expect (_dl_inhibit_rpath != NULL, 0) && !__libc_enable_secure)
484 {
485 const char *found = strstr (_dl_inhibit_rpath, where);
486 if (found != NULL)
487 {
488 size_t len = strlen (where);
489 if ((found == _dl_inhibit_rpath || found[-1] == ':')
490 && (found[len] == '\0' || found[len] == ':'))
491 {
492 /* This object is on the list of objects for which the
493 RUNPATH and RPATH must not be used. */
494 result = (struct r_search_path_elem **)
495 malloc (sizeof (*result));
496 if (result == NULL)
497 _dl_signal_error (ENOMEM, NULL,
498 N_("cannot create cache for search path"));
499 result[0] = NULL;
500
501 sps->dirs = result;
502 sps->malloced = 1;
503
504 return;
505 }
506 }
507 }
508
509 /* Make a writable copy. At the same time expand possible dynamic
510 string tokens. */
511 copy = expand_dynamic_string_token (l, rpath);
512 if (copy == NULL)
513 _dl_signal_error (ENOMEM, NULL, N_("cannot create RUNPATH/RPATH copy"));
514
515 /* Count the number of necessary elements in the result array. */
516 nelems = 0;
517 for (cp = copy; *cp != '\0'; ++cp)
518 if (*cp == ':')
519 ++nelems;
520
521 /* Allocate room for the result. NELEMS + 1 is an upper limit for the
522 number of necessary entries. */
523 result = (struct r_search_path_elem **) malloc ((nelems + 1 + 1)
524 * sizeof (*result));
525 if (result == NULL)
526 _dl_signal_error (ENOMEM, NULL, N_("cannot create cache for search path"));
527
528 fillin_rpath (copy, result, ":", 0, what, where);
529
530 /* Free the copied RPATH string. `fillin_rpath' make own copies if
531 necessary. */
532 free (copy);
533
534 sps->dirs = result;
535 /* The caller will change this value if we haven't used a real malloc. */
536 sps->malloced = 1;
537 }
538
539
540 void
541 internal_function
542 _dl_init_paths (const char *llp)
543 {
544 size_t idx;
545 const char *strp;
546 struct r_search_path_elem *pelem, **aelem;
547 size_t round_size;
548 #ifdef SHARED
549 struct link_map *l;
550 #endif
551
552 /* Fill in the information about the application's RPATH and the
553 directories addressed by the LD_LIBRARY_PATH environment variable. */
554
555 /* Get the capabilities. */
556 capstr = _dl_important_hwcaps (_dl_platform, _dl_platformlen,
557 &ncapstr, &max_capstrlen);
558
559 /* First set up the rest of the default search directory entries. */
560 aelem = rtld_search_dirs.dirs = (struct r_search_path_elem **)
561 malloc ((nsystem_dirs_len + 1) * sizeof (struct r_search_path_elem *));
562 if (rtld_search_dirs.dirs == NULL)
563 _dl_signal_error (ENOMEM, NULL, N_("cannot create search path array"));
564
565 round_size = ((2 * sizeof (struct r_search_path_elem) - 1
566 + ncapstr * sizeof (enum r_dir_status))
567 / sizeof (struct r_search_path_elem));
568
569 rtld_search_dirs.dirs[0] = (struct r_search_path_elem *)
570 malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]))
571 * round_size * sizeof (struct r_search_path_elem));
572 if (rtld_search_dirs.dirs[0] == NULL)
573 _dl_signal_error (ENOMEM, NULL, N_("cannot create cache for search path"));
574
575 rtld_search_dirs.malloced = 0;
576 pelem = _dl_all_dirs = rtld_search_dirs.dirs[0];
577 strp = system_dirs;
578 idx = 0;
579
580 do
581 {
582 size_t cnt;
583
584 *aelem++ = pelem;
585
586 pelem->what = "system search path";
587 pelem->where = NULL;
588
589 pelem->dirname = strp;
590 pelem->dirnamelen = system_dirs_len[idx];
591 strp += system_dirs_len[idx] + 1;
592
593 /* System paths must be absolute. */
594 assert (pelem->dirname[0] == '/');
595 for (cnt = 0; cnt < ncapstr; ++cnt)
596 pelem->status[cnt] = unknown;
597
598 pelem->next = (++idx == nsystem_dirs_len ? NULL : (pelem + round_size));
599
600 pelem += round_size;
601 }
602 while (idx < nsystem_dirs_len);
603
604 max_dirnamelen = SYSTEM_DIRS_MAX_LEN;
605 *aelem = NULL;
606
607 #ifdef SHARED
608 /* This points to the map of the main object. */
609 l = _dl_loaded;
610 if (l != NULL)
611 {
612 assert (l->l_type != lt_loaded);
613
614 if (l->l_info[DT_RUNPATH])
615 {
616 /* Allocate room for the search path and fill in information
617 from RUNPATH. */
618 decompose_rpath (&l->l_runpath_dirs,
619 (const void *) (D_PTR (l, l_info[DT_STRTAB])
620 + l->l_info[DT_RUNPATH]->d_un.d_val),
621 l, "RUNPATH");
622
623 /* The RPATH is ignored. */
624 l->l_rpath_dirs.dirs = (void *) -1;
625 }
626 else
627 {
628 l->l_runpath_dirs.dirs = (void *) -1;
629
630 if (l->l_info[DT_RPATH])
631 {
632 /* Allocate room for the search path and fill in information
633 from RPATH. */
634 decompose_rpath (&l->l_rpath_dirs,
635 (const void *) (D_PTR (l, l_info[DT_STRTAB])
636 + l->l_info[DT_RPATH]->d_un.d_val),
637 l, "RPATH");
638 l->l_rpath_dirs.malloced = 0;
639 }
640 else
641 l->l_rpath_dirs.dirs = (void *) -1;
642 }
643 }
644 #endif /* SHARED */
645
646 if (llp != NULL && *llp != '\0')
647 {
648 size_t nllp;
649 const char *cp = llp;
650
651 /* Decompose the LD_LIBRARY_PATH contents. First determine how many
652 elements it has. */
653 nllp = 1;
654 while (*cp)
655 {
656 if (*cp == ':' || *cp == ';')
657 ++nllp;
658 ++cp;
659 }
660
661 env_path_list.dirs = (struct r_search_path_elem **)
662 malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
663 if (env_path_list.dirs == NULL)
664 _dl_signal_error (ENOMEM, NULL,
665 N_("cannot create cache for search path"));
666
667 (void) fillin_rpath (strdupa (llp), env_path_list.dirs, ":;",
668 __libc_enable_secure, "LD_LIBRARY_PATH", NULL);
669
670 if (env_path_list.dirs[0] == NULL)
671 {
672 free (env_path_list.dirs);
673 env_path_list.dirs = (void *) -1;
674 }
675
676 env_path_list.malloced = 0;
677 }
678 else
679 env_path_list.dirs = (void *) -1;
680
681 /* Remember the last search directory added at startup. */
682 _dl_init_all_dirs = _dl_all_dirs;
683 }
684
685
686 /* Think twice before changing anything in this function. It is placed
687 here and prepared using the `alloca' magic to prevent it from being
688 inlined. The function is only called in case of an error. But then
689 performance does not count. The function used to be "inlinable" and
690 the compiled did so all the time. This increased the code size for
691 absolutely no good reason. */
692 #define LOSE(code, s) lose (code, fd, name, realname, l, s)
693 static void
694 __attribute__ ((noreturn))
695 lose (int code, int fd, const char *name, char *realname, struct link_map *l,
696 const char *msg)
697 {
698 /* The use of `alloca' here looks ridiculous but it helps. The goal
699 is to avoid the function from being inlined. There is no official
700 way to do this so we use this trick. gcc never inlines functions
701 which use `alloca'. */
702 int *a = alloca (sizeof (int));
703 a[0] = fd;
704 (void) __close (a[0]);
705 if (l != NULL)
706 {
707 /* Remove the stillborn object from the list and free it. */
708 if (l->l_prev)
709 l->l_prev->l_next = l->l_next;
710 if (l->l_next)
711 l->l_next->l_prev = l->l_prev;
712 --_dl_nloaded;
713 free (l);
714 }
715 free (realname);
716 _dl_signal_error (code, name, msg);
717 }
718
719
720 /* Map in the shared object NAME, actually located in REALNAME, and already
721 opened on FD. */
722
723 #ifndef EXTERNAL_MAP_FROM_FD
724 static
725 #endif
726 struct link_map *
727 _dl_map_object_from_fd (const char *name, int fd, char *realname,
728 struct link_map *loader, int l_type, int mode)
729 {
730 /* This is the expected ELF header. */
731 #define ELF32_CLASS ELFCLASS32
732 #define ELF64_CLASS ELFCLASS64
733 #ifndef VALID_ELF_HEADER
734 # define VALID_ELF_HEADER(hdr,exp,size) (memcmp (hdr, exp, size) == 0)
735 # define VALID_ELF_OSABI(osabi) (osabi == ELFOSABI_SYSV)
736 # define VALID_ELF_ABIVERSION(ver) (ver == 0)
737 #endif
738 static const unsigned char expected[EI_PAD] =
739 {
740 [EI_MAG0] = ELFMAG0,
741 [EI_MAG1] = ELFMAG1,
742 [EI_MAG2] = ELFMAG2,
743 [EI_MAG3] = ELFMAG3,
744 [EI_CLASS] = ELFW(CLASS),
745 [EI_DATA] = byteorder,
746 [EI_VERSION] = EV_CURRENT,
747 [EI_OSABI] = ELFOSABI_SYSV,
748 [EI_ABIVERSION] = 0
749 };
750 struct link_map *l = NULL;
751
752 inline caddr_t map_segment (ElfW(Addr) mapstart, size_t len,
753 int prot, int fixed, off_t offset)
754 {
755 caddr_t mapat = __mmap ((caddr_t) mapstart, len, prot,
756 fixed|MAP_COPY|MAP_FILE,
757 fd, offset);
758 if (mapat == MAP_FAILED)
759 LOSE (errno, N_("failed to map segment from shared object"));
760 return mapat;
761 }
762
763 const ElfW(Ehdr) *header;
764 const ElfW(Phdr) *phdr;
765 const ElfW(Phdr) *ph;
766 size_t maplength;
767 int type;
768 char *readbuf;
769 ssize_t readlength;
770 struct stat64 st;
771
772 /* Get file information. */
773 if (__fxstat64 (_STAT_VER, fd, &st) < 0)
774 LOSE (errno, N_("cannot stat shared object"));
775
776 /* Look again to see if the real name matched another already loaded. */
777 for (l = _dl_loaded; l; l = l->l_next)
778 if (l->l_ino == st.st_ino && l->l_dev == st.st_dev)
779 {
780 unsigned int i;
781
782 /* The object is already loaded.
783 Just bump its reference count and return it. */
784 __close (fd);
785
786 /* If the name is not in the list of names for this object add
787 it. */
788 free (realname);
789 add_name_to_object (l, name);
790
791 if (l->l_initfini != NULL)
792 for (i = 1; l->l_initfini[i] != NULL; ++i)
793 ++l->l_initfini[i]->l_opencount;
794 ++l->l_opencount;
795 return l;
796 }
797
798 if (mode & RTLD_NOLOAD)
799 /* We are not supposed to load the object unless it is already
800 loaded. So return now. */
801 return NULL;
802
803 /* Print debugging message. */
804 if (__builtin_expect (_dl_debug_files, 0))
805 _dl_debug_message (1, "file=", name, "; generating link map\n", NULL);
806
807 /* Read the header directly. */
808 readbuf = alloca (_dl_pagesize);
809 readlength = __libc_read (fd, readbuf, _dl_pagesize);
810 if (readlength < (ssize_t) sizeof (*header))
811 LOSE (errno, N_("cannot read file data"));
812 header = (void *) readbuf;
813
814 /* Check the header for basic validity. */
815 if (__builtin_expect (!VALID_ELF_HEADER (header->e_ident, expected, EI_PAD),
816 0))
817 {
818 /* Something is wrong. */
819 if (*(Elf32_Word *) &header->e_ident !=
820 #if BYTE_ORDER == LITTLE_ENDIAN
821 ((ELFMAG0 << (EI_MAG0 * 8)) |
822 (ELFMAG1 << (EI_MAG1 * 8)) |
823 (ELFMAG2 << (EI_MAG2 * 8)) |
824 (ELFMAG3 << (EI_MAG3 * 8)))
825 #else
826 ((ELFMAG0 << (EI_MAG3 * 8)) |
827 (ELFMAG1 << (EI_MAG2 * 8)) |
828 (ELFMAG2 << (EI_MAG1 * 8)) |
829 (ELFMAG3 << (EI_MAG0 * 8)))
830 #endif
831 )
832 LOSE (0, N_("invalid ELF header"));
833 if (header->e_ident[EI_CLASS] != ELFW(CLASS))
834 {
835 if (__ELF_NATIVE_CLASS == 32)
836 LOSE (0, N_("ELF file class not 32-bit"));
837 else
838 LOSE (0, N_("ELF file class not 64-bit"));
839 }
840 if (header->e_ident[EI_DATA] != byteorder)
841 {
842 if (BYTE_ORDER == BIG_ENDIAN)
843 LOSE (0, "ELF file data encoding not big-endian");
844 else
845 LOSE (0, "ELF file data encoding not little-endian");
846 }
847 if (header->e_ident[EI_VERSION] != EV_CURRENT)
848 LOSE (0, N_("ELF file version ident does not match current one"));
849 /* XXX We should be able so set system specific versions which are
850 allowed here. */
851 if (!VALID_ELF_OSABI (header->e_ident[EI_OSABI]))
852 LOSE (0, N_("ELF file OS ABI invalid."));
853 if (!VALID_ELF_ABIVERSION (header->e_ident[EI_ABIVERSION]))
854 LOSE (0, N_("ELF file ABI version invalid."));
855 LOSE (0, N_("internal error"));
856 }
857
858 if (__builtin_expect (header->e_version, EV_CURRENT) != EV_CURRENT)
859 LOSE (0, N_("ELF file version does not match current one"));
860 if (! __builtin_expect (elf_machine_matches_host (header), 1))
861 LOSE (0, N_("ELF file machine architecture does not match"));
862 if (__builtin_expect (header->e_phentsize, sizeof (ElfW(Phdr)))
863 != sizeof (ElfW(Phdr)))
864 LOSE (0, N_("ELF file's phentsize not the expected size"));
865
866 #ifndef MAP_ANON
867 # define MAP_ANON 0
868 if (_dl_zerofd == -1)
869 {
870 _dl_zerofd = _dl_sysdep_open_zero_fill ();
871 if (_dl_zerofd == -1)
872 {
873 __close (fd);
874 _dl_signal_error (errno, NULL, N_("cannot open zero fill device"));
875 }
876 }
877 #endif
878
879 /* Enter the new object in the list of loaded objects. */
880 l = _dl_new_object (realname, name, l_type, loader);
881 if (__builtin_expect (! l, 0))
882 LOSE (ENOMEM, N_("cannot create shared object descriptor"));
883 l->l_opencount = 1;
884
885 /* Extract the remaining details we need from the ELF header
886 and then read in the program header table. */
887 l->l_entry = header->e_entry;
888 type = header->e_type;
889 l->l_phnum = header->e_phnum;
890
891 maplength = header->e_phnum * sizeof (ElfW(Phdr));
892 if (header->e_phoff + maplength <= readlength)
893 phdr = (void *) (readbuf + header->e_phoff);
894 else
895 {
896 phdr = alloca (maplength);
897 __lseek (fd, SEEK_SET, header->e_phoff);
898 if (__libc_read (fd, (void *) phdr, maplength) != maplength)
899 LOSE (errno, N_("cannot read file data"));
900 }
901
902 {
903 /* Scan the program header table, collecting its load commands. */
904 struct loadcmd
905 {
906 ElfW(Addr) mapstart, mapend, dataend, allocend;
907 off_t mapoff;
908 int prot;
909 } loadcmds[l->l_phnum], *c;
910 size_t nloadcmds = 0;
911
912 /* The struct is initialized to zero so this is not necessary:
913 l->l_ld = 0;
914 l->l_phdr = 0;
915 l->l_addr = 0; */
916 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
917 switch (ph->p_type)
918 {
919 /* These entries tell us where to find things once the file's
920 segments are mapped in. We record the addresses it says
921 verbatim, and later correct for the run-time load address. */
922 case PT_DYNAMIC:
923 l->l_ld = (void *) ph->p_vaddr;
924 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
925 break;
926 case PT_PHDR:
927 l->l_phdr = (void *) ph->p_vaddr;
928 break;
929
930 case PT_LOAD:
931 /* A load command tells us to map in part of the file.
932 We record the load commands and process them all later. */
933 if (ph->p_align % _dl_pagesize != 0)
934 LOSE (0, N_("ELF load command alignment not page-aligned"));
935 if ((ph->p_vaddr - ph->p_offset) % ph->p_align)
936 LOSE (0,
937 N_("ELF load command address/offset not properly aligned"));
938 {
939 struct loadcmd *c = &loadcmds[nloadcmds++];
940 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
941 c->mapend = ((ph->p_vaddr + ph->p_filesz + _dl_pagesize - 1)
942 & ~(_dl_pagesize - 1));
943 c->dataend = ph->p_vaddr + ph->p_filesz;
944 c->allocend = ph->p_vaddr + ph->p_memsz;
945 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
946
947 /* Optimize a common case. */
948 if ((PF_R | PF_W | PF_X) == 7
949 && (PROT_READ | PROT_WRITE | PROT_EXEC) == 7)
950 c->prot = _dl_pf_to_prot[ph->p_flags & (PF_R | PF_W | PF_X)];
951 else
952 {
953 c->prot = 0;
954 if (ph->p_flags & PF_R)
955 c->prot |= PROT_READ;
956 if (ph->p_flags & PF_W)
957 c->prot |= PROT_WRITE;
958 if (ph->p_flags & PF_X)
959 c->prot |= PROT_EXEC;
960 }
961 break;
962 }
963 }
964
965 /* Now process the load commands and map segments into memory. */
966 c = loadcmds;
967
968 /* Length of the sections to be loaded. */
969 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
970
971 if (type == ET_DYN || type == ET_REL)
972 {
973 /* This is a position-independent shared object. We can let the
974 kernel map it anywhere it likes, but we must have space for all
975 the segments in their specified positions relative to the first.
976 So we map the first segment without MAP_FIXED, but with its
977 extent increased to cover all the segments. Then we remove
978 access from excess portion, and there is known sufficient space
979 there to remap from the later segments.
980
981 As a refinement, sometimes we have an address that we would
982 prefer to map such objects at; but this is only a preference,
983 the OS can do whatever it likes. */
984 ElfW(Addr) mappref;
985 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
986 - MAP_BASE_ADDR (l));
987
988 /* Remember which part of the address space this object uses. */
989 l->l_map_start = (ElfW(Addr)) map_segment (mappref, maplength, c->prot,
990 0, c->mapoff);
991 l->l_map_end = l->l_map_start + maplength;
992 l->l_addr = l->l_map_start - c->mapstart;
993
994 /* Change protection on the excess portion to disallow all access;
995 the portions we do not remap later will be inaccessible as if
996 unallocated. Then jump into the normal segment-mapping loop to
997 handle the portion of the segment past the end of the file
998 mapping. */
999 __mprotect ((caddr_t) (l->l_addr + c->mapend),
1000 loadcmds[nloadcmds - 1].allocend - c->mapend,
1001 0);
1002
1003 goto postmap;
1004 }
1005 else
1006 {
1007 /* This object is loaded at a fixed address. This must never
1008 happen for objects loaded with dlopen(). */
1009 if (mode & __RTLD_DLOPEN)
1010 {
1011 LOSE (0, N_("cannot dynamically load executable"));
1012 }
1013
1014 /* Notify ELF_PREFERRED_ADDRESS that we have to load this one
1015 fixed. */
1016 ELF_FIXED_ADDRESS (loader, c->mapstart);
1017 }
1018
1019 /* Remember which part of the address space this object uses. */
1020 l->l_map_start = c->mapstart + l->l_addr;
1021 l->l_map_end = l->l_map_start + maplength;
1022
1023 while (c < &loadcmds[nloadcmds])
1024 {
1025 if (c->mapend > c->mapstart)
1026 /* Map the segment contents from the file. */
1027 map_segment (l->l_addr + c->mapstart, c->mapend - c->mapstart,
1028 c->prot, MAP_FIXED, c->mapoff);
1029
1030 postmap:
1031 if (l->l_phdr == 0
1032 && c->mapoff <= header->e_phoff
1033 && (c->mapend - c->mapstart + c->mapoff
1034 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
1035 /* Found the program header in this segment. */
1036 l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff);
1037
1038 if (c->allocend > c->dataend)
1039 {
1040 /* Extra zero pages should appear at the end of this segment,
1041 after the data mapped from the file. */
1042 ElfW(Addr) zero, zeroend, zeropage;
1043
1044 zero = l->l_addr + c->dataend;
1045 zeroend = l->l_addr + c->allocend;
1046 zeropage = (zero + _dl_pagesize - 1) & ~(_dl_pagesize - 1);
1047
1048 if (zeroend < zeropage)
1049 /* All the extra data is in the last page of the segment.
1050 We can just zero it. */
1051 zeropage = zeroend;
1052
1053 if (zeropage > zero)
1054 {
1055 /* Zero the final part of the last page of the segment. */
1056 if ((c->prot & PROT_WRITE) == 0)
1057 {
1058 /* Dag nab it. */
1059 if (__mprotect ((caddr_t) (zero & ~(_dl_pagesize - 1)),
1060 _dl_pagesize, c->prot|PROT_WRITE) < 0)
1061 LOSE (errno, N_("cannot change memory protections"));
1062 }
1063 memset ((void *) zero, 0, zeropage - zero);
1064 if ((c->prot & PROT_WRITE) == 0)
1065 __mprotect ((caddr_t) (zero & ~(_dl_pagesize - 1)),
1066 _dl_pagesize, c->prot);
1067 }
1068
1069 if (zeroend > zeropage)
1070 {
1071 /* Map the remaining zero pages in from the zero fill FD. */
1072 caddr_t mapat;
1073 mapat = __mmap ((caddr_t) zeropage, zeroend - zeropage,
1074 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
1075 ANONFD, 0);
1076 if (mapat == MAP_FAILED)
1077 LOSE (errno, N_("cannot map zero-fill pages"));
1078 }
1079 }
1080
1081 ++c;
1082 }
1083
1084 if (l->l_phdr == NULL)
1085 {
1086 /* The program header is not contained in any of the segmenst.
1087 We have to allocate memory ourself and copy it over from
1088 out temporary place. */
1089 ElfW(Phdr) *newp = (ElfW(Phdr) *) malloc (header->e_phnum
1090 * sizeof (ElfW(Phdr)));
1091 if (newp == NULL)
1092 LOSE (ENOMEM, N_("cannot allocate memory for program header"));
1093
1094 l->l_phdr = memcpy (newp, phdr,
1095 (header->e_phnum * sizeof (ElfW(Phdr))));
1096 l->l_phdr_allocated = 1;
1097 }
1098 else
1099 /* Adjust the PT_PHDR value by the runtime load address. */
1100 (ElfW(Addr)) l->l_phdr += l->l_addr;
1101 }
1102
1103 /* We are done mapping in the file. We no longer need the descriptor. */
1104 __close (fd);
1105
1106 if (l->l_type == lt_library && type == ET_EXEC)
1107 l->l_type = lt_executable;
1108
1109 if (l->l_ld == 0)
1110 {
1111 if (type == ET_DYN)
1112 LOSE (0, N_("object file has no dynamic section"));
1113 }
1114 else
1115 (ElfW(Addr)) l->l_ld += l->l_addr;
1116
1117 l->l_entry += l->l_addr;
1118
1119 if (__builtin_expect (_dl_debug_files, 0))
1120 {
1121 const size_t nibbles = sizeof (void *) * 2;
1122 char buf1[nibbles + 1];
1123 char buf2[nibbles + 1];
1124 char buf3[nibbles + 1];
1125
1126 buf1[nibbles] = '\0';
1127 buf2[nibbles] = '\0';
1128 buf3[nibbles] = '\0';
1129
1130 memset (buf1, '0', nibbles);
1131 memset (buf2, '0', nibbles);
1132 memset (buf3, '0', nibbles);
1133 _itoa_word ((unsigned long int) l->l_ld, &buf1[nibbles], 16, 0);
1134 _itoa_word ((unsigned long int) l->l_addr, &buf2[nibbles], 16, 0);
1135 _itoa_word (maplength, &buf3[nibbles], 16, 0);
1136
1137 _dl_debug_message (1, " dynamic: 0x", buf1, " base: 0x", buf2,
1138 " size: 0x", buf3, "\n", NULL);
1139 memset (buf1, '0', nibbles);
1140 memset (buf2, '0', nibbles);
1141 memset (buf3, ' ', nibbles);
1142 _itoa_word ((unsigned long int) l->l_entry, &buf1[nibbles], 16, 0);
1143 _itoa_word ((unsigned long int) l->l_phdr, &buf2[nibbles], 16, 0);
1144 _itoa_word (l->l_phnum, &buf3[nibbles], 10, 0);
1145 _dl_debug_message (1, " entry: 0x", buf1, " phdr: 0x", buf2,
1146 " phnum: ", buf3, "\n\n", NULL);
1147 }
1148
1149 elf_get_dynamic_info (l);
1150
1151 /* Make sure we are dlopen()ing an object which has the DF_1_NOOPEN
1152 flag set. */
1153 if (__builtin_expect (l->l_flags_1 & DF_1_NOOPEN, 0)
1154 && (mode & __RTLD_DLOPEN))
1155 {
1156 /* Remove from the module list. */
1157 assert (l->l_next == NULL);
1158 #ifndef SHARED
1159 if (l->l_prev == NULL)
1160 /* No other module loaded. */
1161 _dl_loaded = NULL;
1162 else
1163 #endif
1164 l->l_prev->l_next = NULL;
1165 --_dl_nloaded;
1166
1167 /* We are not supposed to load this object. Free all resources. */
1168 __munmap ((void *) l->l_map_start, l->l_map_end - l->l_map_start);
1169
1170 free (l->l_libname);
1171
1172 if (l->l_phdr_allocated)
1173 free ((void *) l->l_phdr);
1174
1175 free (l);
1176
1177 _dl_signal_error (0, name, N_("shared object cannot be dlopen()ed"));
1178 }
1179
1180 if (l->l_info[DT_HASH])
1181 _dl_setup_hash (l);
1182
1183 /* If this object has DT_SYMBOLIC set modify now its scope. We don't
1184 have to do this for the main map. */
1185 if (__builtin_expect (l->l_info[DT_SYMBOLIC] != NULL, 0)
1186 && &l->l_searchlist != l->l_scope[0])
1187 {
1188 /* Create an appropriate searchlist. It contains only this map.
1189
1190 XXX This is the definition of DT_SYMBOLIC in SysVr4. The old
1191 GNU ld.so implementation had a different interpretation which
1192 is more reasonable. We are prepared to add this possibility
1193 back as part of a GNU extension of the ELF format. */
1194 l->l_symbolic_searchlist.r_list =
1195 (struct link_map **) malloc (sizeof (struct link_map *));
1196
1197 if (l->l_symbolic_searchlist.r_list == NULL)
1198 LOSE (ENOMEM, N_("cannot create searchlist"));
1199
1200 l->l_symbolic_searchlist.r_list[0] = l;
1201 l->l_symbolic_searchlist.r_nlist = 1;
1202 l->l_symbolic_searchlist.r_duplist = l->l_symbolic_searchlist.r_list;
1203 l->l_symbolic_searchlist.r_nduplist = 1;
1204
1205 /* Now move the existing entries one back. */
1206 memmove (&l->l_scope[1], &l->l_scope[0],
1207 sizeof (l->l_scope) - sizeof (l->l_scope[0]));
1208
1209 /* Now add the new entry. */
1210 l->l_scope[0] = &l->l_symbolic_searchlist;
1211 }
1212
1213 /* Finally the file information. */
1214 l->l_dev = st.st_dev;
1215 l->l_ino = st.st_ino;
1216
1217 return l;
1218 }
1219 \f
1220 /* Print search path. */
1221 static void
1222 print_search_path (struct r_search_path_elem **list,
1223 const char *what, const char *name)
1224 {
1225 char buf[max_dirnamelen + max_capstrlen];
1226 int first = 1;
1227
1228 _dl_debug_message (1, " search path=", NULL);
1229
1230 while (*list != NULL && (*list)->what == what) /* Yes, ==. */
1231 {
1232 char *endp = __mempcpy (buf, (*list)->dirname, (*list)->dirnamelen);
1233 size_t cnt;
1234
1235 for (cnt = 0; cnt < ncapstr; ++cnt)
1236 if ((*list)->status[cnt] != nonexisting)
1237 {
1238 char *cp = __mempcpy (endp, capstr[cnt].str, capstr[cnt].len);
1239 if (cp == buf || (cp == buf + 1 && buf[0] == '/'))
1240 cp[0] = '\0';
1241 else
1242 cp[-1] = '\0';
1243 _dl_debug_message (0, first ? "" : ":", buf, NULL);
1244 first = 0;
1245 }
1246
1247 ++list;
1248 }
1249
1250 if (name != NULL)
1251 _dl_debug_message (0, "\t\t(", what, " from file ",
1252 name[0] ? name : _dl_argv[0], ")\n", NULL);
1253 else
1254 _dl_debug_message (0, "\t\t(", what, ")\n", NULL);
1255 }
1256 \f
1257 /* Try to open NAME in one of the directories in *DIRSP.
1258 Return the fd, or -1. If successful, fill in *REALNAME
1259 with the malloc'd full directory name. If it turns out
1260 that none of the directories in *DIRSP exists, *DIRSP is
1261 replaced with (void *) -1, and the old value is free()d
1262 if MAY_FREE_DIRS is true. */
1263
1264 static int
1265 open_path (const char *name, size_t namelen, int preloaded,
1266 struct r_search_path_struct *sps, char **realname)
1267 {
1268 struct r_search_path_elem **dirs = sps->dirs;
1269 char *buf;
1270 int fd = -1;
1271 const char *current_what = NULL;
1272 int any = 0;
1273
1274 buf = alloca (max_dirnamelen + max_capstrlen + namelen);
1275 do
1276 {
1277 struct r_search_path_elem *this_dir = *dirs;
1278 size_t buflen = 0;
1279 size_t cnt;
1280 char *edp;
1281
1282 /* If we are debugging the search for libraries print the path
1283 now if it hasn't happened now. */
1284 if (__builtin_expect (_dl_debug_libs, 0)
1285 && current_what != this_dir->what)
1286 {
1287 current_what = this_dir->what;
1288 print_search_path (dirs, current_what, this_dir->where);
1289 }
1290
1291 edp = (char *) __mempcpy (buf, this_dir->dirname, this_dir->dirnamelen);
1292 for (cnt = 0; fd == -1 && cnt < ncapstr; ++cnt)
1293 {
1294 /* Skip this directory if we know it does not exist. */
1295 if (this_dir->status[cnt] == nonexisting)
1296 continue;
1297
1298 buflen =
1299 ((char *) __mempcpy (__mempcpy (edp,
1300 capstr[cnt].str, capstr[cnt].len),
1301 name, namelen)
1302 - buf);
1303
1304 /* Print name we try if this is wanted. */
1305 if (__builtin_expect (_dl_debug_libs, 0))
1306 _dl_debug_message (1, " trying file=", buf, "\n", NULL);
1307
1308 fd = __open (buf, O_RDONLY);
1309 if (this_dir->status[cnt] == unknown)
1310 {
1311 if (fd != -1)
1312 this_dir->status[cnt] = existing;
1313 else
1314 {
1315 /* We failed to open machine dependent library. Let's
1316 test whether there is any directory at all. */
1317 struct stat64 st;
1318
1319 buf[buflen - namelen - 1] = '\0';
1320
1321 if (__xstat64 (_STAT_VER, buf, &st) != 0
1322 || ! S_ISDIR (st.st_mode))
1323 /* The directory does not exist or it is no directory. */
1324 this_dir->status[cnt] = nonexisting;
1325 else
1326 this_dir->status[cnt] = existing;
1327 }
1328 }
1329
1330 /* Remember whether we found any existing directory. */
1331 any |= this_dir->status[cnt] == existing;
1332
1333 if (fd != -1 && preloaded && __libc_enable_secure)
1334 {
1335 /* This is an extra security effort to make sure nobody can
1336 preload broken shared objects which are in the trusted
1337 directories and so exploit the bugs. */
1338 struct stat64 st;
1339
1340 if (__fxstat64 (_STAT_VER, fd, &st) != 0
1341 || (st.st_mode & S_ISUID) == 0)
1342 {
1343 /* The shared object cannot be tested for being SUID
1344 or this bit is not set. In this case we must not
1345 use this object. */
1346 __close (fd);
1347 fd = -1;
1348 /* We simply ignore the file, signal this by setting
1349 the error value which would have been set by `open'. */
1350 errno = ENOENT;
1351 }
1352 }
1353 }
1354
1355 if (fd != -1)
1356 {
1357 *realname = malloc (buflen);
1358 if (*realname != NULL)
1359 {
1360 memcpy (*realname, buf, buflen);
1361 return fd;
1362 }
1363 else
1364 {
1365 /* No memory for the name, we certainly won't be able
1366 to load and link it. */
1367 __close (fd);
1368 return -1;
1369 }
1370 }
1371 if (errno != ENOENT && errno != EACCES)
1372 /* The file exists and is readable, but something went wrong. */
1373 return -1;
1374 }
1375 while (*++dirs != NULL);
1376
1377 /* Remove the whole path if none of the directories exists. */
1378 if (! any)
1379 {
1380 /* Paths which were allocated using the minimal malloc() in ld.so
1381 must not be freed using the general free() in libc. */
1382 if (sps->malloced)
1383 free (sps->dirs);
1384 sps->dirs = (void *) -1;
1385 }
1386
1387 return -1;
1388 }
1389
1390 /* Map in the shared object file NAME. */
1391
1392 struct link_map *
1393 internal_function
1394 _dl_map_object (struct link_map *loader, const char *name, int preloaded,
1395 int type, int trace_mode, int mode)
1396 {
1397 int fd;
1398 char *realname;
1399 char *name_copy;
1400 struct link_map *l;
1401
1402 /* Look for this name among those already loaded. */
1403 for (l = _dl_loaded; l; l = l->l_next)
1404 {
1405 unsigned int i;
1406
1407 /* If the requested name matches the soname of a loaded object,
1408 use that object. Elide this check for names that have not
1409 yet been opened. */
1410 if (l->l_opencount <= 0)
1411 continue;
1412 if (!_dl_name_match_p (name, l))
1413 {
1414 const char *soname;
1415
1416 if (l->l_info[DT_SONAME] == NULL)
1417 continue;
1418
1419 soname = ((const char *) D_PTR (l, l_info[DT_STRTAB])
1420 + l->l_info[DT_SONAME]->d_un.d_val);
1421 if (strcmp (name, soname) != 0)
1422 continue;
1423
1424 /* We have a match on a new name -- cache it. */
1425 add_name_to_object (l, soname);
1426 }
1427
1428 /* We have a match -- bump the reference count and return it. */
1429 if (l->l_initfini != NULL)
1430 for (i = 1; l->l_initfini[i] != NULL; ++i)
1431 ++l->l_initfini[i]->l_opencount;
1432 ++l->l_opencount;
1433 return l;
1434 }
1435
1436 /* Display information if we are debugging. */
1437 if (__builtin_expect (_dl_debug_files, 0) && loader != NULL)
1438 _dl_debug_message (1, "\nfile=", name, "; needed by ",
1439 loader->l_name[0] ? loader->l_name : _dl_argv[0],
1440 "\n", NULL);
1441
1442 if (strchr (name, '/') == NULL)
1443 {
1444 /* Search for NAME in several places. */
1445
1446 size_t namelen = strlen (name) + 1;
1447
1448 if (__builtin_expect (_dl_debug_libs, 0))
1449 _dl_debug_message (1, "find library=", name, "; searching\n", NULL);
1450
1451 fd = -1;
1452
1453 /* When the object has the RUNPATH information we don't use any
1454 RPATHs. */
1455 if (loader == NULL || loader->l_info[DT_RUNPATH] == NULL)
1456 {
1457 /* First try the DT_RPATH of the dependent object that caused NAME
1458 to be loaded. Then that object's dependent, and on up. */
1459 for (l = loader; fd == -1 && l; l = l->l_loader)
1460 {
1461 if (l->l_rpath_dirs.dirs == NULL)
1462 {
1463 if (l->l_info[DT_RPATH] == NULL)
1464 /* There is no path. */
1465 l->l_rpath_dirs.dirs = (void *) -1;
1466 else
1467 {
1468 /* Make sure the cache information is available. */
1469 size_t ptrval = (D_PTR (l, l_info[DT_STRTAB])
1470 + l->l_info[DT_RPATH]->d_un.d_val);
1471 decompose_rpath (&l->l_rpath_dirs,
1472 (const char *) ptrval, l, "RPATH");
1473
1474 if (l->l_rpath_dirs.dirs != (void *) -1)
1475 fd = open_path (name, namelen, preloaded,
1476 &l->l_rpath_dirs, &realname);
1477 }
1478 }
1479 else if (l->l_rpath_dirs.dirs != (void *) -1)
1480 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1481 &realname);
1482 }
1483
1484 /* If dynamically linked, try the DT_RPATH of the executable
1485 itself. */
1486 l = _dl_loaded;
1487 if (fd == -1 && l && l->l_type != lt_loaded && l != loader
1488 && l->l_rpath_dirs.dirs != (void *) -1)
1489 fd = open_path (name, namelen, preloaded, &l->l_rpath_dirs,
1490 &realname);
1491 }
1492
1493 /* Try the LD_LIBRARY_PATH environment variable. */
1494 if (fd == -1 && env_path_list.dirs != (void *) -1)
1495 fd = open_path (name, namelen, preloaded, &env_path_list,
1496 &realname);
1497
1498 /* Look at the RUNPATH informaiton for this binary. */
1499 if (loader != NULL && loader->l_runpath_dirs.dirs != (void *) -1)
1500 {
1501 if (loader->l_runpath_dirs.dirs == NULL)
1502 {
1503 if (loader->l_info[DT_RUNPATH] == NULL)
1504 /* No RUNPATH. */
1505 loader->l_runpath_dirs.dirs = (void *) -1;
1506 else
1507 {
1508 /* Make sure the cache information is available. */
1509 size_t ptrval = (D_PTR (loader, l_info[DT_STRTAB])
1510 + loader->l_info[DT_RUNPATH]->d_un.d_val);
1511 decompose_rpath (&loader->l_runpath_dirs,
1512 (const char *) ptrval, loader, "RUNPATH");
1513
1514 if (loader->l_runpath_dirs.dirs != (void *) -1)
1515 fd = open_path (name, namelen, preloaded,
1516 &loader->l_runpath_dirs, &realname);
1517 }
1518 }
1519 else if (loader->l_runpath_dirs.dirs != (void *) -1)
1520 fd = open_path (name, namelen, preloaded,
1521 &loader->l_runpath_dirs, &realname);
1522 }
1523
1524 if (fd == -1)
1525 {
1526 /* Check the list of libraries in the file /etc/ld.so.cache,
1527 for compatibility with Linux's ldconfig program. */
1528 extern const char *_dl_load_cache_lookup (const char *name);
1529 const char *cached = _dl_load_cache_lookup (name);
1530
1531 #ifdef SHARED
1532 l = loader ?: _dl_loaded;
1533 #else
1534 l = loader;
1535 #endif
1536
1537 if (cached)
1538 {
1539 /* If the loader has the DF_1_NODEFLIB flag set we must not
1540 use a cache entry from any of these directories. */
1541 if (l && __builtin_expect (l->l_flags_1 & DF_1_NODEFLIB, 0))
1542 {
1543 const char *dirp = system_dirs;
1544 int cnt = 0;
1545
1546 do
1547 {
1548 if (memcmp (cached, dirp, system_dirs_len[cnt]) == 0)
1549 {
1550 /* The prefix matches. Don't use the entry. */
1551 cached = NULL;
1552 break;
1553 }
1554
1555 dirp += system_dirs_len[cnt] + 1;
1556 ++cnt;
1557 }
1558 while (cnt < nsystem_dirs_len);
1559 }
1560
1561 if (cached)
1562 {
1563 fd = __open (cached, O_RDONLY);
1564 if (fd != -1)
1565 {
1566 realname = local_strdup (cached);
1567 if (realname == NULL)
1568 {
1569 __close (fd);
1570 fd = -1;
1571 }
1572 }
1573 }
1574 }
1575 }
1576
1577 /* Finally, try the default path. */
1578 if (fd == -1
1579 && (l == NULL ||
1580 __builtin_expect (!(l->l_flags_1 & DF_1_NODEFLIB), 1))
1581 && rtld_search_dirs.dirs != (void *) -1)
1582 fd = open_path (name, namelen, preloaded, &rtld_search_dirs,
1583 &realname);
1584
1585 /* Add another newline when we a tracing the library loading. */
1586 if (__builtin_expect (_dl_debug_libs, 0))
1587 _dl_debug_message (1, "\n", NULL);
1588 }
1589 else
1590 {
1591 /* The path may contain dynamic string tokens. */
1592 realname = (loader
1593 ? expand_dynamic_string_token (loader, name)
1594 : local_strdup (name));
1595 if (realname == NULL)
1596 fd = -1;
1597 else
1598 {
1599 fd = __open (realname, O_RDONLY);
1600 if (fd == -1)
1601 free (realname);
1602 }
1603 }
1604
1605 if (fd == -1)
1606 {
1607 if (trace_mode)
1608 {
1609 /* We haven't found an appropriate library. But since we
1610 are only interested in the list of libraries this isn't
1611 so severe. Fake an entry with all the information we
1612 have. */
1613 static const Elf_Symndx dummy_bucket = STN_UNDEF;
1614
1615 /* Enter the new object in the list of loaded objects. */
1616 if ((name_copy = local_strdup (name)) == NULL
1617 || (l = _dl_new_object (name_copy, name, type, loader)) == NULL)
1618 _dl_signal_error (ENOMEM, name,
1619 N_("cannot create shared object descriptor"));
1620 /* We use an opencount of 0 as a sign for the faked entry.
1621 Since the descriptor is initialized with zero we do not
1622 have do this here.
1623 l->l_opencount = 0;
1624 l->l_reserved = 0; */
1625 l->l_buckets = &dummy_bucket;
1626 l->l_nbuckets = 1;
1627 l->l_relocated = 1;
1628
1629 return l;
1630 }
1631 else
1632 _dl_signal_error (errno, name, N_("cannot open shared object file"));
1633 }
1634
1635 return _dl_map_object_from_fd (name, fd, realname, loader, type, mode);
1636 }