OSDN Git Service

replace yet another _dl_malloc + _dl_memset with _dl_zalloc
[uclinux-h8/uClibc.git] / ldso / ldso / ldso.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) 2005 by Joakim Tjernlund
7  * Copyright (C) 2000-2006 by Erik Andersen <andersen@codepoet.org>
8  * Copyright (c) 1994-2000 Eric Youngdale, Peter MacDonald,
9  *                              David Engel, Hongjiu Lu and Mitch D'Souza
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. The name of the above contributors may not be
17  *    used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #include "ldso.h"
34 #include "unsecvars.h"
35
36 /* Pull in common debug code */
37 #include "dl-debug.c"
38
39 #define ALLOW_ZERO_PLTGOT
40
41 /* Pull in the value of _dl_progname */
42 #include LDSO_ELFINTERP
43
44 /* Global variables used within the shared library loader */
45 char *_dl_library_path         = NULL;  /* Where we look for libraries */
46 char *_dl_preload              = NULL;  /* Things to be loaded before the libs */
47 char *_dl_ldsopath             = NULL;  /* Location of the shared lib loader */
48 int _dl_errno                  = 0;     /* We can't use the real errno in ldso */
49 size_t _dl_pagesize            = 0;     /* Store the page size for use later */
50 struct r_debug *_dl_debug_addr = NULL;  /* Used to communicate with the gdb debugger */
51 void *(*_dl_malloc_function) (size_t size) = NULL;
52 void (*_dl_free_function) (void *p) = NULL;
53
54 static int _dl_secure = 1; /* Are we dealing with setuid stuff? */
55
56 #ifdef __SUPPORT_LD_DEBUG__
57 char *_dl_debug           = NULL;
58 char *_dl_debug_symbols   = NULL;
59 char *_dl_debug_move      = NULL;
60 char *_dl_debug_reloc     = NULL;
61 char *_dl_debug_detail    = NULL;
62 char *_dl_debug_nofixups  = NULL;
63 char *_dl_debug_bindings  = NULL;
64 int   _dl_debug_file      = 2;
65 #endif
66
67 /* Needed for standalone execution. */
68 unsigned long attribute_hidden _dl_skip_args = 0;
69 const char *_dl_progname = UCLIBC_LDSO;      /* The name of the executable being run */
70 #include "dl-startup.c"
71 #include "dl-symbols.c"
72 #include "dl-array.c"
73
74 /*
75  * This stub function is used by some debuggers.  The idea is that they
76  * can set an internal breakpoint on it, so that we are notified when the
77  * address mapping is changed in some way.
78  */
79 void _dl_debug_state(void);
80 rtld_hidden_proto(_dl_debug_state, noinline);
81 void _dl_debug_state(void)
82 {
83         /* Make sure GCC doesn't recognize this function as pure, to avoid
84          * having the calls optimized away.
85          */
86         __asm__("");
87 }
88 rtld_hidden_def(_dl_debug_state);
89
90 static unsigned char *_dl_malloc_addr = NULL;   /* Lets _dl_malloc use the already allocated memory page */
91 static unsigned char *_dl_mmap_zero   = NULL;   /* Also used by _dl_malloc */
92
93 static struct elf_resolve **init_fini_list;
94 static unsigned int nlist; /* # items in init_fini_list */
95 extern void _start(void);
96
97 #ifdef __UCLIBC_HAS_SSP__
98 # include <dl-osinfo.h>
99 uintptr_t stack_chk_guard;
100 # ifndef THREAD_SET_STACK_GUARD
101 /* Only exported for architectures that don't store the stack guard canary
102  * in local thread area.  */
103 uintptr_t __stack_chk_guard attribute_relro;
104 #  ifdef __UCLIBC_HAS_SSP_COMPAT__
105 strong_alias(__stack_chk_guard,__guard)
106 #  endif
107 # elif defined __UCLIBC_HAS_SSP_COMPAT__
108 uintptr_t __guard attribute_relro;
109 # endif
110 #endif
111
112 char *_dl_getenv(const char *symbol, char **envp)
113 {
114         char *pnt;
115         const char *pnt1;
116
117         while ((pnt = *envp++)) {
118                 pnt1 = symbol;
119                 while (*pnt && *pnt == *pnt1)
120                         pnt1++, pnt++;
121                 if (!*pnt || *pnt != '=' || *pnt1)
122                         continue;
123                 return pnt + 1;
124         }
125         return 0;
126 }
127
128 void _dl_unsetenv(const char *symbol, char **envp)
129 {
130         char *pnt;
131         const char *pnt1;
132         char **newenvp = envp;
133
134         for (pnt = *envp; pnt; pnt = *++envp) {
135                 pnt1 = symbol;
136                 while (*pnt && *pnt == *pnt1)
137                         pnt1++, pnt++;
138                 if (!*pnt || *pnt != '=' || *pnt1)
139                         *newenvp++ = *envp;
140         }
141         *newenvp++ = *envp;
142         return;
143 }
144
145 static int _dl_suid_ok(void)
146 {
147         __kernel_uid_t uid, euid;
148         __kernel_gid_t gid, egid;
149
150         uid = _dl_getuid();
151         euid = _dl_geteuid();
152         gid = _dl_getgid();
153         egid = _dl_getegid();
154
155         if (uid == euid && gid == egid) {
156                 return 1;
157         }
158         return 0;
159 }
160
161 void *_dl_malloc(size_t size)
162 {
163         void *retval;
164
165 #if 0
166         _dl_debug_early("request for %d bytes\n", size);
167 #endif
168
169         if (_dl_malloc_function)
170                 return (*_dl_malloc_function) (size);
171
172         if (_dl_malloc_addr - _dl_mmap_zero + size > _dl_pagesize) {
173                 size_t rounded_size;
174
175                 /* Since the above assumes we get a full page even if
176                    we request less than that, make sure we request a
177                    full page, since uClinux may give us less than than
178                    a full page.  We might round even
179                    larger-than-a-page sizes, but we end up never
180                    reusing _dl_mmap_zero/_dl_malloc_addr in that case,
181                    so we don't do it.
182
183                    The actual page size doesn't really matter; as long
184                    as we're self-consistent here, we're safe.  */
185                 if (size < _dl_pagesize)
186                         rounded_size = (size + ADDR_ALIGN) & _dl_pagesize;
187                 else
188                         rounded_size = size;
189
190                 _dl_debug_early("mmapping more memory\n");
191                 _dl_mmap_zero = _dl_malloc_addr = _dl_mmap((void *) 0, rounded_size,
192                                 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
193                 if (_dl_mmap_check_error(_dl_mmap_zero)) {
194                         _dl_dprintf(_dl_debug_file, "%s: mmap of a spare page failed!\n", _dl_progname);
195                         _dl_exit(20);
196                 }
197         }
198         retval = _dl_malloc_addr;
199         _dl_malloc_addr += size;
200
201         /*
202          * Align memory to DL_MALLOC_ALIGN byte boundary.  Some
203          * platforms require this, others simply get better
204          * performance.
205          */
206         _dl_malloc_addr = (unsigned char *) (((unsigned long) _dl_malloc_addr + DL_MALLOC_ALIGN - 1) & ~(DL_MALLOC_ALIGN - 1));
207         return retval;
208 }
209
210 static void *_dl_zalloc(size_t size)
211 {
212         void *p = _dl_malloc(size);
213         if (p)
214                 _dl_memset(p, 0, size);
215         return p;
216 }
217
218 void _dl_free (void *p)
219 {
220         if (_dl_free_function)
221                 (*_dl_free_function) (p);
222 }
223
224 static void __attribute__ ((destructor)) __attribute_used__ _dl_fini(void)
225 {
226         unsigned int i;
227         struct elf_resolve * tpnt;
228
229         for (i = 0; i < nlist; ++i) {
230                 tpnt = init_fini_list[i];
231                 if (tpnt->init_flag & FINI_FUNCS_CALLED)
232                         continue;
233                 tpnt->init_flag |= FINI_FUNCS_CALLED;
234                 _dl_run_fini_array(tpnt);
235                 if (tpnt->dynamic_info[DT_FINI]) {
236                         void (*dl_elf_func) (void);
237
238                         dl_elf_func = (void (*)(void)) (intptr_t) DL_RELOC_ADDR(tpnt->loadaddr, tpnt->dynamic_info[DT_FINI]);
239                         _dl_if_debug_dprint("\ncalling FINI: %s\n\n", tpnt->libname);
240                         DL_CALL_FUNC_AT_ADDR (dl_elf_func, tpnt->loadaddr, (void(*)(void)));
241                 }
242         }
243 }
244
245 void _dl_get_ready_to_run(struct elf_resolve *tpnt, DL_LOADADDR_TYPE load_addr,
246                           ElfW(auxv_t) auxvt[AT_EGID + 1], char **envp,
247                           char **argv
248                           DL_GET_READY_TO_RUN_EXTRA_PARMS)
249 {
250         ElfW(Addr) app_mapaddr = 0;
251         ElfW(Phdr) *ppnt;
252         ElfW(Dyn) *dpnt;
253         char *lpntstr;
254         unsigned int i;
255         int unlazy = 0, trace_loaded_objects = 0;
256         struct dyn_elf *rpnt;
257         struct elf_resolve *tcurr;
258         struct elf_resolve *tpnt1;
259         struct elf_resolve app_tpnt_tmp;
260         struct elf_resolve *app_tpnt = &app_tpnt_tmp;
261         struct r_debug *debug_addr;
262         unsigned long *lpnt;
263         unsigned long *_dl_envp;                /* The environment address */
264         ElfW(Addr) relro_addr = 0;
265         size_t relro_size = 0;
266         struct stat st;
267
268         /* Wahoo!!! We managed to make a function call!  Get malloc
269          * setup so we can use _dl_dprintf() to print debug noise
270          * instead of the SEND_STDERR macros used in dl-startup.c */
271
272         _dl_memset(app_tpnt, 0, sizeof(*app_tpnt));
273
274         /* Store the page size for later use */
275         _dl_pagesize = (auxvt[AT_PAGESZ].a_un.a_val) ? (size_t) auxvt[AT_PAGESZ].a_un.a_val : PAGE_SIZE;
276         /* Make it so _dl_malloc can use the page of memory we have already
277          * allocated.  We shouldn't need to grab any more memory.  This must
278          * be first since things like _dl_dprintf() use _dl_malloc()...
279          */
280         _dl_malloc_addr = (unsigned char *)_dl_pagesize;
281         _dl_mmap_zero = 0;
282
283         /* Wahoo!!! */
284         _dl_debug_early("Cool, ldso survived making function calls\n");
285
286         /* Now we have done the mandatory linking of some things.  We are now
287          * free to start using global variables, since these things have all
288          * been fixed up by now.  Still no function calls outside of this
289          * library, since the dynamic resolver is not yet ready.
290          */
291         if (argv[0]) {
292                 _dl_progname = argv[0];
293         }
294
295         if (_start == (void *) auxvt[AT_ENTRY].a_un.a_val) {
296                 _dl_dprintf(_dl_debug_file, "Standalone execution is not supported yet\n");
297                 _dl_exit(1);
298         }
299
300         /* Start to build the tables of the modules that are required for
301          * this beast to run.  We start with the basic executable, and then
302          * go from there.  Eventually we will run across ourself, and we
303          * will need to properly deal with that as well.
304          */
305         rpnt = NULL;
306         if (_dl_getenv("LD_BIND_NOW", envp))
307                 unlazy = RTLD_NOW;
308
309         /* Now we need to figure out what kind of options are selected.
310          * Note that for SUID programs we ignore the settings in
311          * LD_LIBRARY_PATH.
312          */
313         if ((auxvt[AT_UID].a_un.a_val == (size_t)-1 && _dl_suid_ok()) ||
314             (auxvt[AT_UID].a_un.a_val != (size_t)-1 &&
315              auxvt[AT_UID].a_un.a_val == auxvt[AT_EUID].a_un.a_val &&
316              auxvt[AT_GID].a_un.a_val == auxvt[AT_EGID].a_un.a_val)) {
317                 _dl_secure = 0;
318                 _dl_preload = _dl_getenv("LD_PRELOAD", envp);
319                 _dl_library_path = _dl_getenv("LD_LIBRARY_PATH", envp);
320         } else {
321                 static const char unsecure_envvars[] =
322 #ifdef EXTRA_UNSECURE_ENVVARS
323                         EXTRA_UNSECURE_ENVVARS
324 #endif
325                         UNSECURE_ENVVARS;
326                 const char *nextp;
327                 _dl_secure = 1;
328
329                 nextp = unsecure_envvars;
330                 do {
331                         _dl_unsetenv (nextp, envp);
332                         /* We could use rawmemchr but this need not be fast.  */
333                         nextp = _dl_strchr(nextp, '\0') + 1;
334                 } while (*nextp != '\0');
335                 _dl_preload = NULL;
336                 _dl_library_path = NULL;
337                 /* SUID binaries can be exploited if they do LAZY relocation. */
338                 unlazy = RTLD_NOW;
339         }
340
341         /* sjhill: your TLS init should go before this */
342 #ifdef __UCLIBC_HAS_SSP__
343         /* Set up the stack checker's canary.  */
344         stack_chk_guard = _dl_setup_stack_chk_guard ();
345 # ifdef THREAD_SET_STACK_GUARD
346         THREAD_SET_STACK_GUARD (stack_chk_guard);
347 #  ifdef __UCLIBC_HAS_SSP_COMPAT__
348         __guard = stack_chk_guard;
349 #  endif
350 # else
351         __stack_chk_guard = stack_chk_guard;
352 # endif
353 #endif
354
355         /* At this point we are now free to examine the user application,
356          * and figure out which libraries are supposed to be called.  Until
357          * we have this list, we will not be completely ready for dynamic
358          * linking.
359          */
360
361         /* Find the runtime load address of the main executable.  This may be
362          * different from what the ELF header says for ET_DYN/PIE executables.
363          */
364         {
365                 unsigned int idx;
366                 ElfW(Phdr) *phdr = (ElfW(Phdr) *) auxvt[AT_PHDR].a_un.a_val;
367
368                 for (idx = 0; idx < auxvt[AT_PHNUM].a_un.a_val; idx++, phdr++)
369                         if (phdr->p_type == PT_PHDR) {
370                                 DL_INIT_LOADADDR_PROG(app_tpnt->loadaddr, auxvt[AT_PHDR].a_un.a_val - phdr->p_vaddr);
371                                 break;
372                         }
373
374                 if (DL_LOADADDR_BASE(app_tpnt->loadaddr))
375                         _dl_debug_early("Position Independent Executable: "
376                                         "app_tpnt->loadaddr=%x\n", DL_LOADADDR_BASE(app_tpnt->loadaddr));
377         }
378
379         /*
380          * This is used by gdb to locate the chain of shared libraries that are
381          * currently loaded.
382          */
383         debug_addr = _dl_zalloc(sizeof(struct r_debug));
384
385         ppnt = (ElfW(Phdr) *) auxvt[AT_PHDR].a_un.a_val;
386         for (i = 0; i < auxvt[AT_PHNUM].a_un.a_val; i++, ppnt++) {
387                 if (ppnt->p_type == PT_GNU_RELRO) {
388                         relro_addr = ppnt->p_vaddr;
389                         relro_size = ppnt->p_memsz;
390                 }
391                 if (!app_mapaddr && (ppnt->p_type == PT_LOAD)) {
392                         app_mapaddr = DL_RELOC_ADDR (app_tpnt->loadaddr, ppnt->p_vaddr);
393                 }
394                 if (ppnt->p_type == PT_DYNAMIC) {
395                         dpnt = (ElfW(Dyn) *) DL_RELOC_ADDR(app_tpnt->loadaddr, ppnt->p_vaddr);
396                         _dl_parse_dynamic_info(dpnt, app_tpnt->dynamic_info, debug_addr, app_tpnt->loadaddr);
397 #ifndef __FORCE_SHAREABLE_TEXT_SEGMENTS__
398                         /* Ugly, ugly.  We need to call mprotect to change the
399                          * protection of the text pages so that we can do the
400                          * dynamic linking.  We can set the protection back
401                          * again once we are done.
402                          */
403                         _dl_debug_early("calling mprotect on the application program\n");
404                         /* Now cover the application program. */
405                         if (app_tpnt->dynamic_info[DT_TEXTREL]) {
406                                 ElfW(Phdr) *ppnt_outer = ppnt;
407                                 ppnt = (ElfW(Phdr) *) auxvt[AT_PHDR].a_un.a_val;
408                                 for (i = 0; i < auxvt[AT_PHNUM].a_un.a_val; i++, ppnt++) {
409                                         if (ppnt->p_type == PT_LOAD && !(ppnt->p_flags & PF_W))
410                                                 _dl_mprotect((void *) (DL_RELOC_ADDR(app_tpnt->loadaddr, ppnt->p_vaddr) & PAGE_ALIGN),
411                                                              ((ppnt->p_vaddr + app_tpnt->loadaddr) & ADDR_ALIGN) +
412                                                              (unsigned long) ppnt->p_filesz,
413                                                              PROT_READ | PROT_WRITE | PROT_EXEC);
414                                 }
415                                 ppnt = ppnt_outer;
416                         }
417 #else
418                         if (app_tpnt->dynamic_info[DT_TEXTREL]) {
419                                 _dl_dprintf(_dl_debug_file, "Can't modify application's text section; use the GCC option -fPIE for position-independent executables.\n");
420                                 _dl_exit(1);
421                         }
422 #endif
423
424 #ifndef ALLOW_ZERO_PLTGOT
425                         /* make sure it's really there. */
426                         if (app_tpnt->dynamic_info[DT_PLTGOT] == 0)
427                                 continue;
428 #endif
429                         /* OK, we have what we need - slip this one into the list. */
430                         app_tpnt = _dl_add_elf_hash_table(_dl_progname, app_tpnt->loadaddr,
431                                         app_tpnt->dynamic_info,
432                                         (unsigned long) DL_RELOC_ADDR(app_tpnt->loadaddr, ppnt->p_vaddr),
433                                         ppnt->p_filesz);
434                         _dl_loaded_modules->libtype = elf_executable;
435                         _dl_loaded_modules->ppnt = (ElfW(Phdr) *) auxvt[AT_PHDR].a_un.a_val;
436                         _dl_loaded_modules->n_phent = auxvt[AT_PHNUM].a_un.a_val;
437                         _dl_symbol_tables = rpnt = _dl_zalloc(sizeof(struct dyn_elf));
438                         rpnt->dyn = _dl_loaded_modules;
439                         app_tpnt->mapaddr = app_mapaddr;
440                         app_tpnt->rtld_flags = unlazy | RTLD_GLOBAL;
441                         app_tpnt->usage_count++;
442                         app_tpnt->symbol_scope = _dl_symbol_tables;
443                         lpnt = (unsigned long *) (app_tpnt->dynamic_info[DT_PLTGOT]);
444 #ifdef ALLOW_ZERO_PLTGOT
445                         if (lpnt)
446 #endif
447                                 INIT_GOT(lpnt, _dl_loaded_modules);
448                 }
449
450                 /* OK, fill this in - we did not have this before */
451                 if (ppnt->p_type == PT_INTERP) {
452                         char *ptmp;
453
454                         tpnt->libname = (char *) DL_RELOC_ADDR(app_tpnt->loadaddr, ppnt->p_vaddr);
455
456                         /* Store the path where the shared lib loader was found
457                          * for later use
458                          */
459                         _dl_ldsopath = _dl_strdup(tpnt->libname);
460                         ptmp = _dl_strrchr(_dl_ldsopath, '/');
461                         if (ptmp != _dl_ldsopath)
462                                 *ptmp = '\0';
463
464                         _dl_debug_early("Lib Loader: (%x) %s\n", (unsigned) DL_LOADADDR_BASE(tpnt->loadaddr), tpnt->libname);
465                 }
466         }
467         app_tpnt->relro_addr = relro_addr;
468         app_tpnt->relro_size = relro_size;
469
470 #ifdef __SUPPORT_LD_DEBUG__
471         _dl_debug = _dl_getenv("LD_DEBUG", envp);
472         if (_dl_debug) {
473                 if (_dl_strstr(_dl_debug, "all")) {
474                         _dl_debug_detail = _dl_debug_move = _dl_debug_symbols
475                                 = _dl_debug_reloc = _dl_debug_bindings = _dl_debug_nofixups = (void*)1;
476                 } else {
477                         _dl_debug_detail   = _dl_strstr(_dl_debug, "detail");
478                         _dl_debug_move     = _dl_strstr(_dl_debug, "move");
479                         _dl_debug_symbols  = _dl_strstr(_dl_debug, "sym");
480                         _dl_debug_reloc    = _dl_strstr(_dl_debug, "reloc");
481                         _dl_debug_nofixups = _dl_strstr(_dl_debug, "nofix");
482                         _dl_debug_bindings = _dl_strstr(_dl_debug, "bind");
483                 }
484         }
485
486         {
487                 const char *dl_debug_output;
488
489                 dl_debug_output = _dl_getenv("LD_DEBUG_OUTPUT", envp);
490
491                 if (dl_debug_output) {
492                         char tmp[22], *tmp1, *filename;
493                         int len1, len2;
494
495                         _dl_memset(tmp, 0, sizeof(tmp));
496                         tmp1 = _dl_simple_ltoa( tmp, (unsigned long)_dl_getpid());
497
498                         len1 = _dl_strlen(dl_debug_output);
499                         len2 = _dl_strlen(tmp1);
500
501                         filename = _dl_malloc(len1 + len2 + 2);
502
503                         if (filename) {
504                                 _dl_strcpy (filename, dl_debug_output);
505                                 filename[len1] = '.';
506                                 _dl_strcpy (&filename[len1+1], tmp1);
507
508                                 _dl_debug_file = _dl_open(filename, O_WRONLY|O_CREAT, 0644);
509                                 if (_dl_debug_file < 0) {
510                                         _dl_debug_file = 2;
511                                         _dl_dprintf(_dl_debug_file, "can't open file: '%s'\n",filename);
512                                 }
513                         }
514                 }
515         }
516 #endif
517
518         if (_dl_getenv("LD_TRACE_LOADED_OBJECTS", envp) != NULL) {
519                 trace_loaded_objects++;
520         }
521
522 #ifndef __LDSO_LDD_SUPPORT__
523         if (trace_loaded_objects) {
524                 _dl_dprintf(_dl_debug_file, "Use the ldd provided by uClibc\n");
525                 _dl_exit(1);
526         }
527 #endif
528
529         /*
530          * OK, fix one more thing - set up debug_addr so it will point
531          * to our chain.  Later we may need to fill in more fields, but this
532          * should be enough for now.
533          */
534         debug_addr->r_map = (struct link_map *) _dl_loaded_modules;
535         debug_addr->r_version = 1;
536         debug_addr->r_ldbase = DL_LOADADDR_BASE(load_addr);
537         debug_addr->r_brk = (unsigned long) &_dl_debug_state;
538         _dl_debug_addr = debug_addr;
539
540         /* Do not notify the debugger until the interpreter is in the list */
541
542         /* OK, we now have the application in the list, and we have some
543          * basic stuff in place.  Now search through the list for other shared
544          * libraries that should be loaded, and insert them on the list in the
545          * correct order.
546          */
547
548         _dl_map_cache();
549
550         if (_dl_preload) {
551                 char c, *str, *str2;
552
553                 str = _dl_preload;
554                 while (*str == ':' || *str == ' ' || *str == '\t')
555                         str++;
556
557                 while (*str) {
558                         str2 = str;
559                         while (*str2 && *str2 != ':' && *str2 != ' ' && *str2 != '\t')
560                                 str2++;
561                         c = *str2;
562                         *str2 = '\0';
563
564                         if (!_dl_secure || _dl_strchr(str, '/') == NULL) {
565                                 _dl_if_debug_dprint("\tfile='%s';  needed by '%s'\n", str, _dl_progname);
566
567                                 tpnt1 = _dl_load_shared_library(_dl_secure, &rpnt, NULL, str, trace_loaded_objects);
568                                 if (!tpnt1) {
569 #ifdef __LDSO_LDD_SUPPORT__
570                                         if (trace_loaded_objects)
571                                                 _dl_dprintf(1, "\t%s => not found\n", str);
572                                         else
573 #endif
574                                         {
575                                                 _dl_dprintf(_dl_debug_file, "%s: can't load " "library '%s'\n", _dl_progname, str);
576                                                 _dl_exit(15);
577                                         }
578                                 } else {
579                                         tpnt1->rtld_flags = unlazy | RTLD_GLOBAL;
580
581                                         _dl_debug_early("Loading: (%x) %s\n", DL_LOADADDR_BASE(tpnt1->loadaddr), tpnt1->libname);
582
583 #ifdef __LDSO_LDD_SUPPORT__
584                                         if (trace_loaded_objects &&
585                                             tpnt1->usage_count == 1) {
586                                                 /* This is a real hack to make
587                                                  * ldd not print the library
588                                                  * itself when run on a
589                                                  * library.
590                                                  */
591                                                 if (_dl_strcmp(_dl_progname, str) != 0)
592                                                         _dl_dprintf(1, "\t%s => %s (%x)\n", str, tpnt1->libname,
593                                                                     DL_LOADADDR_BASE(tpnt1->loadaddr));
594                                         }
595 #endif
596                                 }
597                         }
598
599                         *str2 = c;
600                         str = str2;
601                         while (*str == ':' || *str == ' ' || *str == '\t')
602                                 str++;
603                 }
604         }
605
606 #ifdef __LDSO_PRELOAD_FILE_SUPPORT__
607         do {
608                 char *preload;
609                 int fd;
610                 char c, *cp, *cp2;
611
612                 if (_dl_stat(LDSO_PRELOAD, &st) || st.st_size == 0) {
613                         break;
614                 }
615
616                 if ((fd = _dl_open(LDSO_PRELOAD, O_RDONLY, 0)) < 0) {
617                         _dl_dprintf(_dl_debug_file, "%s: can't open file '%s'\n",
618                                     _dl_progname, LDSO_PRELOAD);
619                         break;
620                 }
621
622                 preload = (caddr_t) _dl_mmap(0, st.st_size + 1,
623                                              PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
624                 _dl_close(fd);
625                 if (preload == (caddr_t) -1) {
626                         _dl_dprintf(_dl_debug_file, "%s:%i: can't map '%s'\n",
627                                     _dl_progname, __LINE__, LDSO_PRELOAD);
628                         break;
629                 }
630
631                 /* convert all separators and comments to spaces */
632                 for (cp = preload; *cp; /*nada */ ) {
633                         if (*cp == ':' || *cp == '\t' || *cp == '\n') {
634                                 *cp++ = ' ';
635                         } else if (*cp == '#') {
636                                 do {
637                                         *cp++ = ' ';
638                                 } while (*cp != '\n' && *cp != '\0');
639                         } else {
640                                 cp++;
641                         }
642                 }
643
644                 /* find start of first library */
645                 for (cp = preload; *cp && *cp == ' '; cp++)
646                         /*nada */ ;
647
648                 while (*cp) {
649                         /* find end of library */
650                         for (cp2 = cp; *cp && *cp != ' '; cp++)
651                                 /*nada */ ;
652                         c = *cp;
653                         *cp = '\0';
654
655                         _dl_if_debug_dprint("\tfile='%s';  needed by '%s'\n", cp2, _dl_progname);
656
657                         tpnt1 = _dl_load_shared_library(0, &rpnt, NULL, cp2, trace_loaded_objects);
658                         if (!tpnt1) {
659 #ifdef __LDSO_LDD_SUPPORT__
660                                 if (trace_loaded_objects)
661                                         _dl_dprintf(1, "\t%s => not found\n", cp2);
662                                 else
663 #endif
664                                 {
665                                         _dl_dprintf(_dl_debug_file, "%s: can't load library '%s'\n", _dl_progname, cp2);
666                                         _dl_exit(15);
667                                 }
668                         } else {
669                                 tpnt1->rtld_flags = unlazy | RTLD_GLOBAL;
670
671                                 _dl_debug_early("Loading: (%x) %s\n", DL_LOADADDR_BASE(tpnt1->loadaddr), tpnt1->libname);
672
673 #ifdef __LDSO_LDD_SUPPORT__
674                                 if (trace_loaded_objects &&
675                                     tpnt1->usage_count == 1) {
676                                         _dl_dprintf(1, "\t%s => %s (%x)\n",
677                                                     cp2, tpnt1->libname,
678                                                     DL_LOADADDR_BASE(tpnt1->loadaddr));
679                                 }
680 #endif
681                         }
682
683                         /* find start of next library */
684                         *cp = c;
685                         for ( /*nada */ ; *cp && *cp == ' '; cp++)
686                                 /*nada */ ;
687                 }
688
689                 _dl_munmap(preload, st.st_size + 1);
690         } while (0);
691 #endif /* __LDSO_PRELOAD_FILE_SUPPORT__ */
692
693         nlist = 0;
694         for (tcurr = _dl_loaded_modules; tcurr; tcurr = tcurr->next) {
695                 ElfW(Dyn) *this_dpnt;
696
697                 nlist++;
698                 for (this_dpnt = (ElfW(Dyn) *) tcurr->dynamic_addr; this_dpnt->d_tag; this_dpnt++) {
699                         if (this_dpnt->d_tag == DT_NEEDED) {
700                                 char *name;
701                                 struct init_fini_list *tmp;
702
703                                 lpntstr = (char*) (tcurr->dynamic_info[DT_STRTAB] + this_dpnt->d_un.d_val);
704                                 name = _dl_get_last_path_component(lpntstr);
705                                 if (_dl_strcmp(name, UCLIBC_LDSO) == 0)
706                                         continue;
707
708                                 _dl_if_debug_dprint("\tfile='%s';  needed by '%s'\n", lpntstr, _dl_progname);
709
710                                 if (!(tpnt1 = _dl_load_shared_library(0, &rpnt, tcurr, lpntstr, trace_loaded_objects))) {
711 #ifdef __LDSO_LDD_SUPPORT__
712                                         if (trace_loaded_objects) {
713                                                 _dl_dprintf(1, "\t%s => not found\n", lpntstr);
714                                                 continue;
715                                         } else
716 #endif
717                                         {
718                                                 _dl_dprintf(_dl_debug_file, "%s: can't load library '%s'\n", _dl_progname, lpntstr);
719                                                 _dl_exit(16);
720                                         }
721                                 }
722
723                                 tmp = alloca(sizeof(struct init_fini_list)); /* Allocates on stack, no need to free this memory */
724                                 tmp->tpnt = tpnt1;
725                                 tmp->next = tcurr->init_fini;
726                                 tcurr->init_fini = tmp;
727
728                                 tpnt1->rtld_flags = unlazy | RTLD_GLOBAL;
729
730                                 _dl_debug_early("Loading: (%x) %s\n", DL_LOADADDR_BASE(tpnt1->loadaddr), tpnt1->libname);
731
732 #ifdef __LDSO_LDD_SUPPORT__
733                                 if (trace_loaded_objects &&
734                                     tpnt1->usage_count == 1) {
735                                         _dl_dprintf(1, "\t%s => %s (%x)\n",
736                                                     lpntstr, tpnt1->libname,
737                                                     DL_LOADADDR_BASE(tpnt1->loadaddr));
738                                 }
739 #endif
740                         }
741                 }
742         }
743         _dl_unmap_cache();
744
745         --nlist; /* Exclude the application. */
746         init_fini_list = _dl_malloc(nlist * sizeof(struct elf_resolve *));
747         i = 0;
748         for (tcurr = _dl_loaded_modules->next; tcurr; tcurr = tcurr->next) {
749                 init_fini_list[i++] = tcurr;
750         }
751
752         /* Sort the INIT/FINI list in dependency order. */
753         for (tcurr = _dl_loaded_modules->next; tcurr; tcurr = tcurr->next) {
754                 unsigned int j, k;
755
756                 for (j = 0; init_fini_list[j] != tcurr; ++j)
757                         /* Empty */;
758                 for (k = j + 1; k < nlist; ++k) {
759                         struct init_fini_list *runp = init_fini_list[k]->init_fini;
760
761                         for (; runp; runp = runp->next) {
762                                 if (runp->tpnt == tcurr) {
763                                         struct elf_resolve *here = init_fini_list[k];
764                                         _dl_if_debug_dprint("Move %s from pos %d to %d in INIT/FINI list\n", here->libname, k, j);
765                                         for (i = (k - j); i; --i)
766                                                 init_fini_list[i+j] = init_fini_list[i+j-1];
767                                         init_fini_list[j] = here;
768                                         ++j;
769                                         break;
770                                 }
771                         }
772                 }
773         }
774 #ifdef __SUPPORT_LD_DEBUG__
775         if (_dl_debug) {
776                 _dl_dprintf(_dl_debug_file, "\nINIT/FINI order and dependencies:\n");
777                 for (i = 0; i < nlist; i++) {
778                         struct init_fini_list *tmp;
779
780                         _dl_dprintf(_dl_debug_file, "lib: %s has deps:\n",
781                                     init_fini_list[i]->libname);
782                         tmp = init_fini_list[i]->init_fini;
783                         for (; tmp; tmp = tmp->next)
784                                 _dl_dprintf(_dl_debug_file, " %s ", tmp->tpnt->libname);
785                         _dl_dprintf(_dl_debug_file, "\n");
786                 }
787         }
788 #endif
789
790         /*
791          * If the program interpreter is not in the module chain, add it.
792          * This will be required for dlopen to be able to access the internal
793          * functions in the dynamic linker and to relocate the interpreter
794          * again once all libs are loaded.
795          */
796         if (tpnt) {
797                 ElfW(Ehdr) *epnt = (ElfW(Ehdr) *) auxvt[AT_BASE].a_un.a_val;
798                 ElfW(Phdr) *myppnt = (ElfW(Phdr) *) DL_RELOC_ADDR(load_addr, epnt->e_phoff);
799                 int j;
800
801                 tpnt = _dl_add_elf_hash_table(tpnt->libname, load_addr,
802                                               tpnt->dynamic_info,
803                                               (unsigned long)tpnt->dynamic_addr,
804                                               0);
805
806                 if (_dl_stat(tpnt->libname, &st) >= 0) {
807                         tpnt->st_dev = st.st_dev;
808                         tpnt->st_ino = st.st_ino;
809                 }
810                 tpnt->n_phent = epnt->e_phnum;
811                 tpnt->ppnt = myppnt;
812                 for (j = 0; j < epnt->e_phnum; j++, myppnt++) {
813                         if (myppnt->p_type ==  PT_GNU_RELRO) {
814                                 tpnt->relro_addr = myppnt->p_vaddr;
815                                 tpnt->relro_size = myppnt->p_memsz;
816                                 break;
817                         }
818                 }
819                 tpnt->libtype = program_interpreter;
820                 tpnt->usage_count++;
821                 tpnt->symbol_scope = _dl_symbol_tables;
822                 if (rpnt) {
823                         rpnt->next = _dl_zalloc(sizeof(struct dyn_elf));
824                         rpnt->next->prev = rpnt;
825                         rpnt = rpnt->next;
826                 } else {
827                         rpnt = _dl_zalloc(sizeof(struct dyn_elf));
828                 }
829                 rpnt->dyn = tpnt;
830                 tpnt->rtld_flags = RTLD_NOW | RTLD_GLOBAL; /* Must not be LAZY */
831 #ifdef RERELOCATE_LDSO
832                 /* Only rerelocate functions for now. */
833                 tpnt->init_flag = RELOCS_DONE;
834                 lpnt = (unsigned long *) (tpnt->dynamic_info[DT_PLTGOT]);
835 # ifdef ALLOW_ZERO_PLTGOT
836                 if (tpnt->dynamic_info[DT_PLTGOT])
837 # endif
838                         INIT_GOT(lpnt, tpnt);
839 #else
840                 tpnt->init_flag = RELOCS_DONE | JMP_RELOCS_DONE;
841 #endif
842                 tpnt = NULL;
843         }
844
845 #ifdef __LDSO_LDD_SUPPORT__
846         /* End of the line for ldd.... */
847         if (trace_loaded_objects) {
848                 _dl_dprintf(1, "\t%s => %s (%x)\n",
849                             rpnt->dyn->libname + _dl_strlen(_dl_ldsopath) + 1,
850                             rpnt->dyn->libname, DL_LOADADDR_BASE(rpnt->dyn->loadaddr));
851                 _dl_exit(0);
852         }
853 #endif
854
855         _dl_debug_early("Beginning relocation fixups\n");
856
857 #ifdef __mips__
858         /*
859          * Relocation of the GOT entries for MIPS have to be done
860          * after all the libraries have been loaded.
861          */
862         _dl_perform_mips_global_got_relocations(_dl_loaded_modules, !unlazy);
863 #endif
864
865         /*
866          * OK, now all of the kids are tucked into bed in their proper
867          * addresses.  Now we go through and look for REL and RELA records that
868          * indicate fixups to the GOT tables.  We need to do this in reverse
869          * order so that COPY directives work correctly.
870          */
871         if (_dl_symbol_tables)
872                 if (_dl_fixup(_dl_symbol_tables, unlazy))
873                         _dl_exit(-1);
874
875         for (tpnt = _dl_loaded_modules; tpnt; tpnt = tpnt->next) {
876                 if (tpnt->relro_size)
877                         _dl_protect_relro (tpnt);
878         }
879
880         /* OK, at this point things are pretty much ready to run.  Now we need
881          * to touch up a few items that are required, and then we can let the
882          * user application have at it.  Note that the dynamic linker itself
883          * is not guaranteed to be fully dynamicly linked if we are using
884          * ld.so.1, so we have to look up each symbol individually.
885          */
886
887         _dl_envp = (unsigned long *) (intptr_t) _dl_find_hash(__C_SYMBOL_PREFIX__ "__environ", _dl_symbol_tables, NULL, 0);
888         if (_dl_envp)
889                 *_dl_envp = (unsigned long) envp;
890
891 #ifndef __FORCE_SHAREABLE_TEXT_SEGMENTS__
892         {
893                 unsigned int j;
894                 ElfW(Phdr) *myppnt;
895
896                 /* We had to set the protections of all pages to R/W for
897                  * dynamic linking.  Set text pages back to R/O.
898                  */
899                 for (tpnt = _dl_loaded_modules; tpnt; tpnt = tpnt->next) {
900                         for (myppnt = tpnt->ppnt, j = 0; j < tpnt->n_phent; j++, myppnt++) {
901                                 if (myppnt->p_type == PT_LOAD && !(myppnt->p_flags & PF_W) && tpnt->dynamic_info[DT_TEXTREL]) {
902                                         _dl_mprotect((void *) (DL_RELOC_ADDR(tpnt->loadaddr, myppnt->p_vaddr) & PAGE_ALIGN),
903                                                         (myppnt->p_vaddr & ADDR_ALIGN) + (unsigned long) myppnt->p_filesz, LXFLAGS(myppnt->p_flags));
904                                 }
905                         }
906                 }
907
908         }
909 #endif
910         /* Notify the debugger we have added some objects. */
911         _dl_debug_addr->r_state = RT_ADD;
912         _dl_debug_state();
913
914         /* Run pre-initialization functions for the executable.  */
915         _dl_run_array_forward(_dl_loaded_modules->dynamic_info[DT_PREINIT_ARRAY],
916                               _dl_loaded_modules->dynamic_info[DT_PREINIT_ARRAYSZ],
917                               _dl_loaded_modules->loadaddr);
918
919         /* Run initialization functions for loaded objects.  For the
920            main executable, they will be run from __uClibc_main.  */
921         for (i = nlist; i; --i) {
922                 tpnt = init_fini_list[i-1];
923                 tpnt->init_fini = NULL; /* Clear, since alloca was used */
924                 if (tpnt->init_flag & INIT_FUNCS_CALLED)
925                         continue;
926                 tpnt->init_flag |= INIT_FUNCS_CALLED;
927
928                 if (tpnt->dynamic_info[DT_INIT]) {
929                         void (*dl_elf_func) (void);
930
931                         dl_elf_func = (void (*)(void)) DL_RELOC_ADDR(tpnt->loadaddr, tpnt->dynamic_info[DT_INIT]);
932
933                         _dl_if_debug_dprint("calling INIT: %s\n\n", tpnt->libname);
934
935                         DL_CALL_FUNC_AT_ADDR (dl_elf_func, tpnt->loadaddr, (void(*)(void)));
936                 }
937
938                 _dl_run_init_array(tpnt);
939         }
940
941         /* Find the real malloc function and make ldso functions use that from now on */
942         _dl_malloc_function = (void* (*)(size_t)) (intptr_t) _dl_find_hash(__C_SYMBOL_PREFIX__ "malloc",
943                         _dl_symbol_tables, NULL, ELF_RTYPE_CLASS_PLT);
944
945         /* Notify the debugger that all objects are now mapped in.  */
946         _dl_debug_addr->r_state = RT_CONSISTENT;
947         _dl_debug_state();
948 }
949
950 #include "dl-hash.c"
951 #include "dl-elf.c"