]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/uclibc/lib/contrib/uclibc/ldso/ldso/dl-startup.c
update
[l4.git] / l4 / pkg / uclibc / lib / contrib / uclibc / ldso / ldso / dl-startup.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 /*
34  * The main trick with this program is that initially, we ourselves are not
35  * dynamicly linked.  This means that we cannot access any global variables or
36  * call any functions.  No globals initially, since the Global Offset Table
37  * (GOT) is initialized by the linker assuming a virtual address of 0, and no
38  * function calls initially since the Procedure Linkage Table (PLT) is not yet
39  * initialized.
40  *
41  * There are additional initial restrictions - we cannot use large switch
42  * statements, since the compiler generates tables of addresses and jumps
43  * through them.  We cannot use normal syscall stubs, because these all
44  * reference the errno global variable which is not yet initialized.  We _can_
45  * use all of the local stack variables that we want.  We _can_ use inline
46  * functions, because these do not transfer control to a new address, but they
47  * must be static so that they are not exported from the modules.
48  *
49  * Life is further complicated by the fact that initially we do not want to do
50  * a complete dynamic linking.  We want to allow the user to supply new
51  * functions to override symbols (i.e. weak symbols and/or LD_PRELOAD).  So
52  * initially, we only perform relocations for variables that start with "_dl_"
53  * since ANSI specifies that the user is not supposed to redefine any of these
54  * variables.
55  *
56  * Fortunately, the linker itself leaves a few clues lying around, and when the
57  * kernel starts the image, there are a few further clues.  First of all, there
58  * is Auxiliary Vector Table information sitting on which is provided to us by
59  * the kernel, and which includes information about the load address that the
60  * program interpreter was loaded at, the number of sections, the address the
61  * application was loaded at and so forth.  Here this information is stored in
62  * the array auxvt.  For details see linux/fs/binfmt_elf.c where it calls
63  * NEW_AUX_ENT() a bunch of time....
64  *
65  * Next, we need to find the GOT.  On most arches there is a register pointing
66  * to the GOT, but just in case (and for new ports) I've added some (slow) C
67  * code to locate the GOT for you.
68  *
69  * This code was originally written for SVr4, and there the kernel would load
70  * all text pages R/O, so they needed to call mprotect a zillion times to mark
71  * all text pages as writable so dynamic linking would succeed.  Then when they
72  * were done, they would change the protections for all the pages back again.
73  * Well, under Linux everything is loaded writable (since Linux does copy on
74  * write anyways) so all the mprotect stuff has been disabled.
75  *
76  * Initially, we do not have access to _dl_malloc since we can't yet make
77  * function calls, so we mmap one page to use as scratch space.  Later on, when
78  * we can call _dl_malloc we reuse this this memory.  This is also beneficial,
79  * since we do not want to use the same memory pool as malloc anyway - esp if
80  * the user redefines malloc to do something funky.
81  *
82  * Our first task is to perform a minimal linking so that we can call other
83  * portions of the dynamic linker.  Once we have done this, we then build the
84  * list of modules that the application requires, using LD_LIBRARY_PATH if this
85  * is not a suid program (/usr/lib otherwise).  Once this is done, we can do
86  * the dynamic linking as required, and we must omit the things we did to get
87  * the dynamic linker up and running in the first place.  After we have done
88  * this, we just have a few housekeeping chores and we can transfer control to
89  * the user's application.
90  */
91
92 #include "ldso.h"
93
94 /* Pull in all the arch specific stuff */
95 #include "dl-startup.h"
96
97 /* Static declarations */
98 static int (*_dl_elf_main) (int, char **, char **);
99
100 static void* __rtld_stack_end; /* Points to argc on stack, e.g *((long *)__rtld_stackend) == argc */
101 strong_alias(__rtld_stack_end, __libc_stack_end) /* Exported version of __rtld_stack_end */
102
103 #ifndef __NOT_FOR_L4__
104 attribute_hidden void *__rtld_l4re_global_env;
105 strong_alias(__rtld_l4re_global_env, l4re_global_env)
106 #endif
107
108 /* When we enter this piece of code, the program stack looks like this:
109         argc            argument counter (integer)
110         argv[0]         program name (pointer)
111         argv[1..argc-1] program args (pointers)
112         NULL
113         env[0...N]      environment variables (pointers)
114         NULL
115         auxvt[0...N]   Auxiliary Vector Table elements (mixed types)
116 */
117 DL_START(unsigned long args)
118 {
119         unsigned int argc;
120         char **argv, **envp;
121         DL_LOADADDR_TYPE load_addr;
122         /*ElfW(Addr) got;  aw11: dropped this in favour of phdrs*/
123         unsigned long *aux_dat;
124         ElfW(Ehdr) *header;
125         ElfW(Phdr) *phdr; /* aw11: use phdrs to find dynamic info */
126         int i;            /* aw11: use to iterate the phdrs */
127         struct elf_resolve tpnt_tmp;
128         struct elf_resolve *tpnt = &tpnt_tmp;
129         ElfW(auxv_t) auxvt[AT_EGID + 1];
130         ElfW(Dyn) *dpnt;
131         uint32_t  *p32;
132 #ifndef NOT_FOR_L4
133         void *l4re_env = 0;
134 #endif
135
136         /* WARNING! -- we cannot make _any_ function calls until we have
137          * taken care of fixing up our own relocations.  Making static
138          * inline calls is ok, but _no_ function calls.  Not yet
139          * anyways. */
140
141         /* First obtain the information on the stack that tells us more about
142            what binary is loaded, where it is loaded, etc, etc */
143         GET_ARGV(aux_dat, args);
144         argc = aux_dat[-1];
145         argv = (char **) aux_dat;
146         aux_dat += argc;                        /* Skip over the argv pointers */
147         aux_dat++;                                      /* Skip over NULL at end of argv */
148         envp = (char **) aux_dat;
149 #if !defined(NO_EARLY_SEND_STDERR)
150         SEND_EARLY_STDERR_DEBUG("argc=");
151         SEND_NUMBER_STDERR_DEBUG(argc, 0);
152         SEND_EARLY_STDERR_DEBUG(" argv=");
153         SEND_ADDRESS_STDERR_DEBUG(argv, 0);
154         SEND_EARLY_STDERR_DEBUG(" envp=");
155         SEND_ADDRESS_STDERR_DEBUG(envp, 1);
156 #endif
157         while (*aux_dat)
158                 aux_dat++;                              /* Skip over the envp pointers */
159         aux_dat++;                                      /* Skip over NULL at end of envp */
160
161         /* Place -1 here as a checkpoint.  We later check if it was changed
162          * when we read in the auxvt */
163         auxvt[AT_UID].a_type = -1;
164
165         /* The junk on the stack immediately following the environment is
166          * the Auxiliary Vector Table.  Read out the elements of the auxvt,
167          * sort and store them in auxvt for later use. */
168         while (*aux_dat) {
169                 ElfW(auxv_t) *auxv_entry = (ElfW(auxv_t) *) aux_dat;
170
171                 if (auxv_entry->a_type <= AT_EGID) {
172                         _dl_memcpy(&(auxvt[auxv_entry->a_type]), auxv_entry, sizeof(ElfW(auxv_t)));
173                 }
174 #ifndef L4_ONLY
175                 if (auxv_entry->a_type == 0xf1) {
176                         l4re_env = (void*)auxv_entry->a_un.a_val;
177                 }
178 #endif
179                 aux_dat += 2;
180         }
181
182         /* locate the ELF header.   We need this done as soon as possible
183          * (esp since SEND_STDERR() needs this on some platforms... */
184         if (!auxvt[AT_BASE].a_un.a_val)
185                 auxvt[AT_BASE].a_un.a_val = elf_machine_load_address();
186         DL_INIT_LOADADDR_BOOT(load_addr, auxvt[AT_BASE].a_un.a_val);
187         header = (ElfW(Ehdr) *) auxvt[AT_BASE].a_un.a_val;
188
189         /* Check the ELF header to make sure everything looks ok.  */
190         if (!header || header->e_ident[EI_CLASS] != ELF_CLASS ||
191                         header->e_ident[EI_VERSION] != EV_CURRENT
192                         /* Do not use an inline _dl_strncmp here or some arches
193                         * will blow chunks, i.e. those that need to relocate all
194                         * string constants... */
195                         || *(p32 = (uint32_t*)&header->e_ident) != ELFMAG_U32
196         ) {
197                 SEND_EARLY_STDERR("Invalid ELF header\n");
198                 _dl_exit(0);
199         }
200         SEND_EARLY_STDERR_DEBUG("ELF header=");
201         SEND_ADDRESS_STDERR_DEBUG(DL_LOADADDR_BASE(load_addr), 1);
202
203         /* aw11: iterate the phdrs of ldso to find our dynamic info not the GOT,
204          *       as GNU gold does not provide tge GOT entry.
205          * begin: ----------------> */
206 #if 0 /* original code */
207         /* Locate the global offset table.  Since this code must be PIC
208          * we can take advantage of the magic offset register, if we
209          * happen to know what that is for this architecture.  If not,
210          * we can always read stuff out of the ELF file to find it... */
211         DL_BOOT_COMPUTE_GOT(got);
212
213         /* Now, finally, fix up the location of the dynamic stuff */
214         DL_BOOT_COMPUTE_DYN(dpnt, got, load_addr);
215 #else /* aw11 code */
216         /* locate the ELF phdrs.   We need this for finding the dynamic infos
217          */
218         SEND_EARLY_STDERR_DEBUG("AT_PHDR=");
219         SEND_ADDRESS_STDERR_DEBUG(header->e_phoff, 1);
220         phdr = (ElfW(Phdr) *) DL_RELOC_ADDR(load_addr, header->e_phoff);
221         dpnt = 0;
222         for (i = 0; i < header->e_phnum; ++i) {
223                 if (phdr[i].p_type == PT_DYNAMIC) {
224                         DL_BOOT_COMPUTE_DYN(dpnt, phdr[i].p_vaddr, load_addr);
225                         break;
226                 }
227         }
228 #endif
229         /* aw11: end <------------- */
230
231         SEND_EARLY_STDERR_DEBUG("First Dynamic section entry=");
232         SEND_ADDRESS_STDERR_DEBUG(dpnt, 1);
233         _dl_memset(tpnt, 0, sizeof(struct elf_resolve));
234         tpnt->loadaddr = load_addr;
235         /* OK, that was easy.  Next scan the DYNAMIC section of the image.
236            We are only doing ourself right now - we will have to do the rest later */
237         SEND_EARLY_STDERR_DEBUG("Scanning DYNAMIC section\n");
238         tpnt->dynamic_addr = dpnt;
239 #if defined(NO_FUNCS_BEFORE_BOOTSTRAP)
240         /* Some architectures cannot call functions here, must inline */
241         __dl_parse_dynamic_info(dpnt, tpnt->dynamic_info, NULL, load_addr);
242 #else
243         _dl_parse_dynamic_info(dpnt, tpnt->dynamic_info, NULL, load_addr);
244 #endif
245
246         /*
247          * BIG ASSUMPTION: We assume that the dynamic loader does not
248          *                 have any TLS data itself. If this ever occurs
249          *                 more work than what is done below for the
250          *                 loader will have to happen.
251          */
252 #if defined(USE_TLS) && USE_TLS
253         /* This was done by _dl_memset above. */
254         /* tpnt->l_tls_modid = 0; */
255 # if NO_TLS_OFFSET != 0
256         tpnt->l_tls_offset = NO_TLS_OFFSET;
257 # endif
258 #endif
259
260         SEND_EARLY_STDERR_DEBUG("Done scanning DYNAMIC section\n");
261
262 #if defined(PERFORM_BOOTSTRAP_GOT)
263         SEND_EARLY_STDERR_DEBUG("About to do specific GOT bootstrap\n");
264         /* some arches (like MIPS) we have to tweak the GOT before relocations */
265         PERFORM_BOOTSTRAP_GOT(tpnt);
266 #endif
267
268 #if !defined(PERFORM_BOOTSTRAP_GOT) || defined(__avr32__)
269
270         /* OK, now do the relocations.  We do not do a lazy binding here, so
271            that once we are done, we have considerably more flexibility. */
272         SEND_EARLY_STDERR_DEBUG("About to do library loader relocations\n");
273
274         {
275                 int indx;
276 #if defined(ELF_MACHINE_PLTREL_OVERLAP)
277 # define INDX_MAX 1
278 #else
279 # define INDX_MAX 2
280 #endif
281                 for (indx = 0; indx < INDX_MAX; indx++) {
282                         unsigned long rel_addr, rel_size;
283                         ElfW(Word) relative_count = tpnt->dynamic_info[DT_RELCONT_IDX];
284
285                         rel_addr = (indx ? tpnt->dynamic_info[DT_JMPREL] :
286                                            tpnt->dynamic_info[DT_RELOC_TABLE_ADDR]);
287                         rel_size = (indx ? tpnt->dynamic_info[DT_PLTRELSZ] :
288                                            tpnt->dynamic_info[DT_RELOC_TABLE_SIZE]);
289
290                         if (!rel_addr)
291                                 continue;
292
293                         if (!indx && relative_count) {
294                                 rel_size -= relative_count * sizeof(ELF_RELOC);
295                                 elf_machine_relative(load_addr, rel_addr, relative_count);
296                                 rel_addr += relative_count * sizeof(ELF_RELOC);
297                         }
298
299                         /*
300                          * Since ldso is linked with -Bsymbolic, all relocs should be RELATIVE.  All archs
301                          * that need bootstrap relocations need to define ARCH_NEEDS_BOOTSTRAP_RELOCS.
302                          */
303 #ifdef ARCH_NEEDS_BOOTSTRAP_RELOCS
304                         {
305                                 ELF_RELOC *rpnt;
306                                 unsigned int i;
307                                 ElfW(Sym) *sym;
308                                 unsigned long symbol_addr;
309                                 int symtab_index;
310                                 unsigned long *reloc_addr;
311
312                                 /* Now parse the relocation information */
313                                 rpnt = (ELF_RELOC *) rel_addr;
314                                 for (i = 0; i < rel_size; i += sizeof(ELF_RELOC), rpnt++) {
315                                         reloc_addr = (unsigned long *) DL_RELOC_ADDR(load_addr, (unsigned long)rpnt->r_offset);
316                                         symtab_index = ELF_R_SYM(rpnt->r_info);
317                                         symbol_addr = 0;
318                                         sym = NULL;
319                                         if (symtab_index) {
320                                                 char *strtab;
321                                                 ElfW(Sym) *symtab;
322
323                                                 symtab = (ElfW(Sym) *) tpnt->dynamic_info[DT_SYMTAB];
324                                                 strtab = (char *) tpnt->dynamic_info[DT_STRTAB];
325                                                 sym = &symtab[symtab_index];
326                                                 symbol_addr = (unsigned long) DL_RELOC_ADDR(load_addr, sym->st_value);
327 #if !defined(EARLY_STDERR_SPECIAL)
328                                                 SEND_STDERR_DEBUG("relocating symbol: ");
329                                                 SEND_STDERR_DEBUG(strtab + sym->st_name);
330                                                 SEND_STDERR_DEBUG("\n");
331 #endif
332                                         } else {
333                                                 SEND_STDERR_DEBUG("relocating unknown symbol\n");
334                                         }
335                                         /* Use this machine-specific macro to perform the actual relocation.  */
336                                         PERFORM_BOOTSTRAP_RELOC(rpnt, reloc_addr, symbol_addr, load_addr, sym);
337                                 }
338                         }
339 #else /* ARCH_NEEDS_BOOTSTRAP_RELOCS */
340                         if (rel_size) {
341                                 SEND_EARLY_STDERR("Cannot continue, found non relative relocs during the bootstrap.\n");
342                                 _dl_exit(14);
343                         }
344 #endif
345                 }
346         }
347 #endif
348
349         SEND_STDERR_DEBUG("Done relocating ldso; we can now use globals and make function calls!\n");
350
351         /* Now we have done the mandatory linking of some things.  We are now
352            free to start using global variables, since these things have all been
353            fixed up by now.  Still no function calls outside of this library,
354            since the dynamic resolver is not yet ready. */
355
356         __rtld_stack_end = (void *)(argv - 1);
357
358 #ifndef __ONLY_FOR_L4__
359         {
360                 __rtld_l4re_global_env = l4re_env;
361                 ElfW(Dyn) *dpnt = tpnt->dynamic_addr;
362                 void (**ia)(void) = 0;
363                 int ia_sz =  0;
364                 extern void _init(void);
365                 _init();
366
367                 for (; dpnt->d_tag; dpnt++) {
368                         if (dpnt->d_tag == DT_INIT_ARRAY)
369                                 ia = (void (**)(void))(dpnt->d_un.d_val + load_addr);
370                         else if (dpnt->d_tag == DT_INIT_ARRAYSZ)
371                                 ia_sz = dpnt->d_un.d_val;
372                 }
373
374                 ia_sz /= sizeof(void*);
375                 for (; ia_sz > 0; --ia_sz, ++ia)
376                         (*ia)();
377         }
378 #endif
379         _dl_get_ready_to_run(tpnt, load_addr, auxvt, envp, argv
380                              DL_GET_READY_TO_RUN_EXTRA_ARGS);
381
382         /* Transfer control to the application.  */
383         SEND_STDERR_DEBUG("transfering control to application @ ");
384         _dl_elf_main = (int (*)(int, char **, char **)) auxvt[AT_ENTRY].a_un.a_val;
385         SEND_ADDRESS_STDERR_DEBUG(_dl_elf_main, 1);
386
387 #if !defined(START)
388         return _dl_elf_main;
389 #else
390         START();
391 #endif
392 }