]> git.ipfire.org Git - thirdparty/glibc.git/blob - elf/rtld.c
Remove last use of USE___THREAD
[thirdparty/glibc.git] / elf / rtld.c
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2010, 2011 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
19
20 #include <errno.h>
21 #include <dlfcn.h>
22 #include <fcntl.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/mman.h>
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 #include <ldsodefs.h>
31 #include <stdio-common/_itoa.h>
32 #include <entry.h>
33 #include <fpu_control.h>
34 #include <hp-timing.h>
35 #include <bits/libc-lock.h>
36 #include "dynamic-link.h"
37 #include <dl-librecon.h>
38 #include <unsecvars.h>
39 #include <dl-cache.h>
40 #include <dl-osinfo.h>
41 #include <dl-procinfo.h>
42 #include <tls.h>
43 #include <stackinfo.h>
44
45 #include <assert.h>
46
47 /* Avoid PLT use for our local calls at startup. */
48 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
49
50 /* GCC has mental blocks about _exit. */
51 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
52 #define _exit exit_internal
53
54 /* Helper function to handle errors while resolving symbols. */
55 static void print_unresolved (int errcode, const char *objname,
56 const char *errsting);
57
58 /* Helper function to handle errors when a version is missing. */
59 static void print_missing_version (int errcode, const char *objname,
60 const char *errsting);
61
62 /* Print the various times we collected. */
63 static void print_statistics (hp_timing_t *total_timep);
64
65 /* Add audit objects. */
66 static void process_dl_audit (char *str);
67
68 /* This is a list of all the modes the dynamic loader can be in. */
69 enum mode { normal, list, verify, trace };
70
71 /* Process all environments variables the dynamic linker must recognize.
72 Since all of them start with `LD_' we are a bit smarter while finding
73 all the entries. */
74 static void process_envvars (enum mode *modep);
75
76 #ifdef DL_ARGV_NOT_RELRO
77 int _dl_argc attribute_hidden;
78 char **_dl_argv = NULL;
79 /* Nonzero if we were run directly. */
80 unsigned int _dl_skip_args attribute_hidden;
81 #else
82 int _dl_argc attribute_relro attribute_hidden;
83 char **_dl_argv attribute_relro = NULL;
84 unsigned int _dl_skip_args attribute_relro attribute_hidden;
85 #endif
86 INTDEF(_dl_argv)
87
88 #ifndef THREAD_SET_STACK_GUARD
89 /* Only exported for architectures that don't store the stack guard canary
90 in thread local area. */
91 uintptr_t __stack_chk_guard attribute_relro;
92 #endif
93
94 /* Only exported for architectures that don't store the pointer guard
95 value in thread local area. */
96 uintptr_t __pointer_chk_guard_local
97 attribute_relro attribute_hidden __attribute__ ((nocommon));
98 #ifndef THREAD_SET_POINTER_GUARD
99 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
100 #endif
101
102
103 /* List of auditing DSOs. */
104 static struct audit_list
105 {
106 const char *name;
107 struct audit_list *next;
108 } *audit_list;
109
110 #ifndef HAVE_INLINED_SYSCALLS
111 /* Set nonzero during loading and initialization of executable and
112 libraries, cleared before the executable's entry point runs. This
113 must not be initialized to nonzero, because the unused dynamic
114 linker loaded in for libc.so's "ld.so.1" dep will provide the
115 definition seen by libc.so's initializer; that value must be zero,
116 and will be since that dynamic linker's _dl_start and dl_main will
117 never be called. */
118 int _dl_starting_up = 0;
119 INTVARDEF(_dl_starting_up)
120 #endif
121
122 /* This is the structure which defines all variables global to ld.so
123 (except those which cannot be added for some reason). */
124 struct rtld_global _rtld_global =
125 {
126 /* Generally the default presumption without further information is an
127 * executable stack but this is not true for all platforms. */
128 ._dl_stack_flags = DEFAULT_STACK_PERMS,
129 #ifdef _LIBC_REENTRANT
130 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
131 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
132 #endif
133 ._dl_nns = 1,
134 ._dl_ns =
135 {
136 [LM_ID_BASE] = { ._ns_unique_sym_table
137 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
138 }
139 };
140 /* If we would use strong_alias here the compiler would see a
141 non-hidden definition. This would undo the effect of the previous
142 declaration. So spell out was strong_alias does plus add the
143 visibility attribute. */
144 extern struct rtld_global _rtld_local
145 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
146
147
148 /* This variable is similar to _rtld_local, but all values are
149 read-only after relocation. */
150 struct rtld_global_ro _rtld_global_ro attribute_relro =
151 {
152 /* Get architecture specific initializer. */
153 #include <dl-procinfo.c>
154 #ifdef NEED_DL_SYSINFO
155 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
156 #endif
157 ._dl_debug_fd = STDERR_FILENO,
158 ._dl_use_load_bias = -2,
159 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
160 ._dl_hwcap_mask = HWCAP_IMPORTANT,
161 ._dl_lazy = 1,
162 ._dl_fpu_control = _FPU_DEFAULT,
163 ._dl_pointer_guard = 1,
164 ._dl_pagesize = EXEC_PAGESIZE,
165
166 /* Function pointers. */
167 ._dl_debug_printf = _dl_debug_printf,
168 ._dl_catch_error = _dl_catch_error,
169 ._dl_signal_error = _dl_signal_error,
170 ._dl_mcount = _dl_mcount_internal,
171 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
172 ._dl_check_caller = _dl_check_caller,
173 ._dl_open = _dl_open,
174 ._dl_close = _dl_close,
175 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
176 #ifdef HAVE_DL_DISCOVER_OSVERSION
177 ._dl_discover_osversion = _dl_discover_osversion
178 #endif
179 };
180 /* If we would use strong_alias here the compiler would see a
181 non-hidden definition. This would undo the effect of the previous
182 declaration. So spell out was strong_alias does plus add the
183 visibility attribute. */
184 extern struct rtld_global_ro _rtld_local_ro
185 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
186
187
188 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
189 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
190
191 /* These two variables cannot be moved into .data.rel.ro. */
192 static struct libname_list _dl_rtld_libname;
193 static struct libname_list _dl_rtld_libname2;
194
195 /* We expect less than a second for relocation. */
196 #ifdef HP_SMALL_TIMING_AVAIL
197 # undef HP_TIMING_AVAIL
198 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
199 #endif
200
201 /* Variable for statistics. */
202 #ifndef HP_TIMING_NONAVAIL
203 static hp_timing_t relocate_time;
204 static hp_timing_t load_time attribute_relro;
205 static hp_timing_t start_time attribute_relro;
206 #endif
207
208 /* Additional definitions needed by TLS initialization. */
209 #ifdef TLS_INIT_HELPER
210 TLS_INIT_HELPER
211 #endif
212
213 /* Helper function for syscall implementation. */
214 #ifdef DL_SYSINFO_IMPLEMENTATION
215 DL_SYSINFO_IMPLEMENTATION
216 #endif
217
218 /* Before ld.so is relocated we must not access variables which need
219 relocations. This means variables which are exported. Variables
220 declared as static are fine. If we can mark a variable hidden this
221 is fine, too. The latter is important here. We can avoid setting
222 up a temporary link map for ld.so if we can mark _rtld_global as
223 hidden. */
224 #ifdef PI_STATIC_AND_HIDDEN
225 # define DONT_USE_BOOTSTRAP_MAP 1
226 #endif
227
228 #ifdef DONT_USE_BOOTSTRAP_MAP
229 static ElfW(Addr) _dl_start_final (void *arg);
230 #else
231 struct dl_start_final_info
232 {
233 struct link_map l;
234 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
235 hp_timing_t start_time;
236 #endif
237 };
238 static ElfW(Addr) _dl_start_final (void *arg,
239 struct dl_start_final_info *info);
240 #endif
241
242 /* These defined magically in the linker script. */
243 extern char _begin[] attribute_hidden;
244 extern char _etext[] attribute_hidden;
245 extern char _end[] attribute_hidden;
246
247
248 #ifdef RTLD_START
249 RTLD_START
250 #else
251 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
252 #endif
253
254 #ifndef VALIDX
255 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
256 + DT_EXTRANUM + DT_VALTAGIDX (tag))
257 #endif
258 #ifndef ADDRIDX
259 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
260 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
261 #endif
262
263 /* This is the second half of _dl_start (below). It can be inlined safely
264 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
265 references. When the tools don't permit us to avoid using a GOT entry
266 for _dl_rtld_global (no attribute_hidden support), we must make sure
267 this function is not inlined (see below). */
268
269 #ifdef DONT_USE_BOOTSTRAP_MAP
270 static inline ElfW(Addr) __attribute__ ((always_inline))
271 _dl_start_final (void *arg)
272 #else
273 static ElfW(Addr) __attribute__ ((noinline))
274 _dl_start_final (void *arg, struct dl_start_final_info *info)
275 #endif
276 {
277 ElfW(Addr) start_addr;
278
279 if (HP_TIMING_AVAIL)
280 {
281 /* If it hasn't happen yet record the startup time. */
282 if (! HP_TIMING_INLINE)
283 HP_TIMING_NOW (start_time);
284 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
285 else
286 start_time = info->start_time;
287 #endif
288
289 /* Initialize the timing functions. */
290 HP_TIMING_DIFF_INIT ();
291 }
292
293 /* Transfer data about ourselves to the permanent link_map structure. */
294 #ifndef DONT_USE_BOOTSTRAP_MAP
295 GL(dl_rtld_map).l_addr = info->l.l_addr;
296 GL(dl_rtld_map).l_ld = info->l.l_ld;
297 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
298 sizeof GL(dl_rtld_map).l_info);
299 GL(dl_rtld_map).l_mach = info->l.l_mach;
300 GL(dl_rtld_map).l_relocated = 1;
301 #endif
302 _dl_setup_hash (&GL(dl_rtld_map));
303 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
304 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
305 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
306 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
307 /* Copy the TLS related data if necessary. */
308 #ifndef DONT_USE_BOOTSTRAP_MAP
309 # if NO_TLS_OFFSET != 0
310 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
311 # endif
312 #endif
313
314 #if HP_TIMING_AVAIL
315 HP_TIMING_NOW (GL(dl_cpuclock_offset));
316 #endif
317
318 /* Initialize the stack end variable. */
319 __libc_stack_end = __builtin_frame_address (0);
320
321 /* Call the OS-dependent function to set up life so we can do things like
322 file access. It will call `dl_main' (below) to do all the real work
323 of the dynamic linker, and then unwind our frame and run the user
324 entry point on the same stack we entered on. */
325 start_addr = _dl_sysdep_start (arg, &dl_main);
326
327 #ifndef HP_TIMING_NONAVAIL
328 hp_timing_t rtld_total_time;
329 if (HP_TIMING_AVAIL)
330 {
331 hp_timing_t end_time;
332
333 /* Get the current time. */
334 HP_TIMING_NOW (end_time);
335
336 /* Compute the difference. */
337 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
338 }
339 #endif
340
341 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
342 {
343 #ifndef HP_TIMING_NONAVAIL
344 print_statistics (&rtld_total_time);
345 #else
346 print_statistics (NULL);
347 #endif
348 }
349
350 return start_addr;
351 }
352
353 static ElfW(Addr) __attribute_used__ internal_function
354 _dl_start (void *arg)
355 {
356 #ifdef DONT_USE_BOOTSTRAP_MAP
357 # define bootstrap_map GL(dl_rtld_map)
358 #else
359 struct dl_start_final_info info;
360 # define bootstrap_map info.l
361 #endif
362
363 /* This #define produces dynamic linking inline functions for
364 bootstrap relocation instead of general-purpose relocation.
365 Since ld.so must not have any undefined symbols the result
366 is trivial: always the map of ld.so itself. */
367 #define RTLD_BOOTSTRAP
368 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
369 #include "dynamic-link.h"
370
371 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
372 #ifdef DONT_USE_BOOTSTRAP_MAP
373 HP_TIMING_NOW (start_time);
374 #else
375 HP_TIMING_NOW (info.start_time);
376 #endif
377
378 /* Partly clean the `bootstrap_map' structure up. Don't use
379 `memset' since it might not be built in or inlined and we cannot
380 make function calls at this point. Use '__builtin_memset' if we
381 know it is available. We do not have to clear the memory if we
382 do not have to use the temporary bootstrap_map. Global variables
383 are initialized to zero by default. */
384 #ifndef DONT_USE_BOOTSTRAP_MAP
385 # ifdef HAVE_BUILTIN_MEMSET
386 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
387 # else
388 for (size_t cnt = 0;
389 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
390 ++cnt)
391 bootstrap_map.l_info[cnt] = 0;
392 # endif
393 #endif
394
395 /* Figure out the run-time load address of the dynamic linker itself. */
396 bootstrap_map.l_addr = elf_machine_load_address ();
397
398 /* Read our own dynamic section and fill in the info array. */
399 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
400 elf_get_dynamic_info (&bootstrap_map, NULL);
401
402 #if NO_TLS_OFFSET != 0
403 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
404 #endif
405
406 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
407 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
408 #endif
409
410 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
411 {
412 /* Relocate ourselves so we can do normal function calls and
413 data access using the global offset table. */
414
415 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
416 }
417 bootstrap_map.l_relocated = 1;
418
419 /* Please note that we don't allow profiling of this object and
420 therefore need not test whether we have to allocate the array
421 for the relocation results (as done in dl-reloc.c). */
422
423 /* Now life is sane; we can call functions and access global data.
424 Set up to use the operating system facilities, and find out from
425 the operating system's program loader where to find the program
426 header table in core. Put the rest of _dl_start into a separate
427 function, that way the compiler cannot put accesses to the GOT
428 before ELF_DYNAMIC_RELOCATE. */
429 {
430 #ifdef DONT_USE_BOOTSTRAP_MAP
431 ElfW(Addr) entry = _dl_start_final (arg);
432 #else
433 ElfW(Addr) entry = _dl_start_final (arg, &info);
434 #endif
435
436 #ifndef ELF_MACHINE_START_ADDRESS
437 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
438 #endif
439
440 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
441 }
442 }
443
444
445
446 /* Now life is peachy; we can do all normal operations.
447 On to the real work. */
448
449 /* Some helper functions. */
450
451 /* Arguments to relocate_doit. */
452 struct relocate_args
453 {
454 struct link_map *l;
455 int reloc_mode;
456 };
457
458 struct map_args
459 {
460 /* Argument to map_doit. */
461 char *str;
462 struct link_map *loader;
463 int mode;
464 /* Return value of map_doit. */
465 struct link_map *map;
466 };
467
468 struct dlmopen_args
469 {
470 const char *fname;
471 struct link_map *map;
472 };
473
474 struct lookup_args
475 {
476 const char *name;
477 struct link_map *map;
478 void *result;
479 };
480
481 /* Arguments to version_check_doit. */
482 struct version_check_args
483 {
484 int doexit;
485 int dotrace;
486 };
487
488 static void
489 relocate_doit (void *a)
490 {
491 struct relocate_args *args = (struct relocate_args *) a;
492
493 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
494 }
495
496 static void
497 map_doit (void *a)
498 {
499 struct map_args *args = (struct map_args *) a;
500 args->map = _dl_map_object (args->loader, args->str, lt_library, 0,
501 args->mode, LM_ID_BASE);
502 }
503
504 static void
505 dlmopen_doit (void *a)
506 {
507 struct dlmopen_args *args = (struct dlmopen_args *) a;
508 args->map = _dl_open (args->fname,
509 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
510 | __RTLD_SECURE),
511 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
512 __environ);
513 }
514
515 static void
516 lookup_doit (void *a)
517 {
518 struct lookup_args *args = (struct lookup_args *) a;
519 const ElfW(Sym) *ref = NULL;
520 args->result = NULL;
521 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
522 args->map->l_local_scope, NULL, 0,
523 DL_LOOKUP_RETURN_NEWEST, NULL);
524 if (ref != NULL)
525 args->result = DL_SYMBOL_ADDRESS (l, ref);
526 }
527
528 static void
529 version_check_doit (void *a)
530 {
531 struct version_check_args *args = (struct version_check_args *) a;
532 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
533 args->dotrace) && args->doexit)
534 /* We cannot start the application. Abort now. */
535 _exit (1);
536 }
537
538
539 static inline struct link_map *
540 find_needed (const char *name)
541 {
542 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
543 unsigned int n = scope->r_nlist;
544
545 while (n-- > 0)
546 if (_dl_name_match_p (name, scope->r_list[n]))
547 return scope->r_list[n];
548
549 /* Should never happen. */
550 return NULL;
551 }
552
553 static int
554 match_version (const char *string, struct link_map *map)
555 {
556 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
557 ElfW(Verdef) *def;
558
559 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
560 if (map->l_info[VERDEFTAG] == NULL)
561 /* The file has no symbol versioning. */
562 return 0;
563
564 def = (ElfW(Verdef) *) ((char *) map->l_addr
565 + map->l_info[VERDEFTAG]->d_un.d_ptr);
566 while (1)
567 {
568 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
569
570 /* Compare the version strings. */
571 if (strcmp (string, strtab + aux->vda_name) == 0)
572 /* Bingo! */
573 return 1;
574
575 /* If no more definitions we failed to find what we want. */
576 if (def->vd_next == 0)
577 break;
578
579 /* Next definition. */
580 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
581 }
582
583 return 0;
584 }
585
586 static bool tls_init_tp_called;
587
588 static void *
589 init_tls (void)
590 {
591 /* Number of elements in the static TLS block. */
592 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
593
594 /* Do not do this twice. The audit interface might have required
595 the DTV interfaces to be set up early. */
596 if (GL(dl_initial_dtv) != NULL)
597 return NULL;
598
599 /* Allocate the array which contains the information about the
600 dtv slots. We allocate a few entries more than needed to
601 avoid the need for reallocation. */
602 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
603
604 /* Allocate. */
605 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
606 calloc (sizeof (struct dtv_slotinfo_list)
607 + nelem * sizeof (struct dtv_slotinfo), 1);
608 /* No need to check the return value. If memory allocation failed
609 the program would have been terminated. */
610
611 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
612 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
613 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
614
615 /* Fill in the information from the loaded modules. No namespace
616 but the base one can be filled at this time. */
617 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
618 int i = 0;
619 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
620 l = l->l_next)
621 if (l->l_tls_blocksize != 0)
622 {
623 /* This is a module with TLS data. Store the map reference.
624 The generation counter is zero. */
625 slotinfo[i].map = l;
626 /* slotinfo[i].gen = 0; */
627 ++i;
628 }
629 assert (i == GL(dl_tls_max_dtv_idx));
630
631 /* Compute the TLS offsets for the various blocks. */
632 _dl_determine_tlsoffset ();
633
634 /* Construct the static TLS block and the dtv for the initial
635 thread. For some platforms this will include allocating memory
636 for the thread descriptor. The memory for the TLS block will
637 never be freed. It should be allocated accordingly. The dtv
638 array can be changed if dynamic loading requires it. */
639 void *tcbp = _dl_allocate_tls_storage ();
640 if (tcbp == NULL)
641 _dl_fatal_printf ("\
642 cannot allocate TLS data structures for initial thread");
643
644 /* Store for detection of the special case by __tls_get_addr
645 so it knows not to pass this dtv to the normal realloc. */
646 GL(dl_initial_dtv) = GET_DTV (tcbp);
647
648 /* And finally install it for the main thread. If ld.so itself uses
649 TLS we know the thread pointer was initialized earlier. */
650 const char *lossage = TLS_INIT_TP (tcbp, 0);
651 if (__builtin_expect (lossage != NULL, 0))
652 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
653 tls_init_tp_called = true;
654
655 return tcbp;
656 }
657
658 #ifdef _LIBC_REENTRANT
659 /* _dl_error_catch_tsd points to this for the single-threaded case.
660 It's reset by the thread library for multithreaded programs. */
661 void ** __attribute__ ((const))
662 _dl_initial_error_catch_tsd (void)
663 {
664 static void *data;
665 return &data;
666 }
667 #endif
668
669
670 static unsigned int
671 do_preload (char *fname, struct link_map *main_map, const char *where)
672 {
673 const char *objname;
674 const char *err_str = NULL;
675 struct map_args args;
676 bool malloced;
677
678 args.str = fname;
679 args.loader = main_map;
680 args.mode = __RTLD_SECURE;
681
682 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
683
684 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
685 if (__builtin_expect (err_str != NULL, 0))
686 {
687 _dl_error_printf ("\
688 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
689 fname, where);
690 /* No need to call free, this is still before
691 the libc's malloc is used. */
692 }
693 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
694 /* It is no duplicate. */
695 return 1;
696
697 /* Nothing loaded. */
698 return 0;
699 }
700
701 #if defined SHARED && defined _LIBC_REENTRANT \
702 && defined __rtld_lock_default_lock_recursive
703 static void
704 rtld_lock_default_lock_recursive (void *lock)
705 {
706 __rtld_lock_default_lock_recursive (lock);
707 }
708
709 static void
710 rtld_lock_default_unlock_recursive (void *lock)
711 {
712 __rtld_lock_default_unlock_recursive (lock);
713 }
714 #endif
715
716
717 static void
718 security_init (void)
719 {
720 /* Set up the stack checker's canary. */
721 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
722 #ifdef THREAD_SET_STACK_GUARD
723 THREAD_SET_STACK_GUARD (stack_chk_guard);
724 #else
725 __stack_chk_guard = stack_chk_guard;
726 #endif
727
728 /* Set up the pointer guard as well, if necessary. */
729 if (GLRO(dl_pointer_guard))
730 {
731 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
732 stack_chk_guard);
733 #ifdef THREAD_SET_POINTER_GUARD
734 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
735 #endif
736 __pointer_chk_guard_local = pointer_chk_guard;
737 }
738
739 /* We do not need the _dl_random value anymore. The less
740 information we leave behind, the better, so clear the
741 variable. */
742 _dl_random = NULL;
743 }
744
745
746 /* The library search path. */
747 static const char *library_path attribute_relro;
748 /* The list preloaded objects. */
749 static const char *preloadlist attribute_relro;
750 /* Nonzero if information about versions has to be printed. */
751 static int version_info attribute_relro;
752
753 static void
754 dl_main (const ElfW(Phdr) *phdr,
755 ElfW(Word) phnum,
756 ElfW(Addr) *user_entry,
757 ElfW(auxv_t) *auxv)
758 {
759 const ElfW(Phdr) *ph;
760 enum mode mode;
761 struct link_map *main_map;
762 size_t file_size;
763 char *file;
764 bool has_interp = false;
765 unsigned int i;
766 bool prelinked = false;
767 bool rtld_is_main = false;
768 #ifndef HP_TIMING_NONAVAIL
769 hp_timing_t start;
770 hp_timing_t stop;
771 hp_timing_t diff;
772 #endif
773 void *tcbp = NULL;
774
775 #ifdef _LIBC_REENTRANT
776 /* Explicit initialization since the reloc would just be more work. */
777 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
778 #endif
779
780 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
781
782 #if defined SHARED && defined _LIBC_REENTRANT \
783 && defined __rtld_lock_default_lock_recursive
784 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
785 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
786 #endif
787
788 /* The explicit initialization here is cheaper than processing the reloc
789 in the _rtld_local definition's initializer. */
790 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
791
792 /* Process the environment variable which control the behaviour. */
793 process_envvars (&mode);
794
795 #ifndef HAVE_INLINED_SYSCALLS
796 /* Set up a flag which tells we are just starting. */
797 INTUSE(_dl_starting_up) = 1;
798 #endif
799
800 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
801 {
802 /* Ho ho. We are not the program interpreter! We are the program
803 itself! This means someone ran ld.so as a command. Well, that
804 might be convenient to do sometimes. We support it by
805 interpreting the args like this:
806
807 ld.so PROGRAM ARGS...
808
809 The first argument is the name of a file containing an ELF
810 executable we will load and run with the following arguments.
811 To simplify life here, PROGRAM is searched for using the
812 normal rules for shared objects, rather than $PATH or anything
813 like that. We just load it and use its entry point; we don't
814 pay attention to its PT_INTERP command (we are the interpreter
815 ourselves). This is an easy way to test a new ld.so before
816 installing it. */
817 rtld_is_main = true;
818
819 /* Note the place where the dynamic linker actually came from. */
820 GL(dl_rtld_map).l_name = rtld_progname;
821
822 while (_dl_argc > 1)
823 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
824 {
825 mode = list;
826 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
827
828 ++_dl_skip_args;
829 --_dl_argc;
830 ++INTUSE(_dl_argv);
831 }
832 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
833 {
834 mode = verify;
835
836 ++_dl_skip_args;
837 --_dl_argc;
838 ++INTUSE(_dl_argv);
839 }
840 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
841 && _dl_argc > 2)
842 {
843 library_path = INTUSE(_dl_argv)[2];
844
845 _dl_skip_args += 2;
846 _dl_argc -= 2;
847 INTUSE(_dl_argv) += 2;
848 }
849 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
850 && _dl_argc > 2)
851 {
852 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
853
854 _dl_skip_args += 2;
855 _dl_argc -= 2;
856 INTUSE(_dl_argv) += 2;
857 }
858 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
859 {
860 process_dl_audit (INTUSE(_dl_argv)[2]);
861
862 _dl_skip_args += 2;
863 _dl_argc -= 2;
864 INTUSE(_dl_argv) += 2;
865 }
866 else
867 break;
868
869 /* If we have no further argument the program was called incorrectly.
870 Grant the user some education. */
871 if (_dl_argc < 2)
872 _dl_fatal_printf ("\
873 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
874 You have invoked `ld.so', the helper program for shared library executables.\n\
875 This program usually lives in the file `/lib/ld.so', and special directives\n\
876 in executable files using ELF shared libraries tell the system's program\n\
877 loader to load the helper program from this file. This helper program loads\n\
878 the shared libraries needed by the program executable, prepares the program\n\
879 to run, and runs it. You may invoke this helper program directly from the\n\
880 command line to load and run an ELF executable file; this is like executing\n\
881 that file itself, but always uses this helper program from the file you\n\
882 specified, instead of the helper program file specified in the executable\n\
883 file you run. This is mostly of use for maintainers to test new versions\n\
884 of this helper program; chances are you did not intend to run this program.\n\
885 \n\
886 --list list all dependencies and how they are resolved\n\
887 --verify verify that given object really is a dynamically linked\n\
888 object we can handle\n\
889 --library-path PATH use given PATH instead of content of the environment\n\
890 variable LD_LIBRARY_PATH\n\
891 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
892 in LIST\n\
893 --audit LIST use objects named in LIST as auditors\n");
894
895 ++_dl_skip_args;
896 --_dl_argc;
897 ++INTUSE(_dl_argv);
898
899 /* The initialization of _dl_stack_flags done below assumes the
900 executable's PT_GNU_STACK may have been honored by the kernel, and
901 so a PT_GNU_STACK with PF_X set means the stack started out with
902 execute permission. However, this is not really true if the
903 dynamic linker is the executable the kernel loaded. For this
904 case, we must reinitialize _dl_stack_flags to match the dynamic
905 linker itself. If the dynamic linker was built with a
906 PT_GNU_STACK, then the kernel may have loaded us with a
907 nonexecutable stack that we will have to make executable when we
908 load the program below unless it has a PT_GNU_STACK indicating
909 nonexecutable stack is ok. */
910
911 for (ph = phdr; ph < &phdr[phnum]; ++ph)
912 if (ph->p_type == PT_GNU_STACK)
913 {
914 GL(dl_stack_flags) = ph->p_flags;
915 break;
916 }
917
918 if (__builtin_expect (mode, normal) == verify)
919 {
920 const char *objname;
921 const char *err_str = NULL;
922 struct map_args args;
923 bool malloced;
924
925 args.str = rtld_progname;
926 args.loader = NULL;
927 args.mode = __RTLD_OPENEXEC;
928 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
929 &args);
930 if (__builtin_expect (err_str != NULL, 0))
931 /* We don't free the returned string, the programs stops
932 anyway. */
933 _exit (EXIT_FAILURE);
934 }
935 else
936 {
937 HP_TIMING_NOW (start);
938 _dl_map_object (NULL, rtld_progname, lt_library, 0,
939 __RTLD_OPENEXEC, LM_ID_BASE);
940 HP_TIMING_NOW (stop);
941
942 HP_TIMING_DIFF (load_time, start, stop);
943 }
944
945 /* Now the map for the main executable is available. */
946 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
947
948 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
949 && main_map->l_info[DT_SONAME] != NULL
950 && strcmp ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
951 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val,
952 (const char *) D_PTR (main_map, l_info[DT_STRTAB])
953 + main_map->l_info[DT_SONAME]->d_un.d_val) == 0)
954 _dl_fatal_printf ("loader cannot load itself\n");
955
956 phdr = main_map->l_phdr;
957 phnum = main_map->l_phnum;
958 /* We overwrite here a pointer to a malloc()ed string. But since
959 the malloc() implementation used at this point is the dummy
960 implementations which has no real free() function it does not
961 makes sense to free the old string first. */
962 main_map->l_name = (char *) "";
963 *user_entry = main_map->l_entry;
964
965 #ifdef HAVE_AUX_VECTOR
966 /* Adjust the on-stack auxiliary vector so that it looks like the
967 binary was executed directly. */
968 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
969 switch (av->a_type)
970 {
971 case AT_PHDR:
972 av->a_un.a_val = (uintptr_t) phdr;
973 break;
974 case AT_PHNUM:
975 av->a_un.a_val = phnum;
976 break;
977 case AT_ENTRY:
978 av->a_un.a_val = *user_entry;
979 break;
980 }
981 #endif
982 }
983 else
984 {
985 /* Create a link_map for the executable itself.
986 This will be what dlopen on "" returns. */
987 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
988 __RTLD_OPENEXEC, LM_ID_BASE);
989 assert (main_map != NULL);
990 main_map->l_phdr = phdr;
991 main_map->l_phnum = phnum;
992 main_map->l_entry = *user_entry;
993
994 /* Even though the link map is not yet fully initialized we can add
995 it to the map list since there are no possible users running yet. */
996 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
997 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
998
999 /* At this point we are in a bit of trouble. We would have to
1000 fill in the values for l_dev and l_ino. But in general we
1001 do not know where the file is. We also do not handle AT_EXECFD
1002 even if it would be passed up.
1003
1004 We leave the values here defined to 0. This is normally no
1005 problem as the program code itself is normally no shared
1006 object and therefore cannot be loaded dynamically. Nothing
1007 prevent the use of dynamic binaries and in these situations
1008 we might get problems. We might not be able to find out
1009 whether the object is already loaded. But since there is no
1010 easy way out and because the dynamic binary must also not
1011 have an SONAME we ignore this program for now. If it becomes
1012 a problem we can force people using SONAMEs. */
1013
1014 /* We delay initializing the path structure until we got the dynamic
1015 information for the program. */
1016 }
1017
1018 main_map->l_map_end = 0;
1019 main_map->l_text_end = 0;
1020 /* Perhaps the executable has no PT_LOAD header entries at all. */
1021 main_map->l_map_start = ~0;
1022 /* And it was opened directly. */
1023 ++main_map->l_direct_opencount;
1024
1025 /* Scan the program header table for the dynamic section. */
1026 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1027 switch (ph->p_type)
1028 {
1029 case PT_PHDR:
1030 /* Find out the load address. */
1031 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1032 break;
1033 case PT_DYNAMIC:
1034 /* This tells us where to find the dynamic section,
1035 which tells us everything we need to do. */
1036 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1037 break;
1038 case PT_INTERP:
1039 /* This "interpreter segment" was used by the program loader to
1040 find the program interpreter, which is this program itself, the
1041 dynamic linker. We note what name finds us, so that a future
1042 dlopen call or DT_NEEDED entry, for something that wants to link
1043 against the dynamic linker as a shared library, will know that
1044 the shared object is already loaded. */
1045 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1046 + ph->p_vaddr);
1047 /* _dl_rtld_libname.next = NULL; Already zero. */
1048 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1049
1050 /* Ordinarilly, we would get additional names for the loader from
1051 our DT_SONAME. This can't happen if we were actually linked as
1052 a static executable (detect this case when we have no DYNAMIC).
1053 If so, assume the filename component of the interpreter path to
1054 be our SONAME, and add it to our name list. */
1055 if (GL(dl_rtld_map).l_ld == NULL)
1056 {
1057 const char *p = NULL;
1058 const char *cp = _dl_rtld_libname.name;
1059
1060 /* Find the filename part of the path. */
1061 while (*cp != '\0')
1062 if (*cp++ == '/')
1063 p = cp;
1064
1065 if (p != NULL)
1066 {
1067 _dl_rtld_libname2.name = p;
1068 /* _dl_rtld_libname2.next = NULL; Already zero. */
1069 _dl_rtld_libname.next = &_dl_rtld_libname2;
1070 }
1071 }
1072
1073 has_interp = true;
1074 break;
1075 case PT_LOAD:
1076 {
1077 ElfW(Addr) mapstart;
1078 ElfW(Addr) allocend;
1079
1080 /* Remember where the main program starts in memory. */
1081 mapstart = (main_map->l_addr
1082 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1083 if (main_map->l_map_start > mapstart)
1084 main_map->l_map_start = mapstart;
1085
1086 /* Also where it ends. */
1087 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1088 if (main_map->l_map_end < allocend)
1089 main_map->l_map_end = allocend;
1090 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1091 main_map->l_text_end = allocend;
1092 }
1093 break;
1094
1095 case PT_TLS:
1096 if (ph->p_memsz > 0)
1097 {
1098 /* Note that in the case the dynamic linker we duplicate work
1099 here since we read the PT_TLS entry already in
1100 _dl_start_final. But the result is repeatable so do not
1101 check for this special but unimportant case. */
1102 main_map->l_tls_blocksize = ph->p_memsz;
1103 main_map->l_tls_align = ph->p_align;
1104 if (ph->p_align == 0)
1105 main_map->l_tls_firstbyte_offset = 0;
1106 else
1107 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1108 & (ph->p_align - 1));
1109 main_map->l_tls_initimage_size = ph->p_filesz;
1110 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1111
1112 /* This image gets the ID one. */
1113 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1114 }
1115 break;
1116
1117 case PT_GNU_STACK:
1118 GL(dl_stack_flags) = ph->p_flags;
1119 break;
1120
1121 case PT_GNU_RELRO:
1122 main_map->l_relro_addr = ph->p_vaddr;
1123 main_map->l_relro_size = ph->p_memsz;
1124 break;
1125 }
1126
1127 /* Adjust the address of the TLS initialization image in case
1128 the executable is actually an ET_DYN object. */
1129 if (main_map->l_tls_initimage != NULL)
1130 main_map->l_tls_initimage
1131 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1132 if (! main_map->l_map_end)
1133 main_map->l_map_end = ~0;
1134 if (! main_map->l_text_end)
1135 main_map->l_text_end = ~0;
1136 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1137 {
1138 /* We were invoked directly, so the program might not have a
1139 PT_INTERP. */
1140 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1141 /* _dl_rtld_libname.next = NULL; Already zero. */
1142 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1143 }
1144 else
1145 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1146
1147 /* If the current libname is different from the SONAME, add the
1148 latter as well. */
1149 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1150 && strcmp (GL(dl_rtld_map).l_libname->name,
1151 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1152 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1153 {
1154 static struct libname_list newname;
1155 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1156 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1157 newname.next = NULL;
1158 newname.dont_free = 1;
1159
1160 assert (GL(dl_rtld_map).l_libname->next == NULL);
1161 GL(dl_rtld_map).l_libname->next = &newname;
1162 }
1163 /* The ld.so must be relocated since otherwise loading audit modules
1164 will fail since they reuse the very same ld.so. */
1165 assert (GL(dl_rtld_map).l_relocated);
1166
1167 if (! rtld_is_main)
1168 {
1169 /* Extract the contents of the dynamic section for easy access. */
1170 elf_get_dynamic_info (main_map, NULL);
1171 /* Set up our cache of pointers into the hash table. */
1172 _dl_setup_hash (main_map);
1173 }
1174
1175 if (__builtin_expect (mode, normal) == verify)
1176 {
1177 /* We were called just to verify that this is a dynamic
1178 executable using us as the program interpreter. Exit with an
1179 error if we were not able to load the binary or no interpreter
1180 is specified (i.e., this is no dynamically linked binary. */
1181 if (main_map->l_ld == NULL)
1182 _exit (1);
1183
1184 /* We allow here some platform specific code. */
1185 #ifdef DISTINGUISH_LIB_VERSIONS
1186 DISTINGUISH_LIB_VERSIONS;
1187 #endif
1188 _exit (has_interp ? 0 : 2);
1189 }
1190
1191 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1192 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1193 /* Set up the data structures for the system-supplied DSO early,
1194 so they can influence _dl_init_paths. */
1195 if (GLRO(dl_sysinfo_dso) != NULL)
1196 {
1197 /* Do an abridged version of the work _dl_map_object_from_fd would do
1198 to map in the object. It's already mapped and prelinked (and
1199 better be, since it's read-only and so we couldn't relocate it).
1200 We just want our data structures to describe it as if we had just
1201 mapped and relocated it normally. */
1202 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1203 0, LM_ID_BASE);
1204 if (__builtin_expect (l != NULL, 1))
1205 {
1206 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1207
1208 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1209 + GLRO(dl_sysinfo_dso)->e_phoff);
1210 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1211 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1212 {
1213 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1214 if (ph->p_type == PT_DYNAMIC)
1215 {
1216 l->l_ld = (void *) ph->p_vaddr;
1217 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1218 }
1219 else if (ph->p_type == PT_LOAD)
1220 {
1221 if (! l->l_addr)
1222 l->l_addr = ph->p_vaddr;
1223 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1224 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1225 if ((ph->p_flags & PF_X)
1226 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1227 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1228 }
1229 else
1230 /* There must be no TLS segment. */
1231 assert (ph->p_type != PT_TLS);
1232 }
1233 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1234 l->l_addr = l->l_map_start - l->l_addr;
1235 l->l_map_end += l->l_addr;
1236 l->l_text_end += l->l_addr;
1237 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1238 elf_get_dynamic_info (l, dyn_temp);
1239 _dl_setup_hash (l);
1240 l->l_relocated = 1;
1241
1242 /* Initialize l_local_scope to contain just this map. This allows
1243 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1244 So we create a single entry list pointing to l_real as its only
1245 element */
1246 l->l_local_scope[0]->r_nlist = 1;
1247 l->l_local_scope[0]->r_list = &l->l_real;
1248
1249 /* Now that we have the info handy, use the DSO image's soname
1250 so this object can be looked up by name. Note that we do not
1251 set l_name here. That field gives the file name of the DSO,
1252 and this DSO is not associated with any file. */
1253 if (l->l_info[DT_SONAME] != NULL)
1254 {
1255 /* Work around a kernel problem. The kernel cannot handle
1256 addresses in the vsyscall DSO pages in writev() calls. */
1257 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1258 + l->l_info[DT_SONAME]->d_un.d_val);
1259 size_t len = strlen (dsoname);
1260 char *copy = malloc (len);
1261 if (copy == NULL)
1262 _dl_fatal_printf ("out of memory\n");
1263 l->l_libname->name = l->l_name = memcpy (copy, dsoname, len);
1264 }
1265
1266 /* Add the vDSO to the object list. */
1267 _dl_add_to_namespace_list (l, LM_ID_BASE);
1268
1269 /* Rearrange the list so this DSO appears after rtld_map. */
1270 assert (l->l_next == NULL);
1271 assert (l->l_prev == main_map);
1272 GL(dl_rtld_map).l_next = l;
1273 l->l_prev = &GL(dl_rtld_map);
1274 first_preload = &l->l_next;
1275
1276 /* We have a prelinked DSO preloaded by the system. */
1277 GLRO(dl_sysinfo_map) = l;
1278 # ifdef NEED_DL_SYSINFO
1279 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1280 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1281 # endif
1282 }
1283 }
1284 #endif
1285
1286 #ifdef DL_SYSDEP_OSCHECK
1287 DL_SYSDEP_OSCHECK (dl_fatal);
1288 #endif
1289
1290 /* Initialize the data structures for the search paths for shared
1291 objects. */
1292 _dl_init_paths (library_path);
1293
1294 /* Initialize _r_debug. */
1295 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1296 LM_ID_BASE);
1297 r->r_state = RT_CONSISTENT;
1298
1299 /* Put the link_map for ourselves on the chain so it can be found by
1300 name. Note that at this point the global chain of link maps contains
1301 exactly one element, which is pointed to by dl_loaded. */
1302 if (! GL(dl_rtld_map).l_name)
1303 /* If not invoked directly, the dynamic linker shared object file was
1304 found by the PT_INTERP name. */
1305 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1306 GL(dl_rtld_map).l_type = lt_library;
1307 main_map->l_next = &GL(dl_rtld_map);
1308 GL(dl_rtld_map).l_prev = main_map;
1309 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1310 ++GL(dl_load_adds);
1311
1312 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1313 to not using bias for non-prelinked PIEs and libraries
1314 and using it for executables or prelinked PIEs or libraries. */
1315 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1316 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1317
1318 /* Set up the program header information for the dynamic linker
1319 itself. It is needed in the dl_iterate_phdr() callbacks. */
1320 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1321 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1322 + rtld_ehdr->e_phoff);
1323 GL(dl_rtld_map).l_phdr = rtld_phdr;
1324 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1325
1326
1327 /* PT_GNU_RELRO is usually the last phdr. */
1328 size_t cnt = rtld_ehdr->e_phnum;
1329 while (cnt-- > 0)
1330 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1331 {
1332 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1333 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1334 break;
1335 }
1336
1337 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1338 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1339 /* Assign a module ID. Do this before loading any audit modules. */
1340 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1341
1342 /* If we have auditing DSOs to load, do it now. */
1343 if (__builtin_expect (audit_list != NULL, 0))
1344 {
1345 /* Iterate over all entries in the list. The order is important. */
1346 struct audit_ifaces *last_audit = NULL;
1347 struct audit_list *al = audit_list->next;
1348
1349 /* Since we start using the auditing DSOs right away we need to
1350 initialize the data structures now. */
1351 tcbp = init_tls ();
1352
1353 /* Initialize security features. We need to do it this early
1354 since otherwise the constructors of the audit libraries will
1355 use different values (especially the pointer guard) and will
1356 fail later on. */
1357 security_init ();
1358
1359 do
1360 {
1361 int tls_idx = GL(dl_tls_max_dtv_idx);
1362
1363 /* Now it is time to determine the layout of the static TLS
1364 block and allocate it for the initial thread. Note that we
1365 always allocate the static block, we never defer it even if
1366 no DF_STATIC_TLS bit is set. The reason is that we know
1367 glibc will use the static model. */
1368 struct dlmopen_args dlmargs;
1369 dlmargs.fname = al->name;
1370 dlmargs.map = NULL;
1371
1372 const char *objname;
1373 const char *err_str = NULL;
1374 bool malloced;
1375 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1376 &dlmargs);
1377 if (__builtin_expect (err_str != NULL, 0))
1378 {
1379 not_loaded:
1380 _dl_error_printf ("\
1381 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1382 al->name, err_str);
1383 if (malloced)
1384 free ((char *) err_str);
1385 }
1386 else
1387 {
1388 struct lookup_args largs;
1389 largs.name = "la_version";
1390 largs.map = dlmargs.map;
1391
1392 /* Check whether the interface version matches. */
1393 (void) _dl_catch_error (&objname, &err_str, &malloced,
1394 lookup_doit, &largs);
1395
1396 unsigned int (*laversion) (unsigned int);
1397 unsigned int lav;
1398 if (err_str == NULL
1399 && (laversion = largs.result) != NULL
1400 && (lav = laversion (LAV_CURRENT)) > 0
1401 && lav <= LAV_CURRENT)
1402 {
1403 /* Allocate structure for the callback function pointers.
1404 This call can never fail. */
1405 union
1406 {
1407 struct audit_ifaces ifaces;
1408 #define naudit_ifaces 8
1409 void (*fptr[naudit_ifaces]) (void);
1410 } *newp = malloc (sizeof (*newp));
1411
1412 /* Names of the auditing interfaces. All in one
1413 long string. */
1414 static const char audit_iface_names[] =
1415 "la_activity\0"
1416 "la_objsearch\0"
1417 "la_objopen\0"
1418 "la_preinit\0"
1419 #if __ELF_NATIVE_CLASS == 32
1420 "la_symbind32\0"
1421 #elif __ELF_NATIVE_CLASS == 64
1422 "la_symbind64\0"
1423 #else
1424 # error "__ELF_NATIVE_CLASS must be defined"
1425 #endif
1426 #define STRING(s) __STRING (s)
1427 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1428 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1429 "la_objclose\0";
1430 unsigned int cnt = 0;
1431 const char *cp = audit_iface_names;
1432 do
1433 {
1434 largs.name = cp;
1435 (void) _dl_catch_error (&objname, &err_str, &malloced,
1436 lookup_doit, &largs);
1437
1438 /* Store the pointer. */
1439 if (err_str == NULL && largs.result != NULL)
1440 {
1441 newp->fptr[cnt] = largs.result;
1442
1443 /* The dynamic linker link map is statically
1444 allocated, initialize the data now. */
1445 GL(dl_rtld_map).l_audit[cnt].cookie
1446 = (intptr_t) &GL(dl_rtld_map);
1447 }
1448 else
1449 newp->fptr[cnt] = NULL;
1450 ++cnt;
1451
1452 cp = (char *) rawmemchr (cp, '\0') + 1;
1453 }
1454 while (*cp != '\0');
1455 assert (cnt == naudit_ifaces);
1456
1457 /* Now append the new auditing interface to the list. */
1458 newp->ifaces.next = NULL;
1459 if (last_audit == NULL)
1460 last_audit = GLRO(dl_audit) = &newp->ifaces;
1461 else
1462 last_audit = last_audit->next = &newp->ifaces;
1463 ++GLRO(dl_naudit);
1464
1465 /* Mark the DSO as being used for auditing. */
1466 dlmargs.map->l_auditing = 1;
1467 }
1468 else
1469 {
1470 /* We cannot use the DSO, it does not have the
1471 appropriate interfaces or it expects something
1472 more recent. */
1473 #ifndef NDEBUG
1474 Lmid_t ns = dlmargs.map->l_ns;
1475 #endif
1476 _dl_close (dlmargs.map);
1477
1478 /* Make sure the namespace has been cleared entirely. */
1479 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1480 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1481
1482 GL(dl_tls_max_dtv_idx) = tls_idx;
1483 goto not_loaded;
1484 }
1485 }
1486
1487 al = al->next;
1488 }
1489 while (al != audit_list->next);
1490
1491 /* If we have any auditing modules, announce that we already
1492 have two objects loaded. */
1493 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1494 {
1495 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1496
1497 for (unsigned int outer = 0; outer < 2; ++outer)
1498 {
1499 struct audit_ifaces *afct = GLRO(dl_audit);
1500 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1501 {
1502 if (afct->objopen != NULL)
1503 {
1504 ls[outer]->l_audit[cnt].bindflags
1505 = afct->objopen (ls[outer], LM_ID_BASE,
1506 &ls[outer]->l_audit[cnt].cookie);
1507
1508 ls[outer]->l_audit_any_plt
1509 |= ls[outer]->l_audit[cnt].bindflags != 0;
1510 }
1511
1512 afct = afct->next;
1513 }
1514 }
1515 }
1516 }
1517
1518 /* Set up debugging before the debugger is notified for the first time. */
1519 #ifdef ELF_MACHINE_DEBUG_SETUP
1520 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1521 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1522 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1523 #else
1524 if (main_map->l_info[DT_DEBUG] != NULL)
1525 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1526 with the run-time address of the r_debug structure */
1527 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1528
1529 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1530 case you run gdb on the dynamic linker directly. */
1531 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1532 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1533 #endif
1534
1535 /* We start adding objects. */
1536 r->r_state = RT_ADD;
1537 _dl_debug_state ();
1538
1539 /* Auditing checkpoint: we are ready to signal that the initial map
1540 is being constructed. */
1541 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1542 {
1543 struct audit_ifaces *afct = GLRO(dl_audit);
1544 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1545 {
1546 if (afct->activity != NULL)
1547 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1548
1549 afct = afct->next;
1550 }
1551 }
1552
1553 /* We have two ways to specify objects to preload: via environment
1554 variable and via the file /etc/ld.so.preload. The latter can also
1555 be used when security is enabled. */
1556 assert (*first_preload == NULL);
1557 struct link_map **preloads = NULL;
1558 unsigned int npreloads = 0;
1559
1560 if (__builtin_expect (preloadlist != NULL, 0))
1561 {
1562 /* The LD_PRELOAD environment variable gives list of libraries
1563 separated by white space or colons that are loaded before the
1564 executable's dependencies and prepended to the global scope
1565 list. If the binary is running setuid all elements
1566 containing a '/' are ignored since it is insecure. */
1567 char *list = strdupa (preloadlist);
1568 char *p;
1569
1570 HP_TIMING_NOW (start);
1571
1572 /* Prevent optimizing strsep. Speed is not important here. */
1573 while ((p = (strsep) (&list, " :")) != NULL)
1574 if (p[0] != '\0'
1575 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1576 || strchr (p, '/') == NULL))
1577 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1578
1579 HP_TIMING_NOW (stop);
1580 HP_TIMING_DIFF (diff, start, stop);
1581 HP_TIMING_ACCUM_NT (load_time, diff);
1582 }
1583
1584 /* There usually is no ld.so.preload file, it should only be used
1585 for emergencies and testing. So the open call etc should usually
1586 fail. Using access() on a non-existing file is faster than using
1587 open(). So we do this first. If it succeeds we do almost twice
1588 the work but this does not matter, since it is not for production
1589 use. */
1590 static const char preload_file[] = "/etc/ld.so.preload";
1591 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1592 {
1593 /* Read the contents of the file. */
1594 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1595 PROT_READ | PROT_WRITE);
1596 if (__builtin_expect (file != MAP_FAILED, 0))
1597 {
1598 /* Parse the file. It contains names of libraries to be loaded,
1599 separated by white spaces or `:'. It may also contain
1600 comments introduced by `#'. */
1601 char *problem;
1602 char *runp;
1603 size_t rest;
1604
1605 /* Eliminate comments. */
1606 runp = file;
1607 rest = file_size;
1608 while (rest > 0)
1609 {
1610 char *comment = memchr (runp, '#', rest);
1611 if (comment == NULL)
1612 break;
1613
1614 rest -= comment - runp;
1615 do
1616 *comment = ' ';
1617 while (--rest > 0 && *++comment != '\n');
1618 }
1619
1620 /* We have one problematic case: if we have a name at the end of
1621 the file without a trailing terminating characters, we cannot
1622 place the \0. Handle the case separately. */
1623 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1624 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1625 {
1626 problem = &file[file_size];
1627 while (problem > file && problem[-1] != ' '
1628 && problem[-1] != '\t'
1629 && problem[-1] != '\n' && problem[-1] != ':')
1630 --problem;
1631
1632 if (problem > file)
1633 problem[-1] = '\0';
1634 }
1635 else
1636 {
1637 problem = NULL;
1638 file[file_size - 1] = '\0';
1639 }
1640
1641 HP_TIMING_NOW (start);
1642
1643 if (file != problem)
1644 {
1645 char *p;
1646 runp = file;
1647 while ((p = strsep (&runp, ": \t\n")) != NULL)
1648 if (p[0] != '\0')
1649 npreloads += do_preload (p, main_map, preload_file);
1650 }
1651
1652 if (problem != NULL)
1653 {
1654 char *p = strndupa (problem, file_size - (problem - file));
1655
1656 npreloads += do_preload (p, main_map, preload_file);
1657 }
1658
1659 HP_TIMING_NOW (stop);
1660 HP_TIMING_DIFF (diff, start, stop);
1661 HP_TIMING_ACCUM_NT (load_time, diff);
1662
1663 /* We don't need the file anymore. */
1664 __munmap (file, file_size);
1665 }
1666 }
1667
1668 if (__builtin_expect (*first_preload != NULL, 0))
1669 {
1670 /* Set up PRELOADS with a vector of the preloaded libraries. */
1671 struct link_map *l = *first_preload;
1672 preloads = __alloca (npreloads * sizeof preloads[0]);
1673 i = 0;
1674 do
1675 {
1676 preloads[i++] = l;
1677 l = l->l_next;
1678 } while (l);
1679 assert (i == npreloads);
1680 }
1681
1682 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1683 specified some libraries to load, these are inserted before the actual
1684 dependencies in the executable's searchlist for symbol resolution. */
1685 HP_TIMING_NOW (start);
1686 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1687 HP_TIMING_NOW (stop);
1688 HP_TIMING_DIFF (diff, start, stop);
1689 HP_TIMING_ACCUM_NT (load_time, diff);
1690
1691 /* Mark all objects as being in the global scope. */
1692 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1693 main_map->l_searchlist.r_list[--i]->l_global = 1;
1694
1695 /* Remove _dl_rtld_map from the chain. */
1696 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1697 if (GL(dl_rtld_map).l_next != NULL)
1698 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1699
1700 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1701 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1702 break;
1703
1704 bool rtld_multiple_ref = false;
1705 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1706 {
1707 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1708 put it back in the list of visible objects. We insert it into the
1709 chain in symbol search order because gdb uses the chain's order as
1710 its symbol search order. */
1711 rtld_multiple_ref = true;
1712
1713 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1714 if (__builtin_expect (mode, normal) == normal)
1715 {
1716 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1717 ? main_map->l_searchlist.r_list[i + 1]
1718 : NULL);
1719 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1720 if (GLRO(dl_sysinfo_map) != NULL
1721 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1722 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1723 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1724 #endif
1725 }
1726 else
1727 /* In trace mode there might be an invisible object (which we
1728 could not find) after the previous one in the search list.
1729 In this case it doesn't matter much where we put the
1730 interpreter object, so we just initialize the list pointer so
1731 that the assertion below holds. */
1732 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1733
1734 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1735 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1736 if (GL(dl_rtld_map).l_next != NULL)
1737 {
1738 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1739 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1740 }
1741 }
1742
1743 /* Now let us see whether all libraries are available in the
1744 versions we need. */
1745 {
1746 struct version_check_args args;
1747 args.doexit = mode == normal;
1748 args.dotrace = mode == trace;
1749 _dl_receive_error (print_missing_version, version_check_doit, &args);
1750 }
1751
1752 /* We do not initialize any of the TLS functionality unless any of the
1753 initial modules uses TLS. This makes dynamic loading of modules with
1754 TLS impossible, but to support it requires either eagerly doing setup
1755 now or lazily doing it later. Doing it now makes us incompatible with
1756 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1757 used. Trying to do it lazily is too hairy to try when there could be
1758 multiple threads (from a non-TLS-using libpthread). */
1759 bool was_tls_init_tp_called = tls_init_tp_called;
1760 if (tcbp == NULL)
1761 tcbp = init_tls ();
1762
1763 if (__builtin_expect (audit_list == NULL, 1))
1764 /* Initialize security features. But only if we have not done it
1765 earlier. */
1766 security_init ();
1767
1768 if (__builtin_expect (mode, normal) != normal)
1769 {
1770 /* We were run just to list the shared libraries. It is
1771 important that we do this before real relocation, because the
1772 functions we call below for output may no longer work properly
1773 after relocation. */
1774 struct link_map *l;
1775
1776 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1777 {
1778 struct r_scope_elem *scope = &main_map->l_searchlist;
1779
1780 for (i = 0; i < scope->r_nlist; i++)
1781 {
1782 l = scope->r_list [i];
1783 if (l->l_faked)
1784 {
1785 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1786 continue;
1787 }
1788 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1789 GLRO(dl_trace_prelink_map) = l;
1790 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1791 l->l_libname->name[0] ? l->l_libname->name
1792 : rtld_progname ?: "<main program>",
1793 l->l_name[0] ? l->l_name
1794 : rtld_progname ?: "<main program>",
1795 (int) sizeof l->l_map_start * 2,
1796 (size_t) l->l_map_start,
1797 (int) sizeof l->l_addr * 2,
1798 (size_t) l->l_addr);
1799
1800 if (l->l_tls_modid)
1801 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1802 (int) sizeof l->l_tls_offset * 2,
1803 (size_t) l->l_tls_offset);
1804 else
1805 _dl_printf ("\n");
1806 }
1807 }
1808 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1809 {
1810 /* Look through the dependencies of the main executable
1811 and determine which of them is not actually
1812 required. */
1813 struct link_map *l = main_map;
1814
1815 /* Relocate the main executable. */
1816 struct relocate_args args = { .l = l,
1817 .reloc_mode = (GLRO(dl_lazy)
1818 ? RTLD_LAZY : 0) };
1819 _dl_receive_error (print_unresolved, relocate_doit, &args);
1820
1821 /* This loop depends on the dependencies of the executable to
1822 correspond in number and order to the DT_NEEDED entries. */
1823 ElfW(Dyn) *dyn = main_map->l_ld;
1824 bool first = true;
1825 while (dyn->d_tag != DT_NULL)
1826 {
1827 if (dyn->d_tag == DT_NEEDED)
1828 {
1829 l = l->l_next;
1830
1831 if (!l->l_used)
1832 {
1833 if (first)
1834 {
1835 _dl_printf ("Unused direct dependencies:\n");
1836 first = false;
1837 }
1838
1839 _dl_printf ("\t%s\n", l->l_name);
1840 }
1841 }
1842
1843 ++dyn;
1844 }
1845
1846 _exit (first != true);
1847 }
1848 else if (! main_map->l_info[DT_NEEDED])
1849 _dl_printf ("\tstatically linked\n");
1850 else
1851 {
1852 for (l = main_map->l_next; l; l = l->l_next)
1853 if (l->l_faked)
1854 /* The library was not found. */
1855 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1856 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1857 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1858 (int) sizeof l->l_map_start * 2,
1859 (size_t) l->l_map_start);
1860 else
1861 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1862 l->l_name, (int) sizeof l->l_map_start * 2,
1863 (size_t) l->l_map_start);
1864 }
1865
1866 if (__builtin_expect (mode, trace) != trace)
1867 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1868 {
1869 const ElfW(Sym) *ref = NULL;
1870 ElfW(Addr) loadbase;
1871 lookup_t result;
1872
1873 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1874 &ref, main_map->l_scope,
1875 NULL, ELF_RTYPE_CLASS_PLT,
1876 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1877
1878 loadbase = LOOKUP_VALUE_ADDRESS (result);
1879
1880 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1881 INTUSE(_dl_argv)[i],
1882 (int) sizeof ref->st_value * 2,
1883 (size_t) ref->st_value,
1884 (int) sizeof loadbase * 2, (size_t) loadbase);
1885 }
1886 else
1887 {
1888 /* If LD_WARN is set, warn about undefined symbols. */
1889 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1890 {
1891 /* We have to do symbol dependency testing. */
1892 struct relocate_args args;
1893 struct link_map *l;
1894
1895 args.reloc_mode = GLRO(dl_lazy) ? RTLD_LAZY : 0;
1896
1897 l = main_map;
1898 while (l->l_next != NULL)
1899 l = l->l_next;
1900 do
1901 {
1902 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1903 {
1904 args.l = l;
1905 _dl_receive_error (print_unresolved, relocate_doit,
1906 &args);
1907 }
1908 l = l->l_prev;
1909 }
1910 while (l != NULL);
1911
1912 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1913 && rtld_multiple_ref)
1914 {
1915 /* Mark the link map as not yet relocated again. */
1916 GL(dl_rtld_map).l_relocated = 0;
1917 _dl_relocate_object (&GL(dl_rtld_map),
1918 main_map->l_scope, 0, 0);
1919 }
1920 }
1921 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1922 if (version_info)
1923 {
1924 /* Print more information. This means here, print information
1925 about the versions needed. */
1926 int first = 1;
1927 struct link_map *map;
1928
1929 for (map = main_map; map != NULL; map = map->l_next)
1930 {
1931 const char *strtab;
1932 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1933 ElfW(Verneed) *ent;
1934
1935 if (dyn == NULL)
1936 continue;
1937
1938 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1939 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1940
1941 if (first)
1942 {
1943 _dl_printf ("\n\tVersion information:\n");
1944 first = 0;
1945 }
1946
1947 _dl_printf ("\t%s:\n",
1948 map->l_name[0] ? map->l_name : rtld_progname);
1949
1950 while (1)
1951 {
1952 ElfW(Vernaux) *aux;
1953 struct link_map *needed;
1954
1955 needed = find_needed (strtab + ent->vn_file);
1956 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1957
1958 while (1)
1959 {
1960 const char *fname = NULL;
1961
1962 if (needed != NULL
1963 && match_version (strtab + aux->vna_name,
1964 needed))
1965 fname = needed->l_name;
1966
1967 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1968 strtab + ent->vn_file,
1969 strtab + aux->vna_name,
1970 aux->vna_flags & VER_FLG_WEAK
1971 ? "[WEAK] " : "",
1972 fname ?: "not found");
1973
1974 if (aux->vna_next == 0)
1975 /* No more symbols. */
1976 break;
1977
1978 /* Next symbol. */
1979 aux = (ElfW(Vernaux) *) ((char *) aux
1980 + aux->vna_next);
1981 }
1982
1983 if (ent->vn_next == 0)
1984 /* No more dependencies. */
1985 break;
1986
1987 /* Next dependency. */
1988 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1989 }
1990 }
1991 }
1992 }
1993
1994 _exit (0);
1995 }
1996
1997 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
1998 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
1999 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2000 {
2001 ElfW(Lib) *liblist, *liblistend;
2002 struct link_map **r_list, **r_listend, *l;
2003 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2004
2005 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2006 liblist = (ElfW(Lib) *)
2007 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2008 liblistend = (ElfW(Lib) *)
2009 ((char *) liblist +
2010 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2011 r_list = main_map->l_searchlist.r_list;
2012 r_listend = r_list + main_map->l_searchlist.r_nlist;
2013
2014 for (; r_list < r_listend && liblist < liblistend; r_list++)
2015 {
2016 l = *r_list;
2017
2018 if (l == main_map)
2019 continue;
2020
2021 /* If the library is not mapped where it should, fail. */
2022 if (l->l_addr)
2023 break;
2024
2025 /* Next, check if checksum matches. */
2026 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2027 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2028 != liblist->l_checksum)
2029 break;
2030
2031 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2032 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2033 != liblist->l_time_stamp)
2034 break;
2035
2036 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2037 break;
2038
2039 ++liblist;
2040 }
2041
2042
2043 if (r_list == r_listend && liblist == liblistend)
2044 prelinked = true;
2045
2046 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2047 _dl_debug_printf ("\nprelink checking: %s\n",
2048 prelinked ? "ok" : "failed");
2049 }
2050
2051
2052 /* Now set up the variable which helps the assembler startup code. */
2053 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2054
2055 /* Save the information about the original global scope list since
2056 we need it in the memory handling later. */
2057 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2058
2059 /* Remember the last search directory added at startup, now that
2060 malloc will no longer be the one from dl-minimal.c. */
2061 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2062
2063 /* Print scope information. */
2064 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
2065 {
2066 _dl_debug_printf ("\nInitial object scopes\n");
2067
2068 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2069 _dl_show_scope (l, 0);
2070 }
2071
2072 if (prelinked)
2073 {
2074 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2075 {
2076 ElfW(Rela) *conflict, *conflictend;
2077 #ifndef HP_TIMING_NONAVAIL
2078 hp_timing_t start;
2079 hp_timing_t stop;
2080 #endif
2081
2082 HP_TIMING_NOW (start);
2083 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2084 conflict = (ElfW(Rela) *)
2085 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2086 conflictend = (ElfW(Rela) *)
2087 ((char *) conflict
2088 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2089 _dl_resolve_conflicts (main_map, conflict, conflictend);
2090 HP_TIMING_NOW (stop);
2091 HP_TIMING_DIFF (relocate_time, start, stop);
2092 }
2093
2094
2095 /* Mark all the objects so we know they have been already relocated. */
2096 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2097 {
2098 l->l_relocated = 1;
2099 if (l->l_relro_size)
2100 _dl_protect_relro (l);
2101
2102 /* Add object to slot information data if necessasy. */
2103 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2104 _dl_add_to_slotinfo (l);
2105 }
2106 }
2107 else
2108 {
2109 /* Now we have all the objects loaded. Relocate them all except for
2110 the dynamic linker itself. We do this in reverse order so that copy
2111 relocs of earlier objects overwrite the data written by later
2112 objects. We do not re-relocate the dynamic linker itself in this
2113 loop because that could result in the GOT entries for functions we
2114 call being changed, and that would break us. It is safe to relocate
2115 the dynamic linker out of order because it has no copy relocs (we
2116 know that because it is self-contained). */
2117
2118 int consider_profiling = GLRO(dl_profile) != NULL;
2119 #ifndef HP_TIMING_NONAVAIL
2120 hp_timing_t start;
2121 hp_timing_t stop;
2122 #endif
2123
2124 /* If we are profiling we also must do lazy reloaction. */
2125 GLRO(dl_lazy) |= consider_profiling;
2126
2127 HP_TIMING_NOW (start);
2128 unsigned i = main_map->l_searchlist.r_nlist;
2129 while (i-- > 0)
2130 {
2131 struct link_map *l = main_map->l_initfini[i];
2132
2133 /* While we are at it, help the memory handling a bit. We have to
2134 mark some data structures as allocated with the fake malloc()
2135 implementation in ld.so. */
2136 struct libname_list *lnp = l->l_libname->next;
2137
2138 while (__builtin_expect (lnp != NULL, 0))
2139 {
2140 lnp->dont_free = 1;
2141 lnp = lnp->next;
2142 }
2143
2144 if (l != &GL(dl_rtld_map))
2145 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2146 consider_profiling);
2147
2148 /* Add object to slot information data if necessasy. */
2149 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2150 _dl_add_to_slotinfo (l);
2151 }
2152 HP_TIMING_NOW (stop);
2153
2154 HP_TIMING_DIFF (relocate_time, start, stop);
2155
2156 /* Now enable profiling if needed. Like the previous call,
2157 this has to go here because the calls it makes should use the
2158 rtld versions of the functions (particularly calloc()), but it
2159 needs to have _dl_profile_map set up by the relocator. */
2160 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2161 /* We must prepare the profiling. */
2162 _dl_start_profile ();
2163 }
2164
2165 #ifndef NONTLS_INIT_TP
2166 # define NONTLS_INIT_TP do { } while (0)
2167 #endif
2168
2169 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2170 ++GL(dl_tls_generation);
2171
2172 /* Now that we have completed relocation, the initializer data
2173 for the TLS blocks has its final values and we can copy them
2174 into the main thread's TLS area, which we allocated above. */
2175 _dl_allocate_tls_init (tcbp);
2176
2177 /* And finally install it for the main thread. If ld.so itself uses
2178 TLS we know the thread pointer was initialized earlier. */
2179 if (! tls_init_tp_called)
2180 {
2181 const char *lossage = TLS_INIT_TP (tcbp, 0);
2182 if (__builtin_expect (lossage != NULL, 0))
2183 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2184 lossage);
2185 }
2186
2187 /* Make sure no new search directories have been added. */
2188 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
2189
2190 if (! prelinked && rtld_multiple_ref)
2191 {
2192 /* There was an explicit ref to the dynamic linker as a shared lib.
2193 Re-relocate ourselves with user-controlled symbol definitions.
2194
2195 We must do this after TLS initialization in case after this
2196 re-relocation, we might call a user-supplied function
2197 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2198
2199 #ifndef HP_TIMING_NONAVAIL
2200 hp_timing_t start;
2201 hp_timing_t stop;
2202 hp_timing_t add;
2203 #endif
2204
2205 HP_TIMING_NOW (start);
2206 /* Mark the link map as not yet relocated again. */
2207 GL(dl_rtld_map).l_relocated = 0;
2208 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2209 HP_TIMING_NOW (stop);
2210 HP_TIMING_DIFF (add, start, stop);
2211 HP_TIMING_ACCUM_NT (relocate_time, add);
2212 }
2213
2214 /* Do any necessary cleanups for the startup OS interface code.
2215 We do these now so that no calls are made after rtld re-relocation
2216 which might be resolved to different functions than we expect.
2217 We cannot do this before relocating the other objects because
2218 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2219 _dl_sysdep_start_cleanup ();
2220
2221 #ifdef SHARED
2222 /* Auditing checkpoint: we have added all objects. */
2223 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2224 {
2225 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2226 /* Do not call the functions for any auditing object. */
2227 if (head->l_auditing == 0)
2228 {
2229 struct audit_ifaces *afct = GLRO(dl_audit);
2230 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2231 {
2232 if (afct->activity != NULL)
2233 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2234
2235 afct = afct->next;
2236 }
2237 }
2238 }
2239 #endif
2240
2241 /* Notify the debugger all new objects are now ready to go. We must re-get
2242 the address since by now the variable might be in another object. */
2243 r = _dl_debug_initialize (0, LM_ID_BASE);
2244 r->r_state = RT_CONSISTENT;
2245 _dl_debug_state ();
2246
2247 #ifndef MAP_COPY
2248 /* We must munmap() the cache file. */
2249 _dl_unload_cache ();
2250 #endif
2251
2252 /* Once we return, _dl_sysdep_start will invoke
2253 the DT_INIT functions and then *USER_ENTRY. */
2254 }
2255 \f
2256 /* This is a little helper function for resolving symbols while
2257 tracing the binary. */
2258 static void
2259 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2260 const char *errstring)
2261 {
2262 if (objname[0] == '\0')
2263 objname = rtld_progname ?: "<main program>";
2264 _dl_error_printf ("%s (%s)\n", errstring, objname);
2265 }
2266 \f
2267 /* This is a little helper function for resolving symbols while
2268 tracing the binary. */
2269 static void
2270 print_missing_version (int errcode __attribute__ ((unused)),
2271 const char *objname, const char *errstring)
2272 {
2273 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2274 objname, errstring);
2275 }
2276 \f
2277 /* Nonzero if any of the debugging options is enabled. */
2278 static int any_debug attribute_relro;
2279
2280 /* Process the string given as the parameter which explains which debugging
2281 options are enabled. */
2282 static void
2283 process_dl_debug (const char *dl_debug)
2284 {
2285 /* When adding new entries make sure that the maximal length of a name
2286 is correctly handled in the LD_DEBUG_HELP code below. */
2287 static const struct
2288 {
2289 unsigned char len;
2290 const char name[10];
2291 const char helptext[41];
2292 unsigned short int mask;
2293 } debopts[] =
2294 {
2295 #define LEN_AND_STR(str) sizeof (str) - 1, str
2296 { LEN_AND_STR ("libs"), "display library search paths",
2297 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2298 { LEN_AND_STR ("reloc"), "display relocation processing",
2299 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2300 { LEN_AND_STR ("files"), "display progress for input file",
2301 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2302 { LEN_AND_STR ("symbols"), "display symbol table processing",
2303 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2304 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2305 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2306 { LEN_AND_STR ("versions"), "display version dependencies",
2307 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2308 { LEN_AND_STR ("scopes"), "display scope information",
2309 DL_DEBUG_SCOPES },
2310 { LEN_AND_STR ("all"), "all previous options combined",
2311 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2312 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2313 | DL_DEBUG_SCOPES },
2314 { LEN_AND_STR ("statistics"), "display relocation statistics",
2315 DL_DEBUG_STATISTICS },
2316 { LEN_AND_STR ("unused"), "determined unused DSOs",
2317 DL_DEBUG_UNUSED },
2318 { LEN_AND_STR ("help"), "display this help message and exit",
2319 DL_DEBUG_HELP },
2320 };
2321 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2322
2323 /* Skip separating white spaces and commas. */
2324 while (*dl_debug != '\0')
2325 {
2326 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2327 {
2328 size_t cnt;
2329 size_t len = 1;
2330
2331 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2332 && dl_debug[len] != ',' && dl_debug[len] != ':')
2333 ++len;
2334
2335 for (cnt = 0; cnt < ndebopts; ++cnt)
2336 if (debopts[cnt].len == len
2337 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2338 {
2339 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2340 any_debug = 1;
2341 break;
2342 }
2343
2344 if (cnt == ndebopts)
2345 {
2346 /* Display a warning and skip everything until next
2347 separator. */
2348 char *copy = strndupa (dl_debug, len);
2349 _dl_error_printf ("\
2350 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2351 }
2352
2353 dl_debug += len;
2354 continue;
2355 }
2356
2357 ++dl_debug;
2358 }
2359
2360 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2361 {
2362 size_t cnt;
2363
2364 _dl_printf ("\
2365 Valid options for the LD_DEBUG environment variable are:\n\n");
2366
2367 for (cnt = 0; cnt < ndebopts; ++cnt)
2368 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2369 " " + debopts[cnt].len - 3,
2370 debopts[cnt].helptext);
2371
2372 _dl_printf ("\n\
2373 To direct the debugging output into a file instead of standard output\n\
2374 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2375 _exit (0);
2376 }
2377 }
2378 \f
2379 static void
2380 process_dl_audit (char *str)
2381 {
2382 /* The parameter is a colon separated list of DSO names. */
2383 char *p;
2384
2385 while ((p = (strsep) (&str, ":")) != NULL)
2386 if (p[0] != '\0'
2387 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2388 || strchr (p, '/') == NULL))
2389 {
2390 /* This is using the local malloc, not the system malloc. The
2391 memory can never be freed. */
2392 struct audit_list *newp = malloc (sizeof (*newp));
2393 newp->name = p;
2394
2395 if (audit_list == NULL)
2396 audit_list = newp->next = newp;
2397 else
2398 {
2399 newp->next = audit_list->next;
2400 audit_list = audit_list->next = newp;
2401 }
2402 }
2403 }
2404 \f
2405 /* Process all environments variables the dynamic linker must recognize.
2406 Since all of them start with `LD_' we are a bit smarter while finding
2407 all the entries. */
2408 extern char **_environ attribute_hidden;
2409
2410
2411 static void
2412 process_envvars (enum mode *modep)
2413 {
2414 char **runp = _environ;
2415 char *envline;
2416 enum mode mode = normal;
2417 char *debug_output = NULL;
2418
2419 /* This is the default place for profiling data file. */
2420 GLRO(dl_profile_output)
2421 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2422
2423 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2424 {
2425 size_t len = 0;
2426
2427 while (envline[len] != '\0' && envline[len] != '=')
2428 ++len;
2429
2430 if (envline[len] != '=')
2431 /* This is a "LD_" variable at the end of the string without
2432 a '=' character. Ignore it since otherwise we will access
2433 invalid memory below. */
2434 continue;
2435
2436 switch (len)
2437 {
2438 case 4:
2439 /* Warning level, verbose or not. */
2440 if (memcmp (envline, "WARN", 4) == 0)
2441 GLRO(dl_verbose) = envline[5] != '\0';
2442 break;
2443
2444 case 5:
2445 /* Debugging of the dynamic linker? */
2446 if (memcmp (envline, "DEBUG", 5) == 0)
2447 {
2448 process_dl_debug (&envline[6]);
2449 break;
2450 }
2451 if (memcmp (envline, "AUDIT", 5) == 0)
2452 process_dl_audit (&envline[6]);
2453 break;
2454
2455 case 7:
2456 /* Print information about versions. */
2457 if (memcmp (envline, "VERBOSE", 7) == 0)
2458 {
2459 version_info = envline[8] != '\0';
2460 break;
2461 }
2462
2463 /* List of objects to be preloaded. */
2464 if (memcmp (envline, "PRELOAD", 7) == 0)
2465 {
2466 preloadlist = &envline[8];
2467 break;
2468 }
2469
2470 /* Which shared object shall be profiled. */
2471 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2472 GLRO(dl_profile) = &envline[8];
2473 break;
2474
2475 case 8:
2476 /* Do we bind early? */
2477 if (memcmp (envline, "BIND_NOW", 8) == 0)
2478 {
2479 GLRO(dl_lazy) = envline[9] == '\0';
2480 break;
2481 }
2482 if (memcmp (envline, "BIND_NOT", 8) == 0)
2483 GLRO(dl_bind_not) = envline[9] != '\0';
2484 break;
2485
2486 case 9:
2487 /* Test whether we want to see the content of the auxiliary
2488 array passed up from the kernel. */
2489 if (!INTUSE(__libc_enable_secure)
2490 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2491 _dl_show_auxv ();
2492 break;
2493
2494 case 10:
2495 /* Mask for the important hardware capabilities. */
2496 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2497 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2498 0, 0);
2499 break;
2500
2501 case 11:
2502 /* Path where the binary is found. */
2503 if (!INTUSE(__libc_enable_secure)
2504 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2505 GLRO(dl_origin_path) = &envline[12];
2506 break;
2507
2508 case 12:
2509 /* The library search path. */
2510 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2511 {
2512 library_path = &envline[13];
2513 break;
2514 }
2515
2516 /* Where to place the profiling data file. */
2517 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2518 {
2519 debug_output = &envline[13];
2520 break;
2521 }
2522
2523 if (!INTUSE(__libc_enable_secure)
2524 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2525 GLRO(dl_dynamic_weak) = 1;
2526 break;
2527
2528 case 13:
2529 /* We might have some extra environment variable with length 13
2530 to handle. */
2531 #ifdef EXTRA_LD_ENVVARS_13
2532 EXTRA_LD_ENVVARS_13
2533 #endif
2534 if (!INTUSE(__libc_enable_secure)
2535 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2536 {
2537 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2538 break;
2539 }
2540
2541 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2542 GLRO(dl_pointer_guard) = envline[14] != '0';
2543 break;
2544
2545 case 14:
2546 /* Where to place the profiling data file. */
2547 if (!INTUSE(__libc_enable_secure)
2548 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2549 && envline[15] != '\0')
2550 GLRO(dl_profile_output) = &envline[15];
2551 break;
2552
2553 case 16:
2554 /* The mode of the dynamic linker can be set. */
2555 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2556 {
2557 mode = trace;
2558 GLRO(dl_verbose) = 1;
2559 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2560 GLRO(dl_trace_prelink) = &envline[17];
2561 }
2562 break;
2563
2564 case 20:
2565 /* The mode of the dynamic linker can be set. */
2566 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2567 mode = trace;
2568 break;
2569
2570 /* We might have some extra environment variable to handle. This
2571 is tricky due to the pre-processing of the length of the name
2572 in the switch statement here. The code here assumes that added
2573 environment variables have a different length. */
2574 #ifdef EXTRA_LD_ENVVARS
2575 EXTRA_LD_ENVVARS
2576 #endif
2577 }
2578 }
2579
2580 /* The caller wants this information. */
2581 *modep = mode;
2582
2583 /* Extra security for SUID binaries. Remove all dangerous environment
2584 variables. */
2585 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2586 {
2587 static const char unsecure_envvars[] =
2588 #ifdef EXTRA_UNSECURE_ENVVARS
2589 EXTRA_UNSECURE_ENVVARS
2590 #endif
2591 UNSECURE_ENVVARS;
2592 const char *nextp;
2593
2594 nextp = unsecure_envvars;
2595 do
2596 {
2597 unsetenv (nextp);
2598 /* We could use rawmemchr but this need not be fast. */
2599 nextp = (char *) (strchr) (nextp, '\0') + 1;
2600 }
2601 while (*nextp != '\0');
2602
2603 if (__access ("/etc/suid-debug", F_OK) != 0)
2604 {
2605 unsetenv ("MALLOC_CHECK_");
2606 GLRO(dl_debug_mask) = 0;
2607 }
2608
2609 if (mode != normal)
2610 _exit (5);
2611 }
2612 /* If we have to run the dynamic linker in debugging mode and the
2613 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2614 messages to this file. */
2615 else if (any_debug && debug_output != NULL)
2616 {
2617 #ifdef O_NOFOLLOW
2618 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2619 #else
2620 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2621 #endif
2622 size_t name_len = strlen (debug_output);
2623 char buf[name_len + 12];
2624 char *startp;
2625
2626 buf[name_len + 11] = '\0';
2627 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2628 *--startp = '.';
2629 startp = memcpy (startp - name_len, debug_output, name_len);
2630
2631 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2632 if (GLRO(dl_debug_fd) == -1)
2633 /* We use standard output if opening the file failed. */
2634 GLRO(dl_debug_fd) = STDOUT_FILENO;
2635 }
2636 }
2637
2638
2639 /* Print the various times we collected. */
2640 static void
2641 __attribute ((noinline))
2642 print_statistics (hp_timing_t *rtld_total_timep)
2643 {
2644 #ifndef HP_TIMING_NONAVAIL
2645 char buf[200];
2646 char *cp;
2647 char *wp;
2648
2649 /* Total time rtld used. */
2650 if (HP_TIMING_AVAIL)
2651 {
2652 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2653 _dl_debug_printf ("\nruntime linker statistics:\n"
2654 " total startup time in dynamic loader: %s\n", buf);
2655
2656 /* Print relocation statistics. */
2657 char pbuf[30];
2658 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2659 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2660 pbuf + sizeof (pbuf), 10, 0);
2661 wp = pbuf;
2662 switch (pbuf + sizeof (pbuf) - cp)
2663 {
2664 case 3:
2665 *wp++ = *cp++;
2666 case 2:
2667 *wp++ = *cp++;
2668 case 1:
2669 *wp++ = '.';
2670 *wp++ = *cp++;
2671 }
2672 *wp = '\0';
2673 _dl_debug_printf ("\
2674 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2675 }
2676 #endif
2677
2678 unsigned long int num_relative_relocations = 0;
2679 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2680 {
2681 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2682 continue;
2683
2684 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2685
2686 for (unsigned int i = 0; i < scope->r_nlist; i++)
2687 {
2688 struct link_map *l = scope->r_list [i];
2689
2690 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2691 num_relative_relocations
2692 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2693 #ifndef ELF_MACHINE_REL_RELATIVE
2694 /* Relative relocations are processed on these architectures if
2695 library is loaded to different address than p_vaddr or
2696 if not prelinked. */
2697 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2698 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2699 #else
2700 /* On e.g. IA-64 or Alpha, relative relocations are processed
2701 only if library is loaded to different address than p_vaddr. */
2702 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2703 #endif
2704 num_relative_relocations
2705 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2706 }
2707 }
2708
2709 _dl_debug_printf (" number of relocations: %lu\n"
2710 " number of relocations from cache: %lu\n"
2711 " number of relative relocations: %lu\n",
2712 GL(dl_num_relocations),
2713 GL(dl_num_cache_relocations),
2714 num_relative_relocations);
2715
2716 #ifndef HP_TIMING_NONAVAIL
2717 /* Time spend while loading the object and the dependencies. */
2718 if (HP_TIMING_AVAIL)
2719 {
2720 char pbuf[30];
2721 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2722 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2723 pbuf + sizeof (pbuf), 10, 0);
2724 wp = pbuf;
2725 switch (pbuf + sizeof (pbuf) - cp)
2726 {
2727 case 3:
2728 *wp++ = *cp++;
2729 case 2:
2730 *wp++ = *cp++;
2731 case 1:
2732 *wp++ = '.';
2733 *wp++ = *cp++;
2734 }
2735 *wp = '\0';
2736 _dl_debug_printf ("\
2737 time needed to load objects: %s (%s%%)\n",
2738 buf, pbuf);
2739 }
2740 #endif
2741 }