OSDN Git Service

some fixes by anemo in Bug 9 to play nicely with 32 or 64 bit hosts
[uclinux-h8/uClibc.git] / ldso / ldso / dl-elf.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * This file contains the helper routines to load an ELF shared
4  * library into memory and add the symbol table info to the chain.
5  *
6  * Copyright (C) 2000-2004 by Erik Andersen <andersen@codepoet.org>
7  * Copyright (c) 1994-2000 Eric Youngdale, Peter MacDonald,
8  *                              David Engel, Hongjiu Lu and Mitch D'Souza
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. The name of the above contributors may not be
16  *    used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32
33 #include "ldso.h"
34
35 #ifdef __LDSO_CACHE_SUPPORT__
36
37 static caddr_t _dl_cache_addr = NULL;
38 static size_t _dl_cache_size = 0;
39
40 int _dl_map_cache(void)
41 {
42         int fd;
43         struct stat st;
44         header_t *header;
45         libentry_t *libent;
46         int i, strtabsize;
47
48         if (_dl_cache_addr == (caddr_t) - 1)
49                 return -1;
50         else if (_dl_cache_addr != NULL)
51                 return 0;
52
53         if (_dl_stat(LDSO_CACHE, &st)
54             || (fd = _dl_open(LDSO_CACHE, O_RDONLY, 0)) < 0) {
55                 _dl_cache_addr = (caddr_t) - 1; /* so we won't try again */
56                 return -1;
57         }
58
59         _dl_cache_size = st.st_size;
60         _dl_cache_addr = (caddr_t) _dl_mmap(0, _dl_cache_size, PROT_READ, MAP_SHARED, fd, 0);
61         _dl_close(fd);
62         if (_dl_mmap_check_error(_dl_cache_addr)) {
63                 _dl_dprintf(2, "%s: can't map cache '%s'\n",
64                                 _dl_progname, LDSO_CACHE);
65                 return -1;
66         }
67
68         header = (header_t *) _dl_cache_addr;
69
70         if (_dl_cache_size < sizeof(header_t) ||
71                         _dl_memcmp(header->magic, LDSO_CACHE_MAGIC, LDSO_CACHE_MAGIC_LEN)
72                         || _dl_memcmp(header->version, LDSO_CACHE_VER, LDSO_CACHE_VER_LEN)
73                         || _dl_cache_size <
74                         (sizeof(header_t) + header->nlibs * sizeof(libentry_t))
75                         || _dl_cache_addr[_dl_cache_size - 1] != '\0')
76         {
77                 _dl_dprintf(2, "%s: cache '%s' is corrupt\n", _dl_progname,
78                                 LDSO_CACHE);
79                 goto fail;
80         }
81
82         strtabsize = _dl_cache_size - sizeof(header_t) -
83                 header->nlibs * sizeof(libentry_t);
84         libent = (libentry_t *) & header[1];
85
86         for (i = 0; i < header->nlibs; i++) {
87                 if (libent[i].sooffset >= strtabsize ||
88                                 libent[i].liboffset >= strtabsize)
89                 {
90                         _dl_dprintf(2, "%s: cache '%s' is corrupt\n", _dl_progname, LDSO_CACHE);
91                         goto fail;
92                 }
93         }
94
95         return 0;
96
97 fail:
98         _dl_munmap(_dl_cache_addr, _dl_cache_size);
99         _dl_cache_addr = (caddr_t) - 1;
100         return -1;
101 }
102
103 int _dl_unmap_cache(void)
104 {
105         if (_dl_cache_addr == NULL || _dl_cache_addr == (caddr_t) - 1)
106                 return -1;
107
108 #if 1
109         _dl_munmap(_dl_cache_addr, _dl_cache_size);
110         _dl_cache_addr = NULL;
111 #endif
112
113         return 0;
114 }
115 #endif
116
117
118 void 
119 _dl_protect_relro (struct elf_resolve *l)
120 {
121         ElfW(Addr) start = ((l->loadaddr + l->relro_addr)
122                             & ~(_dl_pagesize - 1));
123         ElfW(Addr) end = ((l->loadaddr + l->relro_addr + l->relro_size)
124                           & ~(_dl_pagesize - 1));
125         _dl_if_debug_dprint("RELRO protecting %s:  start:%x, end:%x\n", l->libname, start, end);
126         if (start != end &&
127             _dl_mprotect ((void *) start, end - start, PROT_READ) < 0) {
128                 _dl_dprintf(2, "%s: cannot apply additional memory protection after relocation", l->libname);
129                 _dl_exit(0);
130         }
131 }
132
133 /* This function's behavior must exactly match that
134  * in uClibc/ldso/util/ldd.c */
135 static struct elf_resolve *
136 search_for_named_library(const char *name, int secure, const char *path_list,
137         struct dyn_elf **rpnt)
138 {
139         char *path, *path_n;
140         char mylibname[2050];
141         struct elf_resolve *tpnt;
142         int done = 0;
143
144         if (path_list==NULL)
145                 return NULL;
146
147         /* We need a writable copy of this string */
148         path = _dl_strdup(path_list);
149         if (!path) {
150                 _dl_dprintf(2, "Out of memory!\n");
151                 _dl_exit(0);
152         }
153
154         /* Unlike ldd.c, don't bother to eliminate double //s */
155
156         /* Replace colons with zeros in path_list */
157         /* : at the beginning or end of path maps to CWD */
158         /* :: anywhere maps CWD */
159         /* "" maps to CWD */ 
160         path_n = path;
161         do {
162                 if (*path == 0) {
163                         *path = ':';
164                         done = 1;
165                 }
166                 if (*path == ':') {
167                         *path = 0;
168                         if (*path_n)
169                                 _dl_strcpy(mylibname, path_n);
170                         else
171                                 _dl_strcpy(mylibname, "."); /* Assume current dir if empty path */
172                         _dl_strcat(mylibname, "/");
173                         _dl_strcat(mylibname, name);
174                         if ((tpnt = _dl_load_elf_shared_library(secure, rpnt, mylibname)) != NULL)
175                                 return tpnt;
176                         path_n = path+1;
177                 }
178                 path++;
179         } while (!done);
180         return NULL;
181 }
182
183 /* Check if the named library is already loaded... */
184 struct elf_resolve *_dl_check_if_named_library_is_loaded(const char *full_libname,
185                 int trace_loaded_objects)
186 {
187         const char *pnt, *pnt1;
188         struct elf_resolve *tpnt1;
189         const char *libname, *libname2;
190         static const char libc[] = "libc.so.";
191         static const char aborted_wrong_lib[] = "%s: aborted attempt to load %s!\n";
192
193         pnt = libname = full_libname;
194
195         _dl_if_debug_dprint("Checking if '%s' is already loaded\n", full_libname);
196         /* quick hack to ensure mylibname buffer doesn't overflow.  don't
197            allow full_libname or any directory to be longer than 1024. */
198         if (_dl_strlen(full_libname) > 1024)
199                 return NULL;
200
201         /* Skip over any initial initial './' and '/' stuff to
202          * get the short form libname with no path garbage */
203         pnt1 = _dl_strrchr(pnt, '/');
204         if (pnt1) {
205                 libname = pnt1 + 1;
206         }
207
208         /* Make sure they are not trying to load the wrong C library!
209          * This sometimes happens esp with shared libraries when the
210          * library path is somehow wrong! */
211 #define isdigit(c)  (c >= '0' && c <= '9')
212         if ((_dl_strncmp(libname, libc, 8) == 0) &&  _dl_strlen(libname) >=8 &&
213                         isdigit(libname[8]))
214         {
215                 /* Abort attempts to load glibc, libc5, etc */
216                 if ( libname[8]!='0') {
217                         if (!trace_loaded_objects) {
218                                 _dl_dprintf(2, aborted_wrong_lib, libname, _dl_progname);
219                                 _dl_exit(1);
220                         }
221                         return NULL;
222                 }
223         }
224
225         /* Critical step!  Weed out duplicates early to avoid
226          * function aliasing, which wastes memory, and causes
227          * really bad things to happen with weaks and globals. */
228         for (tpnt1 = _dl_loaded_modules; tpnt1; tpnt1 = tpnt1->next) {
229
230                 /* Skip over any initial initial './' and '/' stuff to
231                  * get the short form libname with no path garbage */
232                 libname2 = tpnt1->libname;
233                 pnt1 = _dl_strrchr(libname2, '/');
234                 if (pnt1) {
235                         libname2 = pnt1 + 1;
236                 }
237
238                 if (_dl_strcmp(libname2, libname) == 0) {
239                         /* Well, that was certainly easy */
240                         return tpnt1;
241                 }
242         }
243
244         return NULL;
245 }
246
247
248 /* Used to return error codes back to dlopen et. al.  */
249 unsigned long _dl_error_number;
250 unsigned long _dl_internal_error_number;
251
252 struct elf_resolve *_dl_load_shared_library(int secure, struct dyn_elf **rpnt,
253         struct elf_resolve *tpnt, char *full_libname, int __attribute__((unused)) trace_loaded_objects)
254 {
255         char *pnt;
256         struct elf_resolve *tpnt1;
257         char *libname;
258
259         _dl_internal_error_number = 0;
260         libname = full_libname;
261
262         /* quick hack to ensure mylibname buffer doesn't overflow.  don't
263            allow full_libname or any directory to be longer than 1024. */
264         if (_dl_strlen(full_libname) > 1024)
265                 goto goof;
266
267         /* Skip over any initial initial './' and '/' stuff to
268          * get the short form libname with no path garbage */
269         pnt = _dl_strrchr(libname, '/');
270         if (pnt) {
271                 libname = pnt + 1;
272         }
273
274         /* Critical step!  Weed out duplicates early to avoid
275          * function aliasing, which wastes memory, and causes
276          * really bad things to happen with weaks and globals. */
277         if ((tpnt1=_dl_check_if_named_library_is_loaded(libname, trace_loaded_objects))!=NULL) {
278                 tpnt1->usage_count++;
279                 return tpnt1;
280         }
281
282         _dl_if_debug_dprint("\tfind library='%s'; searching\n", libname);
283         /* If the filename has any '/', try it straight and leave it at that.
284            For IBCS2 compatibility under linux, we substitute the string
285            /usr/i486-sysv4/lib for /usr/lib in library names. */
286
287         if (libname != full_libname) {
288                 _dl_if_debug_dprint("\ttrying file='%s'\n", full_libname);
289                 tpnt1 = _dl_load_elf_shared_library(secure, rpnt, full_libname);
290                 if (tpnt1) {
291                         return tpnt1;
292                 }
293                 //goto goof;
294         }
295
296         /*
297          * The ABI specifies that RPATH is searched before LD_LIBRARY_PATH or
298          * the default path of /usr/lib.  Check in rpath directories.
299          */
300 #ifdef __LDSO_RUNPATH__
301         pnt = (tpnt ? (char *) tpnt->dynamic_info[DT_RPATH] : NULL);
302         if (pnt) {
303                 pnt += (unsigned long) tpnt->dynamic_info[DT_STRTAB];
304                 _dl_if_debug_dprint("\tsearching RPATH='%s'\n", pnt);
305                 if ((tpnt1 = search_for_named_library(libname, secure, pnt, rpnt)) != NULL)
306                         return tpnt1;
307         }
308 #endif
309
310         /* Check in LD_{ELF_}LIBRARY_PATH, if specified and allowed */
311         if (_dl_library_path) {
312                 _dl_if_debug_dprint("\tsearching LD_LIBRARY_PATH='%s'\n", _dl_library_path);
313                 if ((tpnt1 = search_for_named_library(libname, secure, _dl_library_path, rpnt)) != NULL)
314                 {
315                         return tpnt1;
316                 }
317         }
318
319         /*
320          * The ABI specifies that RUNPATH is searched after LD_LIBRARY_PATH.
321          */
322 #ifdef __LDSO_RUNPATH__
323         pnt = (tpnt ? (char *)tpnt->dynamic_info[DT_RUNPATH] : NULL);
324         if (pnt) {
325                 pnt += (unsigned long) tpnt->dynamic_info[DT_STRTAB];
326                 _dl_if_debug_dprint("\tsearching RUNPATH='%s'\n", pnt);
327                 if ((tpnt1 = search_for_named_library(libname, secure, pnt, rpnt)) != NULL)
328                         return tpnt1;
329         }
330 #endif
331
332         /*
333          * Where should the cache be searched?  There is no such concept in the
334          * ABI, so we have some flexibility here.  For now, search it before
335          * the hard coded paths that follow (i.e before /lib and /usr/lib).
336          */
337 #ifdef __LDSO_CACHE_SUPPORT__
338         if (_dl_cache_addr != NULL && _dl_cache_addr != (caddr_t) - 1) {
339                 int i;
340                 header_t *header = (header_t *) _dl_cache_addr;
341                 libentry_t *libent = (libentry_t *) & header[1];
342                 char *strs = (char *) &libent[header->nlibs];
343
344                 _dl_if_debug_dprint("\tsearching cache='%s'\n", LDSO_CACHE);
345                 for (i = 0; i < header->nlibs; i++) {
346                         if ((libent[i].flags == LIB_ELF ||
347                                                 libent[i].flags == LIB_ELF_LIBC0 ||
348                                                 libent[i].flags == LIB_ELF_LIBC5) &&
349                                         _dl_strcmp(libname, strs + libent[i].sooffset) == 0 &&
350                                         (tpnt1 = _dl_load_elf_shared_library(secure,
351                                                                                                                  rpnt, strs + libent[i].liboffset)))
352                                 return tpnt1;
353                 }
354         }
355 #endif
356
357         /* Look for libraries wherever the shared library loader
358          * was installed */
359         _dl_if_debug_dprint("\tsearching ldso dir='%s'\n", _dl_ldsopath);
360         if ((tpnt1 = search_for_named_library(libname, secure, _dl_ldsopath, rpnt)) != NULL)
361         {
362                 return tpnt1;
363         }
364
365
366         /* Lastly, search the standard list of paths for the library.
367            This list must exactly match the list in uClibc/ldso/util/ldd.c */
368         _dl_if_debug_dprint("\tsearching full lib path list\n");
369         if ((tpnt1 = search_for_named_library(libname, secure,
370                                         UCLIBC_RUNTIME_PREFIX "lib:"
371                                         UCLIBC_RUNTIME_PREFIX "usr/lib"
372 #ifndef __LDSO_CACHE_SUPPORT__
373                                         ":" UCLIBC_RUNTIME_PREFIX "usr/X11R6/lib"
374 #endif
375                                         , rpnt)
376                 ) != NULL)
377         {
378                 return tpnt1;
379         }
380
381 goof:
382         /* Well, we shot our wad on that one.  All we can do now is punt */
383         if (_dl_internal_error_number)
384                 _dl_error_number = _dl_internal_error_number;
385         else
386                 _dl_error_number = LD_ERROR_NOFILE;
387         _dl_if_debug_dprint("Bummer: could not find '%s'!\n", libname);
388         return NULL;
389 }
390
391
392 /*
393  * Read one ELF library into memory, mmap it into the correct locations and
394  * add the symbol info to the symbol chain.  Perform any relocations that
395  * are required.
396  */
397
398 struct elf_resolve *_dl_load_elf_shared_library(int secure,
399         struct dyn_elf **rpnt, char *libname)
400 {
401         ElfW(Ehdr) *epnt;
402         unsigned long dynamic_addr = 0;
403         ElfW(Dyn) *dpnt;
404         struct elf_resolve *tpnt;
405         ElfW(Phdr) *ppnt;
406         char *status, *header;
407         unsigned long dynamic_info[DYNAMIC_SIZE];
408         unsigned long *lpnt;
409         unsigned long libaddr;
410         unsigned long minvma = 0xffffffff, maxvma = 0;
411         int i, flags, piclib, infile;
412         ElfW(Addr) relro_addr = 0;
413         size_t relro_size = 0;
414
415         /* If this file is already loaded, skip this step */
416         tpnt = _dl_check_hashed_files(libname);
417         if (tpnt) {
418                 if (*rpnt) {
419                         (*rpnt)->next = (struct dyn_elf *) _dl_malloc(sizeof(struct dyn_elf));
420                         _dl_memset((*rpnt)->next, 0, sizeof(struct dyn_elf));
421                         (*rpnt)->next->prev = (*rpnt);
422                         *rpnt = (*rpnt)->next;
423                         (*rpnt)->dyn = tpnt;
424                         tpnt->symbol_scope = _dl_symbol_tables;
425                 }
426                 tpnt->usage_count++;
427                 tpnt->libtype = elf_lib;
428                 _dl_if_debug_dprint("file='%s';  already loaded\n", libname);
429                 return tpnt;
430         }
431
432         /* If we are in secure mode (i.e. a setu/gid binary using LD_PRELOAD),
433            we don't load the library if it isn't setuid. */
434
435         if (secure) {
436                 struct stat st;
437
438                 if (_dl_stat(libname, &st) || !(st.st_mode & S_ISUID))
439                         return NULL;
440         }
441
442         libaddr = 0;
443         infile = _dl_open(libname, O_RDONLY, 0);
444         if (infile < 0) {
445 #if 0
446                 /*
447                  * NO!  When we open shared libraries we may search several paths.
448                  * it is inappropriate to generate an error here.
449                  */
450                 _dl_dprintf(2, "%s: can't open '%s'\n", _dl_progname, libname);
451 #endif
452                 _dl_internal_error_number = LD_ERROR_NOFILE;
453                 return NULL;
454         }
455
456         header = _dl_mmap((void *) 0, _dl_pagesize, PROT_READ | PROT_WRITE,
457                         MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
458         if (_dl_mmap_check_error(header)) {
459                 _dl_dprintf(2, "%s: can't map '%s'\n", _dl_progname, libname);
460                 _dl_internal_error_number = LD_ERROR_MMAP_FAILED;
461                 _dl_close(infile);
462                 return NULL;
463         };
464
465         _dl_read(infile, header, _dl_pagesize);
466         epnt = (ElfW(Ehdr) *) (intptr_t) header;
467         if (epnt->e_ident[0] != 0x7f ||
468                         epnt->e_ident[1] != 'E' ||
469                         epnt->e_ident[2] != 'L' ||
470                         epnt->e_ident[3] != 'F')
471         {
472                 _dl_dprintf(2, "%s: '%s' is not an ELF file\n", _dl_progname,
473                                 libname);
474                 _dl_internal_error_number = LD_ERROR_NOTELF;
475                 _dl_close(infile);
476                 _dl_munmap(header, _dl_pagesize);
477                 return NULL;
478         };
479
480         if ((epnt->e_type != ET_DYN) || (epnt->e_machine != MAGIC1
481 #ifdef MAGIC2
482                                 && epnt->e_machine != MAGIC2
483 #endif
484                                 ))
485         {
486                 _dl_internal_error_number =
487                         (epnt->e_type != ET_DYN ? LD_ERROR_NOTDYN : LD_ERROR_NOTMAGIC);
488                 _dl_dprintf(2, "%s: '%s' is not an ELF executable for " ELF_TARGET
489                                 "\n", _dl_progname, libname);
490                 _dl_close(infile);
491                 _dl_munmap(header, _dl_pagesize);
492                 return NULL;
493         };
494
495         ppnt = (ElfW(Phdr) *)(intptr_t) & header[epnt->e_phoff];
496
497         piclib = 1;
498         for (i = 0; i < epnt->e_phnum; i++) {
499
500                 if (ppnt->p_type == PT_DYNAMIC) {
501                         if (dynamic_addr)
502                                 _dl_dprintf(2, "%s: '%s' has more than one dynamic section\n",
503                                                 _dl_progname, libname);
504                         dynamic_addr = ppnt->p_vaddr;
505                 };
506
507                 if (ppnt->p_type == PT_LOAD) {
508                         /* See if this is a PIC library. */
509                         if (i == 0 && ppnt->p_vaddr > 0x1000000) {
510                                 piclib = 0;
511                                 minvma = ppnt->p_vaddr;
512                         }
513                         if (piclib && ppnt->p_vaddr < minvma) {
514                                 minvma = ppnt->p_vaddr;
515                         }
516                         if (((unsigned long) ppnt->p_vaddr + ppnt->p_memsz) > maxvma) {
517                                 maxvma = ppnt->p_vaddr + ppnt->p_memsz;
518                         }
519                 }
520                 ppnt++;
521         };
522
523         maxvma = (maxvma + ADDR_ALIGN) & ~ADDR_ALIGN;
524         minvma = minvma & ~0xffffU;
525
526         flags = MAP_PRIVATE /*| MAP_DENYWRITE */ ;
527         if (!piclib)
528                 flags |= MAP_FIXED;
529
530         status = (char *) _dl_mmap((char *) (piclib ? 0 : minvma),
531                         maxvma - minvma, PROT_NONE, flags | MAP_ANONYMOUS, -1, 0);
532         if (_dl_mmap_check_error(status)) {
533                 _dl_dprintf(2, "%s: can't map %s\n", _dl_progname, libname);
534                 _dl_internal_error_number = LD_ERROR_MMAP_FAILED;
535                 _dl_close(infile);
536                 _dl_munmap(header, _dl_pagesize);
537                 return NULL;
538         };
539         libaddr = (unsigned long) status;
540         flags |= MAP_FIXED;
541
542         /* Get the memory to store the library */
543         ppnt = (ElfW(Phdr) *)(intptr_t) & header[epnt->e_phoff];
544
545         for (i = 0; i < epnt->e_phnum; i++) {
546                 if (ppnt->p_type == PT_GNU_RELRO) {
547                         relro_addr = ppnt->p_vaddr;
548                         relro_size = ppnt->p_memsz;
549                 }
550                 if (ppnt->p_type == PT_LOAD) {
551
552                         /* See if this is a PIC library. */
553                         if (i == 0 && ppnt->p_vaddr > 0x1000000) {
554                                 piclib = 0;
555                                 /* flags |= MAP_FIXED; */
556                         }
557
558
559
560                         if (ppnt->p_flags & PF_W) {
561                                 unsigned long map_size;
562                                 char *cpnt;
563
564                                 status = (char *) _dl_mmap((char *) ((piclib ? libaddr : 0) +
565                                                         (ppnt->p_vaddr & PAGE_ALIGN)), (ppnt->p_vaddr & ADDR_ALIGN)
566                                                 + ppnt->p_filesz, LXFLAGS(ppnt->p_flags), flags, infile,
567                                                 ppnt->p_offset & OFFS_ALIGN);
568
569                                 if (_dl_mmap_check_error(status)) {
570                                         _dl_dprintf(2, "%s: can't map '%s'\n",
571                                                         _dl_progname, libname);
572                                         _dl_internal_error_number = LD_ERROR_MMAP_FAILED;
573                                         _dl_munmap((char *) libaddr, maxvma - minvma);
574                                         _dl_close(infile);
575                                         _dl_munmap(header, _dl_pagesize);
576                                         return NULL;
577                                 };
578
579                                 /* Pad the last page with zeroes. */
580                                 cpnt = (char *) (status + (ppnt->p_vaddr & ADDR_ALIGN) +
581                                                 ppnt->p_filesz);
582                                 while (((unsigned long) cpnt) & ADDR_ALIGN)
583                                         *cpnt++ = 0;
584
585                                 /* I am not quite sure if this is completely
586                                  * correct to do or not, but the basic way that
587                                  * we handle bss segments is that we mmap
588                                  * /dev/zero if there are any pages left over
589                                  * that are not mapped as part of the file */
590
591                                 map_size = (ppnt->p_vaddr + ppnt->p_filesz + ADDR_ALIGN) & PAGE_ALIGN;
592
593                                 if (map_size < ppnt->p_vaddr + ppnt->p_memsz)
594                                         status = (char *) _dl_mmap((char *) map_size +
595                                                         (piclib ? libaddr : 0),
596                                                         ppnt->p_vaddr + ppnt->p_memsz - map_size,
597                                                         LXFLAGS(ppnt->p_flags), flags | MAP_ANONYMOUS, -1, 0);
598                         } else
599                                 status = (char *) _dl_mmap((char *) (ppnt->p_vaddr & PAGE_ALIGN)
600                                                 + (piclib ? libaddr : 0), (ppnt->p_vaddr & ADDR_ALIGN) +
601                                                 ppnt->p_filesz, LXFLAGS(ppnt->p_flags), flags,
602                                                 infile, ppnt->p_offset & OFFS_ALIGN);
603                         if (_dl_mmap_check_error(status)) {
604                                 _dl_dprintf(2, "%s: can't map '%s'\n", _dl_progname, libname);
605                                 _dl_internal_error_number = LD_ERROR_MMAP_FAILED;
606                                 _dl_munmap((char *) libaddr, maxvma - minvma);
607                                 _dl_close(infile);
608                                 _dl_munmap(header, _dl_pagesize);
609                                 return NULL;
610                         };
611
612                         /* if(libaddr == 0 && piclib) {
613                            libaddr = (unsigned long) status;
614                            flags |= MAP_FIXED;
615                            }; */
616                 };
617                 ppnt++;
618         };
619         _dl_close(infile);
620
621         /* For a non-PIC library, the addresses are all absolute */
622         if (piclib) {
623                 dynamic_addr += (unsigned long) libaddr;
624         }
625
626         /*
627          * OK, the ELF library is now loaded into VM in the correct locations
628          * The next step is to go through and do the dynamic linking (if needed).
629          */
630
631         /* Start by scanning the dynamic section to get all of the pointers */
632
633         if (!dynamic_addr) {
634                 _dl_internal_error_number = LD_ERROR_NODYNAMIC;
635                 _dl_dprintf(2, "%s: '%s' is missing a dynamic section\n",
636                                 _dl_progname, libname);
637                 _dl_munmap(header, _dl_pagesize);
638                 return NULL;
639         }
640
641         dpnt = (ElfW(Dyn) *) dynamic_addr;
642         _dl_memset(dynamic_info, 0, sizeof(dynamic_info));
643         _dl_parse_dynamic_info(dpnt, dynamic_info, NULL, libaddr);
644         /* If the TEXTREL is set, this means that we need to make the pages
645            writable before we perform relocations.  Do this now. They get set
646            back again later. */
647
648         if (dynamic_info[DT_TEXTREL]) {
649 #ifndef __FORCE_SHAREABLE_TEXT_SEGMENTS__
650                 ppnt = (ElfW(Phdr) *)(intptr_t) & header[epnt->e_phoff];
651                 for (i = 0; i < epnt->e_phnum; i++, ppnt++) {
652                         if (ppnt->p_type == PT_LOAD && !(ppnt->p_flags & PF_W))
653                                 _dl_mprotect((void *) ((piclib ? libaddr : 0) +
654                                                         (ppnt->p_vaddr & PAGE_ALIGN)),
655                                                 (ppnt->p_vaddr & ADDR_ALIGN) + (unsigned long) ppnt->p_filesz,
656                                                 PROT_READ | PROT_WRITE | PROT_EXEC);
657                 }
658 #else
659                 _dl_dprintf(_dl_debug_file, "Can't modify %s's text section. Use GCC option -fPIC for shared objects, please.\n",libname);
660                 _dl_exit(1);
661 #endif
662         }
663
664         tpnt = _dl_add_elf_hash_table(libname, (char *) libaddr, dynamic_info,
665                         dynamic_addr, 0);
666         tpnt->relro_addr = relro_addr;
667         tpnt->relro_size = relro_size;
668         tpnt->ppnt = (ElfW(Phdr) *)(intptr_t) (tpnt->loadaddr + epnt->e_phoff);
669         tpnt->n_phent = epnt->e_phnum;
670
671         /*
672          * Add this object into the symbol chain
673          */
674         if (*rpnt) {
675                 (*rpnt)->next = (struct dyn_elf *) _dl_malloc(sizeof(struct dyn_elf));
676                 _dl_memset((*rpnt)->next, 0, sizeof(struct dyn_elf));
677                 (*rpnt)->next->prev = (*rpnt);
678                 *rpnt = (*rpnt)->next;
679                 (*rpnt)->dyn = tpnt;
680                 tpnt->symbol_scope = _dl_symbol_tables;
681         }
682         tpnt->usage_count++;
683         tpnt->libtype = elf_lib;
684
685         /*
686          * OK, the next thing we need to do is to insert the dynamic linker into
687          * the proper entry in the GOT so that the PLT symbols can be properly
688          * resolved.
689          */
690
691         lpnt = (unsigned long *) dynamic_info[DT_PLTGOT];
692
693         if (lpnt) {
694                 lpnt = (unsigned long *) (dynamic_info[DT_PLTGOT]);
695                 INIT_GOT(lpnt, tpnt);
696         }
697
698         _dl_if_debug_dprint("\n\tfile='%s';  generating link map\n", libname);
699         _dl_if_debug_dprint("\t\tdynamic: %x  base: %x\n", dynamic_addr, libaddr);
700         _dl_if_debug_dprint("\t\t  entry: %x  phdr: %x  phnum: %x\n\n",
701                         epnt->e_entry + libaddr, tpnt->ppnt, tpnt->n_phent);
702
703         _dl_munmap(header, _dl_pagesize);
704
705         return tpnt;
706 }
707
708 /* now_flag must be RTLD_NOW or zero */
709 int _dl_fixup(struct dyn_elf *rpnt, int now_flag)
710 {
711         int goof = 0;
712         struct elf_resolve *tpnt;
713         ElfW(Word) reloc_size, relative_count;
714         ElfW(Addr) reloc_addr;
715
716         if (rpnt->next)
717                 goof += _dl_fixup(rpnt->next, now_flag);
718         tpnt = rpnt->dyn;
719
720         if(!(tpnt->init_flag & RELOCS_DONE)) 
721                 _dl_if_debug_dprint("relocation processing: %s\n", tpnt->libname);
722
723         if (unlikely(tpnt->dynamic_info[UNSUPPORTED_RELOC_TYPE])) {
724                 _dl_if_debug_dprint("%s: can't handle %s relocation records\n",
725                                 _dl_progname, UNSUPPORTED_RELOC_STR);
726                 goof++;
727                 return goof;
728         }
729
730         reloc_size = tpnt->dynamic_info[DT_RELOC_TABLE_SIZE];
731 /* On some machines, notably SPARC & PPC, DT_REL* includes DT_JMPREL in its
732    range.  Note that according to the ELF spec, this is completely legal! */
733 #ifdef ELF_MACHINE_PLTREL_OVERLAP
734         reloc_size -= tpnt->dynamic_info [DT_PLTRELSZ];
735 #endif
736         if (tpnt->dynamic_info[DT_RELOC_TABLE_ADDR] &&
737             !(tpnt->init_flag & RELOCS_DONE)) {
738                 tpnt->init_flag |= RELOCS_DONE;
739                 reloc_addr = tpnt->dynamic_info[DT_RELOC_TABLE_ADDR];
740                 relative_count = tpnt->dynamic_info[DT_RELCONT_IDX];
741                 if (relative_count) { /* Optimize the XX_RELATIVE relocations if possible */
742                         reloc_size -= relative_count * sizeof(ELF_RELOC);
743                         elf_machine_relative(tpnt->loadaddr, reloc_addr, relative_count);
744                         reloc_addr += relative_count * sizeof(ELF_RELOC);
745                 }
746                 goof += _dl_parse_relocation_information(rpnt,
747                                 reloc_addr,
748                                 reloc_size);
749         }
750         if (tpnt->dynamic_info[DT_BIND_NOW])
751                 now_flag = RTLD_NOW;
752         if (tpnt->dynamic_info[DT_JMPREL] &&
753             (!(tpnt->init_flag & JMP_RELOCS_DONE) ||
754              (now_flag && !(tpnt->rtld_flags & now_flag)))) {
755                 tpnt->rtld_flags |= now_flag; 
756                 tpnt->init_flag |= JMP_RELOCS_DONE;
757                 if (!(tpnt->rtld_flags & RTLD_NOW)) {
758                         _dl_parse_lazy_relocation_information(rpnt,
759                                         tpnt->dynamic_info[DT_JMPREL],
760                                         tpnt->dynamic_info [DT_PLTRELSZ]);
761                 } else {
762                         goof += _dl_parse_relocation_information(rpnt,
763                                         tpnt->dynamic_info[DT_JMPREL],
764                                         tpnt->dynamic_info[DT_PLTRELSZ]);
765                 }
766         }
767         return goof;
768 }
769
770 /* Minimal printf which handles only %s, %d, and %x */
771 void _dl_dprintf(int fd, const char *fmt, ...)
772 {
773 #if __WORDSIZE > 32
774         long int num;
775 #else
776         int num;
777 #endif
778         va_list args;
779         char *start, *ptr, *string;
780         static char *buf;
781
782         buf = _dl_mmap((void *) 0, _dl_pagesize, PROT_READ | PROT_WRITE,
783                         MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
784         if (_dl_mmap_check_error(buf)) {
785                 _dl_write(fd, "mmap of a spare page failed!\n", 29);
786                 _dl_exit(20);
787         }
788
789         start = ptr = buf;
790
791         if (!fmt)
792                 return;
793
794         if (_dl_strlen(fmt) >= (_dl_pagesize - 1)) {
795                 _dl_write(fd, "overflow\n", 11);
796                 _dl_exit(20);
797         }
798
799         _dl_strcpy(buf, fmt);
800         va_start(args, fmt);
801
802         while (start) {
803                 while (*ptr != '%' && *ptr) {
804                         ptr++;
805                 }
806
807                 if (*ptr == '%') {
808                         *ptr++ = '\0';
809                         _dl_write(fd, start, _dl_strlen(start));
810
811                         switch (*ptr++) {
812                                 case 's':
813                                         string = va_arg(args, char *);
814
815                                         if (!string)
816                                                 _dl_write(fd, "(null)", 6);
817                                         else
818                                                 _dl_write(fd, string, _dl_strlen(string));
819                                         break;
820
821                                 case 'i':
822                                 case 'd':
823                                         {
824                                                 char tmp[22];
825 #if __WORDSIZE > 32
826                                                 num = va_arg(args, long int);
827 #else
828                                                 num = va_arg(args, int);
829 #endif
830                                                 string = _dl_simple_ltoa(tmp, num);
831                                                 _dl_write(fd, string, _dl_strlen(string));
832                                                 break;
833                                         }
834                                 case 'x':
835                                 case 'X':
836                                         {
837                                                 char tmp[22];
838 #if __WORDSIZE > 32
839                                                 num = va_arg(args, long int);
840 #else
841                                                 num = va_arg(args, int);
842 #endif
843                                                 string = _dl_simple_ltoahex(tmp, num);
844                                                 _dl_write(fd, string, _dl_strlen(string));
845                                                 break;
846                                         }
847                                 default:
848                                         _dl_write(fd, "(null)", 6);
849                                         break;
850                         }
851
852                         start = ptr;
853                 } else {
854                         _dl_write(fd, start, _dl_strlen(start));
855                         start = NULL;
856                 }
857         }
858         _dl_munmap(buf, _dl_pagesize);
859         return;
860 }
861
862 char *_dl_strdup(const char *string)
863 {
864         char *retval;
865         int len;
866
867         len = _dl_strlen(string);
868         retval = _dl_malloc(len + 1);
869         _dl_strcpy(retval, string);
870         return retval;
871 }
872
873 void _dl_parse_dynamic_info(ElfW(Dyn) *dpnt, unsigned long dynamic_info[], void *debug_addr, ElfW(Addr) load_off)
874 {
875         __dl_parse_dynamic_info(dpnt, dynamic_info, debug_addr, load_off);
876 }
877 #ifdef __USE_GNU
878 #if ! defined LIBDL || (! defined PIC && ! defined __PIC__)
879 int
880 __dl_iterate_phdr (int (*callback) (struct dl_phdr_info *info, size_t size, void *data), void *data)
881 {
882         struct elf_resolve *l;
883         struct dl_phdr_info info;
884         int ret = 0;
885
886         for (l = _dl_loaded_modules; l != NULL; l = l->next) {
887                 info.dlpi_addr = l->loadaddr;
888                 info.dlpi_name = l->libname;
889                 info.dlpi_phdr = l->ppnt;
890                 info.dlpi_phnum = l->n_phent;
891                 ret = callback (&info, sizeof (struct dl_phdr_info), data);
892                 if (ret)
893                         break;
894         }
895         return ret;
896 }
897 strong_alias(__dl_iterate_phdr, dl_iterate_phdr);
898 #endif
899 #endif