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