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