OSDN Git Service

Let ldso decide if it should relocate itselft a second time. This
[uclinux-h8/uClibc.git] / ldso / libdl / libdl.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Program to load an ELF binary on a linux system, and run it
4  * after resolving ELF shared library symbols
5  *
6  * Copyright (C) 2000-2004 by Erik Andersen <andersen@codpoet.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 #include <stdio.h>
35
36
37 #if defined (__LIBDL_SHARED__)
38
39 /* When libdl is loaded as a shared library, we need to load in
40  * and use a pile of symbols from ldso... */
41
42 extern char *_dl_find_hash(const char *, struct dyn_elf *, int)
43         __attribute__ ((__weak__));
44 extern struct elf_resolve * _dl_load_shared_library(int, struct dyn_elf **,
45         struct elf_resolve *, char *, int) __attribute__ ((__weak__));
46 extern struct elf_resolve * _dl_check_if_named_library_is_loaded(const char *, int)
47         __attribute__ ((__weak__));
48 extern int _dl_fixup(struct dyn_elf *rpnt, int lazy)
49          __attribute__ ((__weak__));
50 extern int _dl_errno __attribute__ ((__weak__));
51 extern struct dyn_elf *_dl_symbol_tables __attribute__ ((__weak__));
52 extern struct dyn_elf *_dl_handles __attribute__ ((__weak__));
53 extern struct elf_resolve *_dl_loaded_modules __attribute__ ((__weak__));
54 extern struct r_debug *_dl_debug_addr __attribute__ ((__weak__));
55 extern unsigned long _dl_error_number __attribute__ ((__weak__));
56 extern void *(*_dl_malloc_function)(size_t) __attribute__ ((__weak__));
57 #ifdef USE_CACHE
58 int _dl_map_cache(void) __attribute__ ((__weak__));
59 int _dl_unmap_cache(void) __attribute__ ((__weak__));
60 #endif
61 #ifdef __mips__
62 extern void _dl_perform_mips_global_got_relocations(struct elf_resolve *tpnt)
63         __attribute__ ((__weak__));
64 #endif
65 #ifdef __SUPPORT_LD_DEBUG__
66 extern char *_dl_debug __attribute__ ((__weak__));
67 #endif
68
69
70 #else /* __LIBDL_SHARED__ */
71
72 /* When libdl is linked as a static library, we need to replace all
73  * the symbols that otherwise would have been loaded in from ldso... */
74
75 #ifdef __SUPPORT_LD_DEBUG__
76 char *_dl_debug  = 0;
77 #endif
78 char *_dl_library_path         = 0;                 /* Where we look for libraries */
79 char *_dl_ldsopath             = 0;                 /* Location of the shared lib loader */
80 int _dl_errno                  = 0;         /* We can't use the real errno in ldso */
81 size_t _dl_pagesize            = PAGE_SIZE; /* Store the page size for use later */
82 /* This global variable is also to communicate with debuggers such as gdb. */
83 struct r_debug *_dl_debug_addr = NULL;
84 #define _dl_malloc malloc
85 #include "dl-progname.h"
86 #include "../ldso/dl-hash.c"
87 #define _dl_trace_loaded_objects    0
88 #include "../ldso/dl-elf.c"
89 #endif
90
91 static int do_dlclose(void *, int need_fini);
92
93
94 static const char *dl_error_names[] = {
95         "",
96         "File not found",
97         "Unable to open /dev/zero",
98         "Not an ELF file",
99 #if defined (__i386__)
100         "Not i386 binary",
101 #elif defined (__sparc__)
102         "Not sparc binary",
103 #elif defined (__mc68000__)
104         "Not m68k binary",
105 #else
106         "Unrecognized binary type",
107 #endif
108         "Not an ELF shared library",
109         "Unable to mmap file",
110         "No dynamic section",
111 #ifdef ELF_USES_RELOCA
112         "Unable to process REL relocs",
113 #else
114         "Unable to process RELA relocs",
115 #endif
116         "Bad handle",
117         "Unable to resolve symbol"
118 };
119
120 void __attribute__ ((destructor)) dl_cleanup(void)
121 {
122         struct dyn_elf *d;
123         for (d = _dl_handles; d; d = d->next_handle) {
124                 do_dlclose(d, 1);
125         }
126 }
127
128 void *dlopen(const char *libname, int flag)
129 {
130         struct elf_resolve *tpnt, *tfrom, *tcurr;
131         struct dyn_elf *dyn_chain, *rpnt = NULL, *dyn_ptr;
132         struct dyn_elf *dpnt;
133         static int dl_init = 0;
134         ElfW(Addr) from;
135         struct elf_resolve *tpnt1;
136         void (*dl_brk) (void);
137         int now_flag;
138
139         /* A bit of sanity checking... */
140         if (!(flag & (RTLD_LAZY|RTLD_NOW))) {
141                 _dl_error_number = LD_BAD_HANDLE;
142                 return NULL;
143         }
144
145         from = (ElfW(Addr)) __builtin_return_address(0);
146
147         /* Have the dynamic linker use the regular malloc function now */
148         if (!dl_init) {
149                 dl_init++;
150 #if defined (__LIBDL_SHARED__)
151                 _dl_malloc_function = malloc;
152 #endif
153         }
154
155         /* Cover the trivial case first */
156         if (!libname)
157                 return _dl_symbol_tables;
158
159         _dl_map_cache();
160
161         /*
162          * Try and locate the module we were called from - we
163          * need this so that we get the correct RPATH.  Note that
164          * this is the current behavior under Solaris, but the
165          * ABI+ specifies that we should only use the RPATH from
166          * the application.  Thus this may go away at some time
167          * in the future.
168          */
169         tfrom = NULL;
170         for (dpnt = _dl_symbol_tables; dpnt; dpnt = dpnt->next) {
171                 tpnt = dpnt->dyn;
172                 if (tpnt->loadaddr < from
173                                 && (tfrom == NULL || tfrom->loadaddr < tpnt->loadaddr))
174                         tfrom = tpnt;
175         }
176         for(rpnt = _dl_symbol_tables; rpnt->next; rpnt=rpnt->next);
177         /* Try to load the specified library */
178 #ifdef __SUPPORT_LD_DEBUG__
179         if(_dl_debug)
180                 fprintf(stderr, "Trying to dlopen '%s'\n", (char*)libname);
181 #endif
182         if (!(tpnt = _dl_check_if_named_library_is_loaded((char *)libname, 0)))
183                 tpnt = _dl_load_shared_library(0, &rpnt, tfrom, (char*)libname, 0);
184         if (tpnt == NULL) {
185                 _dl_unmap_cache();
186                 return NULL;
187         }
188
189         dyn_chain = (struct dyn_elf *) malloc(sizeof(struct dyn_elf));
190         _dl_memset(dyn_chain, 0, sizeof(struct dyn_elf));
191         dyn_chain->dyn = tpnt;
192         tpnt->rtld_flags |= RTLD_GLOBAL;
193
194         dyn_chain->next_handle = _dl_handles;
195         _dl_handles = dyn_ptr = dyn_chain;
196
197 #ifdef __SUPPORT_LD_DEBUG__
198         if(_dl_debug)
199                 fprintf(stderr, "Looking for needed libraries\n");
200 #endif
201
202         for (tcurr = tpnt; tcurr; tcurr = tcurr->next)
203         {
204                 Elf32_Dyn *dpnt;
205                 char *lpntstr;
206                 for (dpnt = (Elf32_Dyn *) tcurr->dynamic_addr; dpnt->d_tag; dpnt++) {
207                         if (dpnt->d_tag == DT_NEEDED) {
208
209                                 char *name;
210                                 lpntstr = (char*) (tcurr->loadaddr + tcurr->dynamic_info[DT_STRTAB] +
211                                                 dpnt->d_un.d_val);
212                                 name = _dl_get_last_path_component(lpntstr);
213                                 tpnt1 = _dl_check_if_named_library_is_loaded(name, 0);
214 #ifdef __SUPPORT_LD_DEBUG__
215                                 if(_dl_debug)
216                                         fprintf(stderr, "Trying to load '%s', needed by '%s'\n",
217                                                         lpntstr, tcurr->libname);
218 #endif
219                                 dyn_ptr->next = (struct dyn_elf *) malloc(sizeof(struct dyn_elf));
220                                 _dl_memset (dyn_ptr->next, 0, sizeof (struct dyn_elf));
221                                 dyn_ptr = dyn_ptr->next;
222                                 dyn_ptr->dyn = tpnt1;
223                                 tpnt->rtld_flags |= RTLD_GLOBAL;
224                                 if (!tpnt1) {
225                                         tpnt1 = _dl_load_shared_library(0, &rpnt, tcurr, lpntstr, 0);
226                                         if (!tpnt1)
227                                                 goto oops;
228                                         dyn_ptr->dyn = tpnt1;
229                                 } else {
230                                         tpnt1->usage_count++;
231                                 }
232                         }
233                 }
234         }
235
236         if (dyn_chain->dyn->init_flag & INIT_FUNCS_CALLED) {
237                 /* If the init and fini stuff has already been run, that means
238                  * the dlopen'd library has already been loaded, and nothing
239                  * further needs to be done. */
240                 return (void *) dyn_chain;
241         }
242 #ifdef __mips__
243         /*
244          * Relocation of the GOT entries for MIPS have to be done
245          * after all the libraries have been loaded.
246          */
247         _dl_perform_mips_global_got_relocations(tpnt);
248 #endif
249
250 #ifdef __SUPPORT_LD_DEBUG__
251         if(_dl_debug)
252                 fprintf(stderr, "Beginning dlopen relocation fixups\n");
253 #endif
254         /*
255          * OK, now all of the kids are tucked into bed in their proper addresses.
256          * Now we go through and look for REL and RELA records that indicate fixups
257          * to the GOT tables.  We need to do this in reverse order so that COPY
258          * directives work correctly */
259         now_flag = (flag & RTLD_NOW) ? RTLD_NOW : 0;
260         if (getenv("LD_BIND_NOW"))
261                 now_flag = RTLD_NOW;
262         if (_dl_fixup(dyn_chain, now_flag))
263                 goto oops;
264
265         /* TODO:  Should we set the protections of all pages back to R/O now ? */
266
267
268         /* Notify the debugger we have added some objects. */
269         if (_dl_debug_addr) {
270                 dl_brk = (void (*)(void)) _dl_debug_addr->r_brk;
271                 if (dl_brk != NULL) {
272                         _dl_debug_addr->r_state = RT_ADD;
273                         (*dl_brk) ();
274
275                         _dl_debug_addr->r_state = RT_CONSISTENT;
276                         (*dl_brk) ();
277                 }
278         }
279
280 #if defined (__LIBDL_SHARED__)
281         /* Find the last library so we can run things in the right order */
282         for (tpnt = dyn_chain->dyn; tpnt->next!=NULL; tpnt = tpnt->next)
283                 ;
284
285         /* Run the ctors and set up the dtors */
286         for (; tpnt != dyn_chain->dyn->prev; tpnt=tpnt->prev)
287         {
288                 /* Apparently crt1 for the application is responsible for handling this.
289                  * We only need to run the init/fini for shared libraries
290                  */
291                 if (tpnt->libtype == program_interpreter)
292                         continue;
293                 if (tpnt->libtype == elf_executable)
294                         continue;
295                 if (tpnt->init_flag & INIT_FUNCS_CALLED)
296                         continue;
297                 tpnt->init_flag |= INIT_FUNCS_CALLED;
298
299                 if (tpnt->dynamic_info[DT_INIT]) {
300                         void (*dl_elf_func) (void);
301                         dl_elf_func = (void (*)(void)) (tpnt->loadaddr + tpnt->dynamic_info[DT_INIT]);
302                         if (dl_elf_func && *dl_elf_func != NULL) {
303 #ifdef __SUPPORT_LD_DEBUG__
304                                 if(_dl_debug)
305                                         fprintf(stderr, "running ctors for library %s at '%x'\n", tpnt->libname, dl_elf_func);
306 #endif
307                                 (*dl_elf_func) ();
308                         }
309                 }
310         }
311 #endif
312         return (void *) dyn_chain;
313
314 oops:
315         /* Something went wrong.  Clean up and return NULL. */
316         _dl_unmap_cache();
317         do_dlclose(dyn_chain, 0);
318         return NULL;
319 }
320
321 void *dlsym(void *vhandle, const char *name)
322 {
323         struct elf_resolve *tpnt, *tfrom;
324         struct dyn_elf *handle;
325         ElfW(Addr) from;
326         struct dyn_elf *rpnt;
327         void *ret;
328
329         handle = (struct dyn_elf *) vhandle;
330
331         /* First of all verify that we have a real handle
332            of some kind.  Return NULL if not a valid handle. */
333
334         if (handle == NULL)
335                 handle = _dl_symbol_tables;
336         else if (handle != RTLD_NEXT && handle != _dl_symbol_tables) {
337                 for (rpnt = _dl_handles; rpnt; rpnt = rpnt->next_handle)
338                         if (rpnt == handle)
339                                 break;
340                 if (!rpnt) {
341                         _dl_error_number = LD_BAD_HANDLE;
342                         return NULL;
343                 }
344         } else if (handle == RTLD_NEXT) {
345                 /*
346                  * Try and locate the module we were called from - we
347                  * need this so that we know where to start searching
348                  * from.  We never pass RTLD_NEXT down into the actual
349                  * dynamic loader itself, as it doesn't know
350                  * how to properly treat it.
351                  */
352                 from = (ElfW(Addr)) __builtin_return_address(0);
353
354                 tfrom = NULL;
355                 for (rpnt = _dl_symbol_tables; rpnt; rpnt = rpnt->next) {
356                         tpnt = rpnt->dyn;
357                         if (tpnt->loadaddr < from
358                                         && (tfrom == NULL || tfrom->loadaddr < tpnt->loadaddr)) {
359                                 tfrom = tpnt;
360                                 handle = rpnt->next;
361                         }
362                 }
363         }
364
365         ret = _dl_find_hash((char*)name, handle, 0);
366
367         /*
368          * Nothing found.
369          */
370         if (!ret)
371                 _dl_error_number = LD_NO_SYMBOL;
372         return ret;
373 }
374
375 static int do_dlclose(void *vhandle, int need_fini)
376 {
377         struct dyn_elf *rpnt, *rpnt1;
378         ElfW(Phdr) *ppnt;
379         struct elf_resolve *tpnt;
380         int (*dl_elf_fini) (void);
381         void (*dl_brk) (void);
382         struct dyn_elf *handle;
383         unsigned int end;
384         int i = 0;
385
386         handle = (struct dyn_elf *) vhandle;
387         rpnt1 = NULL;
388         for (rpnt = _dl_handles; rpnt; rpnt = rpnt->next_handle) {
389                 if (rpnt == handle)
390                         break;
391                 rpnt1 = rpnt;
392         }
393
394         if (!rpnt) {
395                 _dl_error_number = LD_BAD_HANDLE;
396                 return 1;
397         }
398         if (rpnt1)
399                 rpnt1->next_handle = rpnt->next_handle;
400         else
401                 _dl_handles = rpnt->next_handle;
402         /* OK, this is a valid handle - now close out the file */
403         for (rpnt = handle; rpnt; rpnt = rpnt->next) {
404                 tpnt = rpnt->dyn;
405                 if (--tpnt->usage_count == 0) {
406                         if (need_fini && tpnt->dynamic_info[DT_FINI]) {
407                                 dl_elf_fini = (int (*)(void)) (tpnt->loadaddr + tpnt->dynamic_info[DT_FINI]);
408                                 (*dl_elf_fini) ();
409                         }
410
411                         end = 0;
412                         for (i = 0, ppnt = tpnt->ppnt;
413                                         i < tpnt->n_phent; ppnt++, i++) {
414                                 if (ppnt->p_type != PT_LOAD)
415                                         continue;
416                                 if (end < ppnt->p_vaddr + ppnt->p_memsz)
417                                         end = ppnt->p_vaddr + ppnt->p_memsz;
418                         }
419                         _dl_munmap((void*)tpnt->loadaddr, end);
420                         /* Next, remove tpnt from the loaded_module list */
421                         if (_dl_loaded_modules == tpnt) {
422                                 _dl_loaded_modules = tpnt->next;
423                                 if (_dl_loaded_modules)
424                                         _dl_loaded_modules->prev = 0;
425                         } else
426                                 for (tpnt = _dl_loaded_modules; tpnt; tpnt = tpnt->next)
427                                         if (tpnt->next == rpnt->dyn) {
428                                                 tpnt->next = tpnt->next->next;
429                                                 if (tpnt->next)
430                                                         tpnt->next->prev = tpnt;
431                                                 break;
432                                         }
433
434                         /* Next, remove tpnt from the global symbol table list */
435                         if (_dl_symbol_tables->dyn == rpnt->dyn) {
436                                 _dl_symbol_tables = rpnt->next;
437                                 if (_dl_symbol_tables)
438                                         _dl_symbol_tables->prev = 0;
439                         } else
440                                 for (rpnt1 = _dl_symbol_tables; rpnt1->next; rpnt1 = rpnt1->next) {
441                                         if (rpnt1->next->dyn == rpnt->dyn) {
442                                                 free(rpnt1->next);
443                                                 rpnt1->next = rpnt1->next->next;
444                                                 if (rpnt1->next)
445                                                         rpnt1->next->prev = rpnt1;
446                                                 break;
447                                         }
448                                 }
449                         free(rpnt->dyn->libname);
450                         free(rpnt->dyn);
451                 }
452                 free(rpnt);
453         }
454
455
456         if (_dl_debug_addr) {
457                 dl_brk = (void (*)(void)) _dl_debug_addr->r_brk;
458                 if (dl_brk != NULL) {
459                         _dl_debug_addr->r_state = RT_DELETE;
460                         (*dl_brk) ();
461
462                         _dl_debug_addr->r_state = RT_CONSISTENT;
463                         (*dl_brk) ();
464                 }
465         }
466
467         return 0;
468 }
469
470 int dlclose(void *vhandle)
471 {
472         return do_dlclose(vhandle, 1);
473 }
474
475 const char *dlerror(void)
476 {
477         const char *retval;
478
479         if (!_dl_error_number)
480                 return NULL;
481         retval = dl_error_names[_dl_error_number];
482         _dl_error_number = 0;
483         return retval;
484 }
485
486 /*
487  * Dump information to stderrr about the current loaded modules
488  */
489 static char *type[] = { "Lib", "Exe", "Int", "Mod" };
490
491 void dlinfo(void)
492 {
493         struct elf_resolve *tpnt;
494         struct dyn_elf *rpnt, *hpnt;
495
496         fprintf(stderr, "List of loaded modules\n");
497         /* First start with a complete list of all of the loaded files. */
498         for (tpnt = _dl_loaded_modules; tpnt; tpnt = tpnt->next) {
499                 fprintf(stderr, "\t%x %x %x %s %d %s\n",
500                                 (unsigned) tpnt->loadaddr, (unsigned) tpnt,
501                                 (unsigned) tpnt->symbol_scope,
502                                 type[tpnt->libtype],
503                                 tpnt->usage_count, tpnt->libname);
504         }
505
506         /* Next dump the module list for the application itself */
507         fprintf(stderr, "\nModules for application (%x):\n",
508                         (unsigned) _dl_symbol_tables);
509         for (rpnt = _dl_symbol_tables; rpnt; rpnt = rpnt->next)
510                 fprintf(stderr, "\t%x %s\n", (unsigned) rpnt->dyn, rpnt->dyn->libname);
511
512         for (hpnt = _dl_handles; hpnt; hpnt = hpnt->next_handle) {
513                 fprintf(stderr, "Modules for handle %x\n", (unsigned) hpnt);
514                 for (rpnt = hpnt; rpnt; rpnt = rpnt->next)
515                         fprintf(stderr, "\t%x %s\n", (unsigned) rpnt->dyn,
516                                         rpnt->dyn->libname);
517         }
518 }
519
520 int dladdr(void *__address, Dl_info * __dlip)
521 {
522         struct elf_resolve *pelf;
523         struct elf_resolve *rpnt;
524
525         _dl_map_cache();
526
527         /*
528          * Try and locate the module address is in
529          */
530         pelf = NULL;
531
532 #if 0
533         fprintf(stderr, "dladdr( %x, %x )\n", __address, __dlip);
534 #endif
535
536         for (rpnt = _dl_loaded_modules; rpnt; rpnt = rpnt->next) {
537                 struct elf_resolve *tpnt;
538
539                 tpnt = rpnt;
540 #if 0
541                 fprintf(stderr, "Module \"%s\" at %x\n",
542                                 tpnt->libname, tpnt->loadaddr);
543 #endif
544                 if (tpnt->loadaddr < (ElfW(Addr)) __address
545                                 && (pelf == NULL || pelf->loadaddr < tpnt->loadaddr)) {
546                         pelf = tpnt;
547                 }
548         }
549
550         if (!pelf) {
551                 return 0;
552         }
553
554         /*
555          * Try and locate the symbol of address
556          */
557
558         {
559                 char *strtab;
560                 Elf32_Sym *symtab;
561                 int hn, si;
562                 int sf;
563                 int sn = 0;
564                 ElfW(Addr) sa;
565
566                 sa = 0;
567                 symtab = (Elf32_Sym *) (pelf->dynamic_info[DT_SYMTAB] + pelf->loadaddr);
568                 strtab = (char *) (pelf->dynamic_info[DT_STRTAB] + pelf->loadaddr);
569
570                 sf = 0;
571                 for (hn = 0; hn < pelf->nbucket; hn++) {
572                         for (si = pelf->elf_buckets[hn]; si; si = pelf->chains[si]) {
573                                 ElfW(Addr) symbol_addr;
574
575                                 symbol_addr = pelf->loadaddr + symtab[si].st_value;
576                                 if (symbol_addr <= (ElfW(Addr))__address && (!sf || sa < symbol_addr)) {
577                                         sa = symbol_addr;
578                                         sn = si;
579                                         sf = 1;
580                                 }
581 #if 0
582                                 fprintf(stderr, "Symbol \"%s\" at %x\n",
583                                                 strtab + symtab[si].st_name, symbol_addr);
584 #endif
585                         }
586                 }
587
588                 if (sf) {
589                         __dlip->dli_fname = pelf->libname;
590                         __dlip->dli_fbase = (void *)pelf->loadaddr;
591                         __dlip->dli_sname = strtab + symtab[sn].st_name;
592                         __dlip->dli_saddr = (void *)sa;
593                 }
594                 return 1;
595         }
596 }