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