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