1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
5 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
6 * Copyright 2009-2013 Konstantin Belousov <kib@FreeBSD.ORG>.
7 * Copyright 2012 John Marino <draco@marino.st>.
8 * Copyright 2014-2017 The FreeBSD Foundation
9 * All rights reserved.
10 *
11 * Portions of this software were developed by Konstantin Belousov
12 * under sponsorship from the FreeBSD Foundation.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 /*
36 * Dynamic linker for ELF.
37 *
38 * John Polstra <jdp@polstra.com>.
39 */
40
41 #include <sys/param.h>
42 #include <sys/ktrace.h>
43 #include <sys/mman.h>
44 #include <sys/mount.h>
45 #include <sys/stat.h>
46 #include <sys/sysctl.h>
47 #include <sys/uio.h>
48 #include <sys/utsname.h>
49
50 #include <dlfcn.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <stdarg.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59
60 #include "debug.h"
61 #include "libmap.h"
62 #include "notes.h"
63 #include "rtld.h"
64 #include "rtld_libc.h"
65 #include "rtld_malloc.h"
66 #include "rtld_paths.h"
67 #include "rtld_printf.h"
68 #include "rtld_tls.h"
69 #include "rtld_utrace.h"
70
71 /* Types. */
72 typedef void (*func_ptr_type)(void);
73 typedef void *(*path_enum_proc)(const char *path, size_t len, void *arg);
74
75 /* Variables that cannot be static: */
76 extern struct r_debug r_debug; /* For GDB */
77 extern int _thread_autoinit_dummy_decl;
78 extern void (*__cleanup)(void);
79
80 struct dlerror_save {
81 int seen;
82 char *msg;
83 };
84
85 struct tcb_list_entry {
86 TAILQ_ENTRY(tcb_list_entry) next;
87 };
88
89 /*
90 * Function declarations.
91 */
92 static bool allocate_tls_offset_common(size_t *offp, size_t tlssize,
93 size_t tlsalign, size_t tlspoffset);
94 static const char *basename(const char *);
95 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
96 const Elf_Dyn **, const Elf_Dyn **);
97 static bool digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
98 const Elf_Dyn *);
99 static bool digest_dynamic(Obj_Entry *, int);
100 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
101 static void distribute_static_tls(Objlist *);
102 static Obj_Entry *dlcheck(void *);
103 static int dlclose_locked(void *, RtldLockState *);
104 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
105 int lo_flags, int mode, RtldLockState *lockstate);
106 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
107 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
108 static bool donelist_check(DoneList *, const Obj_Entry *);
109 static void dump_auxv(Elf_Auxinfo **aux_info);
110 static void errmsg_restore(struct dlerror_save *);
111 static struct dlerror_save *errmsg_save(void);
112 static void *fill_search_info(const char *, size_t, void *);
113 static char *find_library(const char *, const Obj_Entry *, int *);
114 static const char *gethints(bool);
115 static void hold_object(Obj_Entry *);
116 static void unhold_object(Obj_Entry *);
117 static void init_dag(Obj_Entry *);
118 static void init_marker(Obj_Entry *);
119 static void init_pagesizes(Elf_Auxinfo **aux_info);
120 static void init_rtld(caddr_t, Elf_Auxinfo **);
121 static void initlist_add_neededs(Needed_Entry *, Objlist *, Objlist *);
122 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *,
123 Objlist *);
124 static void initlist_for_loaded_obj(Obj_Entry *obj, Obj_Entry *tail,
125 Objlist *list);
126 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *);
127 static void linkmap_add(Obj_Entry *);
128 static void linkmap_delete(Obj_Entry *);
129 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
130 static void unload_filtees(Obj_Entry *, RtldLockState *);
131 static int load_needed_objects(Obj_Entry *, int);
132 static int load_preload_objects(const char *, bool);
133 static int load_kpreload(const void *addr);
134 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
135 static void map_stacks_exec(RtldLockState *);
136 static int obj_disable_relro(Obj_Entry *);
137 static int obj_enforce_relro(Obj_Entry *);
138 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
139 static void objlist_call_init(Objlist *, RtldLockState *);
140 static void objlist_clear(Objlist *);
141 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
142 static void objlist_init(Objlist *);
143 static void objlist_push_head(Objlist *, Obj_Entry *);
144 static void objlist_push_tail(Objlist *, Obj_Entry *);
145 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
146 static void objlist_remove(Objlist *, Obj_Entry *);
147 static int open_binary_fd(const char *argv0, bool search_in_path,
148 const char **binpath_res);
149 static int parse_args(char *argv[], int argc, bool *use_pathp, int *fdp,
150 const char **argv0, bool *dir_ignore);
151 static int parse_integer(const char *);
152 static void *path_enumerate(const char *, path_enum_proc, const char *, void *);
153 static void print_usage(const char *argv0);
154 static void release_object(Obj_Entry *);
155 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
156 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
157 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
158 int flags, RtldLockState *lockstate);
159 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
160 RtldLockState *);
161 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *);
162 static int rtld_dirname(const char *, char *);
163 static int rtld_dirname_abs(const char *, char *);
164 static void *rtld_dlopen(const char *name, int fd, int mode);
165 static void rtld_exit(void);
166 static void rtld_nop_exit(void);
167 static char *search_library_path(const char *, const char *, const char *,
168 int *);
169 static char *search_library_pathfds(const char *, const char *, int *);
170 static const void **get_program_var_addr(const char *, RtldLockState *);
171 static void set_program_var(const char *, const void *);
172 static int symlook_default(SymLook *, const Obj_Entry *refobj);
173 static int symlook_global(SymLook *, DoneList *);
174 static void symlook_init_from_req(SymLook *, const SymLook *);
175 static int symlook_list(SymLook *, const Objlist *, DoneList *);
176 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
177 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
178 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
179 static void *tls_get_addr_slow(struct tcb *, int, size_t, bool) __noinline;
180 static void trace_loaded_objects(Obj_Entry *, bool);
181 static void unlink_object(Obj_Entry *);
182 static void unload_object(Obj_Entry *, RtldLockState *lockstate);
183 static void unref_dag(Obj_Entry *);
184 static void ref_dag(Obj_Entry *);
185 static char *origin_subst_one(Obj_Entry *, char *, const char *, const char *,
186 bool);
187 static char *origin_subst(Obj_Entry *, const char *);
188 static bool obj_resolve_origin(Obj_Entry *obj);
189 static void preinit_main(void);
190 static int rtld_verify_versions(const Objlist *);
191 static int rtld_verify_object_versions(Obj_Entry *);
192 static void object_add_name(Obj_Entry *, const char *);
193 static int object_match_name(const Obj_Entry *, const char *);
194 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
195 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
196 struct dl_phdr_info *phdr_info);
197 static uint32_t gnu_hash(const char *);
198 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
199 const unsigned long);
200
201 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported;
202 void _r_debug_postinit(struct link_map *) __noinline __exported;
203
204 int __sys_openat(int, const char *, int, ...);
205
206 /*
207 * Data declarations.
208 */
209 struct r_debug r_debug __exported; /* for GDB; */
210 static bool libmap_disable; /* Disable libmap */
211 static bool ld_loadfltr; /* Immediate filters processing */
212 static const char *libmap_override; /* Maps to use in addition to libmap.conf */
213 static bool trust; /* False for setuid and setgid programs */
214 static bool dangerous_ld_env; /* True if environment variables have been
215 used to affect the libraries loaded */
216 bool ld_bind_not; /* Disable PLT update */
217 static const char *ld_bind_now; /* Environment variable for immediate binding */
218 static const char *ld_debug; /* Environment variable for debugging */
219 static bool ld_dynamic_weak = true; /* True if non-weak definition overrides
220 weak definition */
221 static const char *ld_library_path; /* Environment variable for search path */
222 static const char
223 *ld_library_dirs; /* Environment variable for library descriptors */
224 static const char *ld_preload; /* Environment variable for libraries to
225 load first */
226 static const char *ld_preload_fds; /* Environment variable for libraries
227 represented by descriptors */
228 static const char
229 *ld_elf_hints_path; /* Environment variable for alternative hints path */
230 static const char *ld_tracing; /* Called from ldd to print libs */
231 static const char *ld_utrace; /* Use utrace() to log events. */
232 static struct obj_entry_q obj_list; /* Queue of all loaded objects */
233 static Obj_Entry *obj_main; /* The main program shared object */
234 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
235 static unsigned int obj_count; /* Number of objects in obj_list */
236 static unsigned int obj_loads; /* Number of loads of objects (gen count) */
237 size_t ld_static_tls_extra = /* Static TLS extra space (bytes) */
238 RTLD_STATIC_TLS_EXTRA;
239
240 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
241 STAILQ_HEAD_INITIALIZER(list_global);
242 static Objlist list_main = /* Objects loaded at program startup */
243 STAILQ_HEAD_INITIALIZER(list_main);
244 static Objlist list_fini = /* Objects needing fini() calls */
245 STAILQ_HEAD_INITIALIZER(list_fini);
246
247 Elf_Sym sym_zero; /* For resolving undefined weak refs. */
248
249 #define GDB_STATE(s, m) \
250 r_debug.r_state = s; \
251 r_debug_state(&r_debug, m);
252
253 extern Elf_Dyn _DYNAMIC;
254 #pragma weak _DYNAMIC
255
256 int dlclose(void *) __exported;
257 char *dlerror(void) __exported;
258 void *dlopen(const char *, int) __exported;
259 void *fdlopen(int, int) __exported;
260 void *dlsym(void *, const char *) __exported;
261 dlfunc_t dlfunc(void *, const char *) __exported;
262 void *dlvsym(void *, const char *, const char *) __exported;
263 int dladdr(const void *, Dl_info *) __exported;
264 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *),
265 void (*)(void *), void (*)(void *), void (*)(void *)) __exported;
266 int dlinfo(void *, int, void *) __exported;
267 int _dl_iterate_phdr_locked(__dl_iterate_hdr_callback, void *) __exported;
268 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported;
269 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported;
270 int _rtld_get_stack_prot(void) __exported;
271 int _rtld_is_dlopened(void *) __exported;
272 void _rtld_error(const char *, ...) __exported;
273 const char *rtld_get_var(const char *name) __exported;
274 int rtld_set_var(const char *name, const char *val) __exported;
275
276 /* Only here to fix -Wmissing-prototypes warnings */
277 int __getosreldate(void);
278 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp);
279 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff);
280
281 int npagesizes;
282 static int osreldate;
283 size_t *pagesizes;
284 size_t page_size;
285
286 static int stack_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
287 static int max_stack_flags;
288
289 /*
290 * Global declarations normally provided by crt1. The dynamic linker is
291 * not built with crt1, so we have to provide them ourselves.
292 */
293 char *__progname;
294 char **environ;
295
296 /*
297 * Used to pass argc, argv to init functions.
298 */
299 int main_argc;
300 char **main_argv;
301
302 /*
303 * Globals to control TLS allocation.
304 */
305 size_t tls_last_offset; /* Static TLS offset of last module */
306 size_t tls_last_size; /* Static TLS size of last module */
307 size_t tls_static_space; /* Static TLS space allocated */
308 static size_t tls_static_max_align;
309 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */
310 int tls_max_index = 1; /* Largest module index allocated */
311
312 static TAILQ_HEAD(, tcb_list_entry) tcb_list =
313 TAILQ_HEAD_INITIALIZER(tcb_list);
314 static size_t tcb_list_entry_offset;
315
316 static bool ld_library_path_rpath = false;
317 bool ld_fast_sigblock = false;
318
319 /*
320 * Globals for path names, and such
321 */
322 const char *ld_elf_hints_default = _PATH_ELF_HINTS;
323 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF;
324 const char *ld_path_rtld = _PATH_RTLD;
325 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH;
326 const char *ld_env_prefix = LD_;
327
328 static void (*rtld_exit_ptr)(void);
329
330 /*
331 * Fill in a DoneList with an allocation large enough to hold all of
332 * the currently-loaded objects. Keep this as a macro since it calls
333 * alloca and we want that to occur within the scope of the caller.
334 */
335 #define donelist_init(dlp) \
336 ((dlp)->objs = alloca(obj_count * sizeof(dlp)->objs[0]), \
337 assert((dlp)->objs != NULL), (dlp)->num_alloc = obj_count, \
338 (dlp)->num_used = 0)
339
340 #define LD_UTRACE(e, h, mb, ms, r, n) \
341 do { \
342 if (ld_utrace != NULL) \
343 ld_utrace_log(e, h, mb, ms, r, n); \
344 } while (0)
345
346 static void
ld_utrace_log(int event,void * handle,void * mapbase,size_t mapsize,int refcnt,const char * name)347 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
348 int refcnt, const char *name)
349 {
350 struct utrace_rtld ut;
351 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG;
352
353 memset(&ut, 0, sizeof(ut)); /* clear holes */
354 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig));
355 ut.event = event;
356 ut.handle = handle;
357 ut.mapbase = mapbase;
358 ut.mapsize = mapsize;
359 ut.refcnt = refcnt;
360 if (name != NULL)
361 strlcpy(ut.name, name, sizeof(ut.name));
362 utrace(&ut, sizeof(ut));
363 }
364
365 struct ld_env_var_desc {
366 const char *const n;
367 const char *val;
368 const bool unsecure : 1;
369 const bool can_update : 1;
370 const bool debug : 1;
371 bool owned : 1;
372 };
373 #define LD_ENV_DESC(var, unsec, ...) \
374 [LD_##var] = { .n = #var, .unsecure = unsec, __VA_ARGS__ }
375
376 static struct ld_env_var_desc ld_env_vars[] = {
377 LD_ENV_DESC(BIND_NOW, false),
378 LD_ENV_DESC(PRELOAD, true),
379 LD_ENV_DESC(LIBMAP, true),
380 LD_ENV_DESC(LIBRARY_PATH, true, .can_update = true),
381 LD_ENV_DESC(LIBRARY_PATH_FDS, true, .can_update = true),
382 LD_ENV_DESC(LIBMAP_DISABLE, true),
383 LD_ENV_DESC(BIND_NOT, true),
384 LD_ENV_DESC(DEBUG, true, .can_update = true, .debug = true),
385 LD_ENV_DESC(ELF_HINTS_PATH, true),
386 LD_ENV_DESC(LOADFLTR, true),
387 LD_ENV_DESC(LIBRARY_PATH_RPATH, true, .can_update = true),
388 LD_ENV_DESC(PRELOAD_FDS, true),
389 LD_ENV_DESC(DYNAMIC_WEAK, true, .can_update = true),
390 LD_ENV_DESC(TRACE_LOADED_OBJECTS, false),
391 LD_ENV_DESC(UTRACE, false, .can_update = true),
392 LD_ENV_DESC(DUMP_REL_PRE, false, .can_update = true),
393 LD_ENV_DESC(DUMP_REL_POST, false, .can_update = true),
394 LD_ENV_DESC(TRACE_LOADED_OBJECTS_PROGNAME, false),
395 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT1, false),
396 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT2, false),
397 LD_ENV_DESC(TRACE_LOADED_OBJECTS_ALL, false),
398 LD_ENV_DESC(SHOW_AUXV, false),
399 LD_ENV_DESC(STATIC_TLS_EXTRA, false),
400 LD_ENV_DESC(NO_DL_ITERATE_PHDR_AFTER_FORK, false),
401 };
402
403 const char *
ld_get_env_var(int idx)404 ld_get_env_var(int idx)
405 {
406 return (ld_env_vars[idx].val);
407 }
408
409 static const char *
rtld_get_env_val(char ** env,const char * name,size_t name_len)410 rtld_get_env_val(char **env, const char *name, size_t name_len)
411 {
412 char **m, *n, *v;
413
414 for (m = env; *m != NULL; m++) {
415 n = *m;
416 v = strchr(n, '=');
417 if (v == NULL) {
418 /* corrupt environment? */
419 continue;
420 }
421 if (v - n == (ptrdiff_t)name_len &&
422 strncmp(name, n, name_len) == 0)
423 return (v + 1);
424 }
425 return (NULL);
426 }
427
428 static void
rtld_init_env_vars_for_prefix(char ** env,const char * env_prefix)429 rtld_init_env_vars_for_prefix(char **env, const char *env_prefix)
430 {
431 struct ld_env_var_desc *lvd;
432 size_t prefix_len, nlen;
433 char **m, *n, *v;
434 int i;
435
436 prefix_len = strlen(env_prefix);
437 for (m = env; *m != NULL; m++) {
438 n = *m;
439 if (strncmp(env_prefix, n, prefix_len) != 0) {
440 /* Not a rtld environment variable. */
441 continue;
442 }
443 n += prefix_len;
444 v = strchr(n, '=');
445 if (v == NULL) {
446 /* corrupt environment? */
447 continue;
448 }
449 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
450 lvd = &ld_env_vars[i];
451 if (lvd->val != NULL) {
452 /* Saw higher-priority variable name already. */
453 continue;
454 }
455 nlen = strlen(lvd->n);
456 if (v - n == (ptrdiff_t)nlen &&
457 strncmp(lvd->n, n, nlen) == 0) {
458 lvd->val = v + 1;
459 break;
460 }
461 }
462 }
463 }
464
465 static void
rtld_init_env_vars(char ** env)466 rtld_init_env_vars(char **env)
467 {
468 rtld_init_env_vars_for_prefix(env, ld_env_prefix);
469 }
470
471 static void
set_ld_elf_hints_path(void)472 set_ld_elf_hints_path(void)
473 {
474 if (ld_elf_hints_path == NULL || strlen(ld_elf_hints_path) == 0)
475 ld_elf_hints_path = ld_elf_hints_default;
476 }
477
478 uintptr_t
rtld_round_page(uintptr_t x)479 rtld_round_page(uintptr_t x)
480 {
481 return (roundup2(x, page_size));
482 }
483
484 uintptr_t
rtld_trunc_page(uintptr_t x)485 rtld_trunc_page(uintptr_t x)
486 {
487 return (rounddown2(x, page_size));
488 }
489
490 /*
491 * Main entry point for dynamic linking. The first argument is the
492 * stack pointer. The stack is expected to be laid out as described
493 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
494 * Specifically, the stack pointer points to a word containing
495 * ARGC. Following that in the stack is a null-terminated sequence
496 * of pointers to argument strings. Then comes a null-terminated
497 * sequence of pointers to environment strings. Finally, there is a
498 * sequence of "auxiliary vector" entries.
499 *
500 * The second argument points to a place to store the dynamic linker's
501 * exit procedure pointer and the third to a place to store the main
502 * program's object.
503 *
504 * The return value is the main program's entry point.
505 */
506 func_ptr_type
_rtld(Elf_Addr * sp,func_ptr_type * exit_proc,Obj_Entry ** objp)507 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
508 {
509 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT], auxtmp;
510 Objlist_Entry *entry;
511 Obj_Entry *last_interposer, *obj, *preload_tail;
512 const Elf_Phdr *phdr;
513 Objlist initlist;
514 RtldLockState lockstate;
515 struct stat st;
516 Elf_Addr *argcp;
517 char **argv, **env, **envp, *kexecpath;
518 const char *argv0, *binpath, *library_path_rpath, *static_tls_extra;
519 struct ld_env_var_desc *lvd;
520 caddr_t imgentry;
521 char buf[MAXPATHLEN];
522 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc;
523 size_t sz;
524 #ifdef __powerpc__
525 int old_auxv_format = 1;
526 #endif
527 bool dir_enable, dir_ignore, direct_exec, explicit_fd, search_in_path;
528
529 /*
530 * On entry, the dynamic linker itself has not been relocated yet.
531 * Be very careful not to reference any global data until after
532 * init_rtld has returned. It is OK to reference file-scope statics
533 * and string constants, and to call static and global functions.
534 */
535
536 /* Find the auxiliary vector on the stack. */
537 argcp = sp;
538 argc = *sp++;
539 argv = (char **)sp;
540 sp += argc + 1; /* Skip over arguments and NULL terminator */
541 env = (char **)sp;
542 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
543 ;
544 aux = (Elf_Auxinfo *)sp;
545
546 /* Digest the auxiliary vector. */
547 for (i = 0; i < AT_COUNT; i++)
548 aux_info[i] = NULL;
549 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
550 if (auxp->a_type < AT_COUNT)
551 aux_info[auxp->a_type] = auxp;
552 #ifdef __powerpc__
553 if (auxp->a_type == 23) /* AT_STACKPROT */
554 old_auxv_format = 0;
555 #endif
556 }
557
558 #ifdef __powerpc__
559 if (old_auxv_format) {
560 /* Remap from old-style auxv numbers. */
561 aux_info[23] = aux_info[21]; /* AT_STACKPROT */
562 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */
563 aux_info[19] = aux_info[17]; /* AT_NCPUS */
564 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */
565 aux_info[15] = aux_info[13]; /* AT_EXECPATH */
566 aux_info[13] = NULL; /* AT_GID */
567
568 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */
569 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */
570 aux_info[16] = aux_info[14]; /* AT_CANARY */
571 aux_info[14] = NULL; /* AT_EGID */
572 }
573 #endif
574
575 /* Initialize and relocate ourselves. */
576 assert(aux_info[AT_BASE] != NULL);
577 init_rtld((caddr_t)aux_info[AT_BASE]->a_un.a_ptr, aux_info);
578
579 dlerror_dflt_init();
580
581 __progname = obj_rtld.path;
582 argv0 = argv[0] != NULL ? argv[0] : "(null)";
583 environ = env;
584 main_argc = argc;
585 main_argv = argv;
586
587 if (aux_info[AT_BSDFLAGS] != NULL &&
588 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0)
589 ld_fast_sigblock = true;
590
591 trust = !issetugid();
592 direct_exec = false;
593
594 md_abi_variant_hook(aux_info);
595 rtld_init_env_vars(env);
596
597 fd = -1;
598 if (aux_info[AT_EXECFD] != NULL) {
599 fd = aux_info[AT_EXECFD]->a_un.a_val;
600 } else {
601 assert(aux_info[AT_PHDR] != NULL);
602 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
603 if (phdr == obj_rtld.phdr) {
604 if (!trust) {
605 _rtld_error(
606 "Tainted process refusing to run binary %s",
607 argv0);
608 rtld_die();
609 }
610 direct_exec = true;
611
612 dbg("opening main program in direct exec mode");
613 if (argc >= 2) {
614 rtld_argc = parse_args(argv, argc,
615 &search_in_path, &fd, &argv0, &dir_ignore);
616 explicit_fd = (fd != -1);
617 binpath = NULL;
618 if (!explicit_fd)
619 fd = open_binary_fd(argv0,
620 search_in_path, &binpath);
621 if (fstat(fd, &st) == -1) {
622 _rtld_error(
623 "Failed to fstat FD %d (%s): %s",
624 fd,
625 explicit_fd ?
626 "user-provided descriptor" :
627 argv0,
628 rtld_strerror(errno));
629 rtld_die();
630 }
631
632 /*
633 * Rough emulation of the permission checks done
634 * by execve(2), only Unix DACs are checked,
635 * ACLs are ignored. Preserve the semantic of
636 * disabling owner to execute if owner x bit is
637 * cleared, even if others x bit is enabled.
638 * mmap(2) does not allow to mmap with PROT_EXEC
639 * if binary' file comes from noexec mount. We
640 * cannot set a text reference on the binary.
641 */
642 dir_enable = false;
643 if (st.st_uid == geteuid()) {
644 if ((st.st_mode & S_IXUSR) != 0)
645 dir_enable = true;
646 } else if (st.st_gid == getegid()) {
647 if ((st.st_mode & S_IXGRP) != 0)
648 dir_enable = true;
649 } else if ((st.st_mode & S_IXOTH) != 0) {
650 dir_enable = true;
651 }
652 if (!dir_enable && !dir_ignore) {
653 _rtld_error(
654 "No execute permission for binary %s",
655 argv0);
656 rtld_die();
657 }
658
659 /*
660 * For direct exec mode, argv[0] is the
661 * interpreter name, we must remove it and shift
662 * arguments left before invoking binary main.
663 * Since stack layout places environment
664 * pointers and aux vectors right after the
665 * terminating NULL, we must shift environment
666 * and aux as well.
667 */
668 main_argc = argc - rtld_argc;
669 for (i = 0; i <= main_argc; i++)
670 argv[i] = argv[i + rtld_argc];
671 *argcp -= rtld_argc;
672 environ = env = envp = argv + main_argc + 1;
673 dbg("move env from %p to %p", envp + rtld_argc,
674 envp);
675 do {
676 *envp = *(envp + rtld_argc);
677 } while (*envp++ != NULL);
678 aux = auxp = (Elf_Auxinfo *)envp;
679 auxpf = (Elf_Auxinfo *)(envp + rtld_argc);
680 dbg("move aux from %p to %p", auxpf, aux);
681 /*
682 * XXXKIB insert place for AT_EXECPATH if not
683 * present
684 */
685 for (;; auxp++, auxpf++) {
686 /*
687 * NB: Use a temporary since *auxpf and
688 * *auxp overlap if rtld_argc is 1
689 */
690 auxtmp = *auxpf;
691 *auxp = auxtmp;
692 if (auxp->a_type == AT_NULL)
693 break;
694 }
695 /*
696 * Since the auxiliary vector has moved,
697 * redigest it.
698 */
699 for (i = 0; i < AT_COUNT; i++)
700 aux_info[i] = NULL;
701 for (auxp = aux; auxp->a_type != AT_NULL;
702 auxp++) {
703 if (auxp->a_type < AT_COUNT)
704 aux_info[auxp->a_type] = auxp;
705 }
706
707 /*
708 * Point AT_EXECPATH auxv and aux_info to the
709 * binary path.
710 */
711 if (binpath == NULL) {
712 aux_info[AT_EXECPATH] = NULL;
713 } else {
714 if (aux_info[AT_EXECPATH] == NULL) {
715 aux_info[AT_EXECPATH] = xmalloc(
716 sizeof(Elf_Auxinfo));
717 aux_info[AT_EXECPATH]->a_type =
718 AT_EXECPATH;
719 }
720 aux_info[AT_EXECPATH]->a_un.a_ptr =
721 __DECONST(void *, binpath);
722 }
723 } else {
724 _rtld_error("No binary");
725 rtld_die();
726 }
727 }
728 }
729
730 ld_bind_now = ld_get_env_var(LD_BIND_NOW);
731
732 /*
733 * If the process is tainted, then we un-set the dangerous environment
734 * variables. The process will be marked as tainted until setuid(2)
735 * is called. If any child process calls setuid(2) we do not want any
736 * future processes to honor the potentially un-safe variables.
737 */
738 if (!trust) {
739 for (i = 0; i < (int)nitems(ld_env_vars); i++) {
740 lvd = &ld_env_vars[i];
741 if (lvd->unsecure)
742 lvd->val = NULL;
743 }
744 }
745
746 ld_debug = ld_get_env_var(LD_DEBUG);
747 if (ld_bind_now == NULL)
748 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL;
749 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL;
750 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL;
751 libmap_override = ld_get_env_var(LD_LIBMAP);
752 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH);
753 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS);
754 ld_preload = ld_get_env_var(LD_PRELOAD);
755 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS);
756 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH);
757 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL;
758 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH);
759 if (library_path_rpath != NULL) {
760 if (library_path_rpath[0] == 'y' ||
761 library_path_rpath[0] == 'Y' ||
762 library_path_rpath[0] == '1')
763 ld_library_path_rpath = true;
764 else
765 ld_library_path_rpath = false;
766 }
767 static_tls_extra = ld_get_env_var(LD_STATIC_TLS_EXTRA);
768 if (static_tls_extra != NULL && static_tls_extra[0] != '\0') {
769 sz = parse_integer(static_tls_extra);
770 if (sz >= RTLD_STATIC_TLS_EXTRA && sz <= SIZE_T_MAX)
771 ld_static_tls_extra = sz;
772 }
773 dangerous_ld_env = libmap_disable || libmap_override != NULL ||
774 ld_library_path != NULL || ld_preload != NULL ||
775 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak ||
776 static_tls_extra != NULL;
777 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS);
778 ld_utrace = ld_get_env_var(LD_UTRACE);
779
780 set_ld_elf_hints_path();
781 if (ld_debug != NULL && *ld_debug != '\0')
782 debug = 1;
783 dbg("%s is initialized, base address = %p", __progname,
784 (caddr_t)aux_info[AT_BASE]->a_un.a_ptr);
785 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
786 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
787
788 dbg("initializing thread locks");
789 lockdflt_init();
790
791 /*
792 * Load the main program, or process its program header if it is
793 * already loaded.
794 */
795 if (fd != -1) { /* Load the main program. */
796 dbg("loading main program");
797 obj_main = map_object(fd, argv0, NULL, true);
798 close(fd);
799 if (obj_main == NULL)
800 rtld_die();
801 max_stack_flags = obj_main->stack_flags;
802 } else { /* Main program already loaded. */
803 dbg("processing main program's program header");
804 assert(aux_info[AT_PHDR] != NULL);
805 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr;
806 assert(aux_info[AT_PHNUM] != NULL);
807 phnum = aux_info[AT_PHNUM]->a_un.a_val;
808 assert(aux_info[AT_PHENT] != NULL);
809 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
810 assert(aux_info[AT_ENTRY] != NULL);
811 imgentry = (caddr_t)aux_info[AT_ENTRY]->a_un.a_ptr;
812 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) ==
813 NULL)
814 rtld_die();
815 }
816
817 if (aux_info[AT_EXECPATH] != NULL && fd == -1) {
818 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
819 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
820 if (kexecpath[0] == '/')
821 obj_main->path = kexecpath;
822 else if (getcwd(buf, sizeof(buf)) == NULL ||
823 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
824 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
825 obj_main->path = xstrdup(argv0);
826 else
827 obj_main->path = xstrdup(buf);
828 } else {
829 dbg("No AT_EXECPATH or direct exec");
830 obj_main->path = xstrdup(argv0);
831 }
832 dbg("obj_main path %s", obj_main->path);
833 obj_main->mainprog = true;
834
835 if (aux_info[AT_STACKPROT] != NULL &&
836 aux_info[AT_STACKPROT]->a_un.a_val != 0)
837 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
838
839 #ifndef COMPAT_libcompat
840 /*
841 * Get the actual dynamic linker pathname from the executable if
842 * possible. (It should always be possible.) That ensures that
843 * gdb will find the right dynamic linker even if a non-standard
844 * one is being used.
845 */
846 if (obj_main->interp != NULL &&
847 strcmp(obj_main->interp, obj_rtld.path) != 0) {
848 free(obj_rtld.path);
849 obj_rtld.path = xstrdup(obj_main->interp);
850 __progname = obj_rtld.path;
851 }
852 #endif
853
854 if (!digest_dynamic(obj_main, 0))
855 rtld_die();
856 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
857 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
858 obj_main->dynsymcount);
859
860 linkmap_add(obj_main);
861 linkmap_add(&obj_rtld);
862 LD_UTRACE(UTRACE_LOAD_OBJECT, obj_main, obj_main->mapbase,
863 obj_main->mapsize, 0, obj_main->path);
864 LD_UTRACE(UTRACE_LOAD_OBJECT, &obj_rtld, obj_rtld.mapbase,
865 obj_rtld.mapsize, 0, obj_rtld.path);
866
867 /* Link the main program into the list of objects. */
868 TAILQ_INSERT_HEAD(&obj_list, obj_main, next);
869 obj_count++;
870 obj_loads++;
871
872 /* Initialize a fake symbol for resolving undefined weak references. */
873 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
874 sym_zero.st_shndx = SHN_UNDEF;
875 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
876
877 if (!libmap_disable)
878 libmap_disable = (bool)lm_init(libmap_override);
879
880 if (aux_info[AT_KPRELOAD] != NULL &&
881 aux_info[AT_KPRELOAD]->a_un.a_ptr != NULL) {
882 dbg("loading kernel vdso");
883 if (load_kpreload(aux_info[AT_KPRELOAD]->a_un.a_ptr) == -1)
884 rtld_die();
885 }
886
887 dbg("loading LD_PRELOAD_FDS libraries");
888 if (load_preload_objects(ld_preload_fds, true) == -1)
889 rtld_die();
890
891 dbg("loading LD_PRELOAD libraries");
892 if (load_preload_objects(ld_preload, false) == -1)
893 rtld_die();
894 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
895
896 dbg("loading needed objects");
897 if (load_needed_objects(obj_main,
898 ld_tracing != NULL ? RTLD_LO_TRACE : 0) == -1)
899 rtld_die();
900
901 /* Make a list of all objects loaded at startup. */
902 last_interposer = obj_main;
903 TAILQ_FOREACH(obj, &obj_list, next) {
904 if (obj->marker)
905 continue;
906 if (obj->z_interpose && obj != obj_main) {
907 objlist_put_after(&list_main, last_interposer, obj);
908 last_interposer = obj;
909 } else {
910 objlist_push_tail(&list_main, obj);
911 }
912 obj->refcount++;
913 }
914
915 dbg("checking for required versions");
916 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
917 rtld_die();
918
919 if (ld_get_env_var(LD_SHOW_AUXV) != NULL)
920 dump_auxv(aux_info);
921
922 if (ld_tracing) { /* We're done */
923 trace_loaded_objects(obj_main, true);
924 exit(0);
925 }
926
927 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) {
928 dump_relocations(obj_main);
929 exit(0);
930 }
931
932 /*
933 * Processing tls relocations requires having the tls offsets
934 * initialized. Prepare offsets before starting initial
935 * relocation processing.
936 */
937 dbg("initializing initial thread local storage offsets");
938 STAILQ_FOREACH(entry, &list_main, link) {
939 /*
940 * Allocate all the initial objects out of the static TLS
941 * block even if they didn't ask for it.
942 */
943 allocate_tls_offset(entry->obj);
944 }
945
946 if (!allocate_tls_offset_common(&tcb_list_entry_offset,
947 sizeof(struct tcb_list_entry), _Alignof(struct tcb_list_entry),
948 0)) {
949 /*
950 * This should be impossible as the static block size is not
951 * yet fixed, but catch and diagnose it failing if that ever
952 * changes or somehow turns out to be false.
953 */
954 _rtld_error("Could not allocate offset for tcb_list_entry");
955 rtld_die();
956 }
957 dbg("tcb_list_entry_offset %zu", tcb_list_entry_offset);
958
959 if (relocate_objects(obj_main,
960 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld,
961 SYMLOOK_EARLY, NULL) == -1)
962 rtld_die();
963
964 dbg("doing copy relocations");
965 if (do_copy_relocations(obj_main) == -1)
966 rtld_die();
967
968 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) {
969 dump_relocations(obj_main);
970 exit(0);
971 }
972
973 ifunc_init(aux_info);
974
975 /*
976 * Setup TLS for main thread. This must be done after the
977 * relocations are processed, since tls initialization section
978 * might be the subject for relocations.
979 */
980 dbg("initializing initial thread local storage");
981 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list)));
982
983 dbg("initializing key program variables");
984 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
985 set_program_var("environ", env);
986 set_program_var("__elf_aux_vector", aux);
987
988 /* Make a list of init functions to call. */
989 objlist_init(&initlist);
990 initlist_for_loaded_obj(globallist_curr(TAILQ_FIRST(&obj_list)),
991 preload_tail, &initlist);
992
993 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
994
995 map_stacks_exec(NULL);
996
997 if (!obj_main->crt_no_init) {
998 /*
999 * Make sure we don't call the main program's init and fini
1000 * functions for binaries linked with old crt1 which calls
1001 * _init itself.
1002 */
1003 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
1004 obj_main->preinit_array = obj_main->init_array =
1005 obj_main->fini_array = (Elf_Addr)NULL;
1006 }
1007
1008 if (direct_exec) {
1009 /* Set osrel for direct-execed binary */
1010 mib[0] = CTL_KERN;
1011 mib[1] = KERN_PROC;
1012 mib[2] = KERN_PROC_OSREL;
1013 mib[3] = getpid();
1014 osrel = obj_main->osrel;
1015 sz = sizeof(old_osrel);
1016 dbg("setting osrel to %d", osrel);
1017 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel));
1018 }
1019
1020 wlock_acquire(rtld_bind_lock, &lockstate);
1021
1022 dbg("resolving ifuncs");
1023 if (initlist_objects_ifunc(&initlist,
1024 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY,
1025 &lockstate) == -1)
1026 rtld_die();
1027
1028 rtld_exit_ptr = rtld_exit;
1029 if (obj_main->crt_no_init)
1030 preinit_main();
1031 objlist_call_init(&initlist, &lockstate);
1032 _r_debug_postinit(&obj_main->linkmap);
1033 objlist_clear(&initlist);
1034 dbg("loading filtees");
1035 TAILQ_FOREACH(obj, &obj_list, next) {
1036 if (obj->marker)
1037 continue;
1038 if (ld_loadfltr || obj->z_loadfltr)
1039 load_filtees(obj, 0, &lockstate);
1040 }
1041
1042 dbg("enforcing main obj relro");
1043 if (obj_enforce_relro(obj_main) == -1)
1044 rtld_die();
1045
1046 lock_release(rtld_bind_lock, &lockstate);
1047
1048 dbg("transferring control to program entry point = %p",
1049 obj_main->entry);
1050
1051 /* Return the exit procedure and the program entry point. */
1052 *exit_proc = rtld_exit_ptr;
1053 *objp = obj_main;
1054 return ((func_ptr_type)obj_main->entry);
1055 }
1056
1057 void *
rtld_resolve_ifunc(const Obj_Entry * obj,const Elf_Sym * def)1058 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
1059 {
1060 void *ptr;
1061 Elf_Addr target;
1062
1063 ptr = (void *)make_function_pointer(def, obj);
1064 target = call_ifunc_resolver(ptr);
1065 return ((void *)target);
1066 }
1067
1068 Elf_Addr
_rtld_bind(Obj_Entry * obj,Elf_Size reloff)1069 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
1070 {
1071 const Elf_Rel *rel;
1072 const Elf_Sym *def;
1073 const Obj_Entry *defobj;
1074 Elf_Addr *where;
1075 Elf_Addr target;
1076 RtldLockState lockstate;
1077
1078 relock:
1079 rlock_acquire(rtld_bind_lock, &lockstate);
1080 if (sigsetjmp(lockstate.env, 0) != 0)
1081 lock_upgrade(rtld_bind_lock, &lockstate);
1082 if (obj->pltrel)
1083 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff);
1084 else
1085 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff);
1086
1087 where = (Elf_Addr *)(obj->relocbase + rel->r_offset);
1088 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT,
1089 NULL, &lockstate);
1090 if (def == NULL)
1091 rtld_die();
1092 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) {
1093 if (lockstate_wlocked(&lockstate)) {
1094 lock_release(rtld_bind_lock, &lockstate);
1095 goto relock;
1096 }
1097 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
1098 } else {
1099 target = (Elf_Addr)(defobj->relocbase + def->st_value);
1100 }
1101
1102 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"", defobj->strtab + def->st_name,
1103 obj->path == NULL ? NULL : basename(obj->path), (void *)target,
1104 defobj->path == NULL ? NULL : basename(defobj->path));
1105
1106 /*
1107 * Write the new contents for the jmpslot. Note that depending on
1108 * architecture, the value which we need to return back to the
1109 * lazy binding trampoline may or may not be the target
1110 * address. The value returned from reloc_jmpslot() is the value
1111 * that the trampoline needs.
1112 */
1113 target = reloc_jmpslot(where, target, defobj, obj, rel);
1114 lock_release(rtld_bind_lock, &lockstate);
1115 return (target);
1116 }
1117
1118 /*
1119 * Error reporting function. Use it like printf. If formats the message
1120 * into a buffer, and sets things up so that the next call to dlerror()
1121 * will return the message.
1122 */
1123 void
_rtld_error(const char * fmt,...)1124 _rtld_error(const char *fmt, ...)
1125 {
1126 va_list ap;
1127
1128 va_start(ap, fmt);
1129 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz, fmt,
1130 ap);
1131 va_end(ap);
1132 *lockinfo.dlerror_seen() = 0;
1133 dbg("rtld_error: %s", lockinfo.dlerror_loc());
1134 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc());
1135 }
1136
1137 /*
1138 * Return a dynamically-allocated copy of the current error message, if any.
1139 */
1140 static struct dlerror_save *
errmsg_save(void)1141 errmsg_save(void)
1142 {
1143 struct dlerror_save *res;
1144
1145 res = xmalloc(sizeof(*res));
1146 res->seen = *lockinfo.dlerror_seen();
1147 if (res->seen == 0)
1148 res->msg = xstrdup(lockinfo.dlerror_loc());
1149 return (res);
1150 }
1151
1152 /*
1153 * Restore the current error message from a copy which was previously saved
1154 * by errmsg_save(). The copy is freed.
1155 */
1156 static void
errmsg_restore(struct dlerror_save * saved_msg)1157 errmsg_restore(struct dlerror_save *saved_msg)
1158 {
1159 if (saved_msg == NULL || saved_msg->seen == 1) {
1160 *lockinfo.dlerror_seen() = 1;
1161 } else {
1162 *lockinfo.dlerror_seen() = 0;
1163 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg,
1164 lockinfo.dlerror_loc_sz);
1165 free(saved_msg->msg);
1166 }
1167 free(saved_msg);
1168 }
1169
1170 static const char *
basename(const char * name)1171 basename(const char *name)
1172 {
1173 const char *p;
1174
1175 p = strrchr(name, '/');
1176 return (p != NULL ? p + 1 : name);
1177 }
1178
1179 static struct utsname uts;
1180
1181 static char *
origin_subst_one(Obj_Entry * obj,char * real,const char * kw,const char * subst,bool may_free)1182 origin_subst_one(Obj_Entry *obj, char *real, const char *kw, const char *subst,
1183 bool may_free)
1184 {
1185 char *p, *p1, *res, *resp;
1186 int subst_len, kw_len, subst_count, old_len, new_len;
1187
1188 kw_len = strlen(kw);
1189
1190 /*
1191 * First, count the number of the keyword occurrences, to
1192 * preallocate the final string.
1193 */
1194 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
1195 p1 = strstr(p, kw);
1196 if (p1 == NULL)
1197 break;
1198 }
1199
1200 /*
1201 * If the keyword is not found, just return.
1202 *
1203 * Return non-substituted string if resolution failed. We
1204 * cannot do anything more reasonable, the failure mode of the
1205 * caller is unresolved library anyway.
1206 */
1207 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj)))
1208 return (may_free ? real : xstrdup(real));
1209 if (obj != NULL)
1210 subst = obj->origin_path;
1211
1212 /*
1213 * There is indeed something to substitute. Calculate the
1214 * length of the resulting string, and allocate it.
1215 */
1216 subst_len = strlen(subst);
1217 old_len = strlen(real);
1218 new_len = old_len + (subst_len - kw_len) * subst_count;
1219 res = xmalloc(new_len + 1);
1220
1221 /*
1222 * Now, execute the substitution loop.
1223 */
1224 for (p = real, resp = res, *resp = '\0';;) {
1225 p1 = strstr(p, kw);
1226 if (p1 != NULL) {
1227 /* Copy the prefix before keyword. */
1228 memcpy(resp, p, p1 - p);
1229 resp += p1 - p;
1230 /* Keyword replacement. */
1231 memcpy(resp, subst, subst_len);
1232 resp += subst_len;
1233 *resp = '\0';
1234 p = p1 + kw_len;
1235 } else
1236 break;
1237 }
1238
1239 /* Copy to the end of string and finish. */
1240 strcat(resp, p);
1241 if (may_free)
1242 free(real);
1243 return (res);
1244 }
1245
1246 static const struct {
1247 const char *kw;
1248 bool pass_obj;
1249 const char *subst;
1250 } tokens[] = {
1251 { .kw = "$ORIGIN", .pass_obj = true, .subst = NULL },
1252 { .kw = "${ORIGIN}", .pass_obj = true, .subst = NULL },
1253 { .kw = "$OSNAME", .pass_obj = false, .subst = uts.sysname },
1254 { .kw = "${OSNAME}", .pass_obj = false, .subst = uts.sysname },
1255 { .kw = "$OSREL", .pass_obj = false, .subst = uts.release },
1256 { .kw = "${OSREL}", .pass_obj = false, .subst = uts.release },
1257 { .kw = "$PLATFORM", .pass_obj = false, .subst = uts.machine },
1258 { .kw = "${PLATFORM}", .pass_obj = false, .subst = uts.machine },
1259 { .kw = "$LIB", .pass_obj = false, .subst = TOKEN_LIB },
1260 { .kw = "${LIB}", .pass_obj = false, .subst = TOKEN_LIB },
1261 };
1262
1263 static char *
origin_subst(Obj_Entry * obj,const char * real)1264 origin_subst(Obj_Entry *obj, const char *real)
1265 {
1266 char *res;
1267 int i;
1268
1269 if (obj == NULL || !trust)
1270 return (xstrdup(real));
1271 if (uts.sysname[0] == '\0') {
1272 if (uname(&uts) != 0) {
1273 _rtld_error("utsname failed: %d", errno);
1274 return (NULL);
1275 }
1276 }
1277
1278 /* __DECONST is safe here since without may_free real is unchanged */
1279 res = __DECONST(char *, real);
1280 for (i = 0; i < (int)nitems(tokens); i++) {
1281 res = origin_subst_one(tokens[i].pass_obj ? obj : NULL, res,
1282 tokens[i].kw, tokens[i].subst, i != 0);
1283 }
1284 return (res);
1285 }
1286
1287 void
rtld_die(void)1288 rtld_die(void)
1289 {
1290 const char *msg = dlerror();
1291
1292 if (msg == NULL)
1293 msg = "Fatal error";
1294 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": ");
1295 rtld_fdputstr(STDERR_FILENO, msg);
1296 rtld_fdputchar(STDERR_FILENO, '\n');
1297 _exit(1);
1298 }
1299
1300 /*
1301 * Process a shared object's DYNAMIC section, and save the important
1302 * information in its Obj_Entry structure.
1303 */
1304 static void
digest_dynamic1(Obj_Entry * obj,int early,const Elf_Dyn ** dyn_rpath,const Elf_Dyn ** dyn_soname,const Elf_Dyn ** dyn_runpath)1305 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
1306 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
1307 {
1308 const Elf_Dyn *dynp;
1309 Needed_Entry **needed_tail = &obj->needed;
1310 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
1311 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
1312 const Elf_Hashelt *hashtab;
1313 const Elf32_Word *hashval;
1314 Elf32_Word bkt, nmaskwords;
1315 int bloom_size32;
1316 int plttype = DT_REL;
1317
1318 *dyn_rpath = NULL;
1319 *dyn_soname = NULL;
1320 *dyn_runpath = NULL;
1321
1322 obj->bind_now = false;
1323 dynp = obj->dynamic;
1324 if (dynp == NULL)
1325 return;
1326 for (; dynp->d_tag != DT_NULL; dynp++) {
1327 switch (dynp->d_tag) {
1328 case DT_REL:
1329 obj->rel = (const Elf_Rel *)(obj->relocbase +
1330 dynp->d_un.d_ptr);
1331 break;
1332
1333 case DT_RELSZ:
1334 obj->relsize = dynp->d_un.d_val;
1335 break;
1336
1337 case DT_RELENT:
1338 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1339 break;
1340
1341 case DT_JMPREL:
1342 obj->pltrel = (const Elf_Rel *)(obj->relocbase +
1343 dynp->d_un.d_ptr);
1344 break;
1345
1346 case DT_PLTRELSZ:
1347 obj->pltrelsize = dynp->d_un.d_val;
1348 break;
1349
1350 case DT_RELA:
1351 obj->rela = (const Elf_Rela *)(obj->relocbase +
1352 dynp->d_un.d_ptr);
1353 break;
1354
1355 case DT_RELASZ:
1356 obj->relasize = dynp->d_un.d_val;
1357 break;
1358
1359 case DT_RELAENT:
1360 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1361 break;
1362
1363 case DT_RELR:
1364 obj->relr = (const Elf_Relr *)(obj->relocbase +
1365 dynp->d_un.d_ptr);
1366 break;
1367
1368 case DT_RELRSZ:
1369 obj->relrsize = dynp->d_un.d_val;
1370 break;
1371
1372 case DT_RELRENT:
1373 assert(dynp->d_un.d_val == sizeof(Elf_Relr));
1374 break;
1375
1376 case DT_PLTREL:
1377 plttype = dynp->d_un.d_val;
1378 assert(
1379 dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1380 break;
1381
1382 case DT_SYMTAB:
1383 obj->symtab = (const Elf_Sym *)(obj->relocbase +
1384 dynp->d_un.d_ptr);
1385 break;
1386
1387 case DT_SYMENT:
1388 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1389 break;
1390
1391 case DT_STRTAB:
1392 obj->strtab = (const char *)(obj->relocbase +
1393 dynp->d_un.d_ptr);
1394 break;
1395
1396 case DT_STRSZ:
1397 obj->strsize = dynp->d_un.d_val;
1398 break;
1399
1400 case DT_VERNEED:
1401 obj->verneed = (const Elf_Verneed *)(obj->relocbase +
1402 dynp->d_un.d_val);
1403 break;
1404
1405 case DT_VERNEEDNUM:
1406 obj->verneednum = dynp->d_un.d_val;
1407 break;
1408
1409 case DT_VERDEF:
1410 obj->verdef = (const Elf_Verdef *)(obj->relocbase +
1411 dynp->d_un.d_val);
1412 break;
1413
1414 case DT_VERDEFNUM:
1415 obj->verdefnum = dynp->d_un.d_val;
1416 break;
1417
1418 case DT_VERSYM:
1419 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1420 dynp->d_un.d_val);
1421 break;
1422
1423 case DT_HASH: {
1424 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1425 dynp->d_un.d_ptr);
1426 obj->nbuckets = hashtab[0];
1427 obj->nchains = hashtab[1];
1428 obj->buckets = hashtab + 2;
1429 obj->chains = obj->buckets + obj->nbuckets;
1430 obj->valid_hash_sysv = obj->nbuckets > 0 &&
1431 obj->nchains > 0 && obj->buckets != NULL;
1432 } break;
1433
1434 case DT_GNU_HASH: {
1435 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1436 dynp->d_un.d_ptr);
1437 obj->nbuckets_gnu = hashtab[0];
1438 obj->symndx_gnu = hashtab[1];
1439 nmaskwords = hashtab[2];
1440 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1441 obj->maskwords_bm_gnu = nmaskwords - 1;
1442 obj->shift2_gnu = hashtab[3];
1443 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4);
1444 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1445 obj->chain_zero_gnu = obj->buckets_gnu +
1446 obj->nbuckets_gnu - obj->symndx_gnu;
1447 /* Number of bitmask words is required to be power of 2
1448 */
1449 obj->valid_hash_gnu = powerof2(nmaskwords) &&
1450 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL;
1451 } break;
1452
1453 case DT_NEEDED:
1454 if (!obj->rtld) {
1455 Needed_Entry *nep = NEW(Needed_Entry);
1456 nep->name = dynp->d_un.d_val;
1457 nep->obj = NULL;
1458 nep->next = NULL;
1459
1460 *needed_tail = nep;
1461 needed_tail = &nep->next;
1462 }
1463 break;
1464
1465 case DT_FILTER:
1466 if (!obj->rtld) {
1467 Needed_Entry *nep = NEW(Needed_Entry);
1468 nep->name = dynp->d_un.d_val;
1469 nep->obj = NULL;
1470 nep->next = NULL;
1471
1472 *needed_filtees_tail = nep;
1473 needed_filtees_tail = &nep->next;
1474
1475 if (obj->linkmap.l_refname == NULL)
1476 obj->linkmap.l_refname =
1477 (char *)dynp->d_un.d_val;
1478 }
1479 break;
1480
1481 case DT_AUXILIARY:
1482 if (!obj->rtld) {
1483 Needed_Entry *nep = NEW(Needed_Entry);
1484 nep->name = dynp->d_un.d_val;
1485 nep->obj = NULL;
1486 nep->next = NULL;
1487
1488 *needed_aux_filtees_tail = nep;
1489 needed_aux_filtees_tail = &nep->next;
1490 }
1491 break;
1492
1493 case DT_PLTGOT:
1494 obj->pltgot = (Elf_Addr *)(obj->relocbase +
1495 dynp->d_un.d_ptr);
1496 break;
1497
1498 case DT_TEXTREL:
1499 obj->textrel = true;
1500 break;
1501
1502 case DT_SYMBOLIC:
1503 obj->symbolic = true;
1504 break;
1505
1506 case DT_RPATH:
1507 /*
1508 * We have to wait until later to process this, because
1509 * we might not have gotten the address of the string
1510 * table yet.
1511 */
1512 *dyn_rpath = dynp;
1513 break;
1514
1515 case DT_SONAME:
1516 *dyn_soname = dynp;
1517 break;
1518
1519 case DT_RUNPATH:
1520 *dyn_runpath = dynp;
1521 break;
1522
1523 case DT_INIT:
1524 obj->init = (Elf_Addr)(obj->relocbase +
1525 dynp->d_un.d_ptr);
1526 break;
1527
1528 case DT_PREINIT_ARRAY:
1529 obj->preinit_array = (Elf_Addr)(obj->relocbase +
1530 dynp->d_un.d_ptr);
1531 break;
1532
1533 case DT_PREINIT_ARRAYSZ:
1534 obj->preinit_array_num = dynp->d_un.d_val /
1535 sizeof(Elf_Addr);
1536 break;
1537
1538 case DT_INIT_ARRAY:
1539 obj->init_array = (Elf_Addr)(obj->relocbase +
1540 dynp->d_un.d_ptr);
1541 break;
1542
1543 case DT_INIT_ARRAYSZ:
1544 obj->init_array_num = dynp->d_un.d_val /
1545 sizeof(Elf_Addr);
1546 break;
1547
1548 case DT_FINI:
1549 obj->fini = (Elf_Addr)(obj->relocbase +
1550 dynp->d_un.d_ptr);
1551 break;
1552
1553 case DT_FINI_ARRAY:
1554 obj->fini_array = (Elf_Addr)(obj->relocbase +
1555 dynp->d_un.d_ptr);
1556 break;
1557
1558 case DT_FINI_ARRAYSZ:
1559 obj->fini_array_num = dynp->d_un.d_val /
1560 sizeof(Elf_Addr);
1561 break;
1562
1563 case DT_DEBUG:
1564 if (!early)
1565 dbg("Filling in DT_DEBUG entry");
1566 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr =
1567 (Elf_Addr)&r_debug;
1568 break;
1569
1570 case DT_FLAGS:
1571 if (dynp->d_un.d_val & DF_ORIGIN)
1572 obj->z_origin = true;
1573 if (dynp->d_un.d_val & DF_SYMBOLIC)
1574 obj->symbolic = true;
1575 if (dynp->d_un.d_val & DF_TEXTREL)
1576 obj->textrel = true;
1577 if (dynp->d_un.d_val & DF_BIND_NOW)
1578 obj->bind_now = true;
1579 if (dynp->d_un.d_val & DF_STATIC_TLS)
1580 obj->static_tls = true;
1581 break;
1582
1583 case DT_FLAGS_1:
1584 if (dynp->d_un.d_val & DF_1_NOOPEN)
1585 obj->z_noopen = true;
1586 if (dynp->d_un.d_val & DF_1_ORIGIN)
1587 obj->z_origin = true;
1588 if (dynp->d_un.d_val & DF_1_GLOBAL)
1589 obj->z_global = true;
1590 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1591 obj->bind_now = true;
1592 if (dynp->d_un.d_val & DF_1_NODELETE)
1593 obj->z_nodelete = true;
1594 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1595 obj->z_loadfltr = true;
1596 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1597 obj->z_interpose = true;
1598 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1599 obj->z_nodeflib = true;
1600 if (dynp->d_un.d_val & DF_1_PIE)
1601 obj->z_pie = true;
1602 if (dynp->d_un.d_val & DF_1_INITFIRST)
1603 obj->z_initfirst = true;
1604 break;
1605
1606 default:
1607 if (arch_digest_dynamic(obj, dynp))
1608 break;
1609
1610 if (!early) {
1611 dbg("Ignoring d_tag %ld = %#lx",
1612 (long)dynp->d_tag, (long)dynp->d_tag);
1613 }
1614 break;
1615 }
1616 }
1617
1618 obj->traced = false;
1619
1620 if (plttype == DT_RELA) {
1621 obj->pltrela = (const Elf_Rela *)obj->pltrel;
1622 obj->pltrel = NULL;
1623 obj->pltrelasize = obj->pltrelsize;
1624 obj->pltrelsize = 0;
1625 }
1626
1627 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1628 if (obj->valid_hash_sysv)
1629 obj->dynsymcount = obj->nchains;
1630 else if (obj->valid_hash_gnu) {
1631 obj->dynsymcount = 0;
1632 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1633 if (obj->buckets_gnu[bkt] == 0)
1634 continue;
1635 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1636 do
1637 obj->dynsymcount++;
1638 while ((*hashval++ & 1u) == 0);
1639 }
1640 obj->dynsymcount += obj->symndx_gnu;
1641 }
1642
1643 if (obj->linkmap.l_refname != NULL)
1644 obj->linkmap.l_refname = obj->strtab +
1645 (unsigned long)obj->linkmap.l_refname;
1646 }
1647
1648 static bool
obj_resolve_origin(Obj_Entry * obj)1649 obj_resolve_origin(Obj_Entry *obj)
1650 {
1651 if (obj->origin_path != NULL)
1652 return (true);
1653 obj->origin_path = xmalloc(PATH_MAX);
1654 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1655 }
1656
1657 static bool
digest_dynamic2(Obj_Entry * obj,const Elf_Dyn * dyn_rpath,const Elf_Dyn * dyn_soname,const Elf_Dyn * dyn_runpath)1658 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1659 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1660 {
1661 if (obj->z_origin && !obj_resolve_origin(obj))
1662 return (false);
1663
1664 if (dyn_runpath != NULL) {
1665 obj->runpath = (const char *)obj->strtab +
1666 dyn_runpath->d_un.d_val;
1667 obj->runpath = origin_subst(obj, obj->runpath);
1668 } else if (dyn_rpath != NULL) {
1669 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1670 obj->rpath = origin_subst(obj, obj->rpath);
1671 }
1672 if (dyn_soname != NULL)
1673 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1674 return (true);
1675 }
1676
1677 static bool
digest_dynamic(Obj_Entry * obj,int early)1678 digest_dynamic(Obj_Entry *obj, int early)
1679 {
1680 const Elf_Dyn *dyn_rpath;
1681 const Elf_Dyn *dyn_soname;
1682 const Elf_Dyn *dyn_runpath;
1683
1684 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1685 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath));
1686 }
1687
1688 /*
1689 * Process a shared object's program header. This is used only for the
1690 * main program, when the kernel has already loaded the main program
1691 * into memory before calling the dynamic linker. It creates and
1692 * returns an Obj_Entry structure.
1693 */
1694 static Obj_Entry *
digest_phdr(const Elf_Phdr * phdr,int phnum,caddr_t entry,const char * path)1695 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1696 {
1697 Obj_Entry *obj;
1698 const Elf_Phdr *phlimit = phdr + phnum;
1699 const Elf_Phdr *ph;
1700 Elf_Addr note_start, note_end;
1701 int nsegs = 0;
1702
1703 obj = obj_new();
1704 for (ph = phdr; ph < phlimit; ph++) {
1705 if (ph->p_type != PT_PHDR)
1706 continue;
1707
1708 obj->phdr = phdr;
1709 obj->phsize = ph->p_memsz;
1710 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1711 break;
1712 }
1713
1714 obj->stack_flags = PF_X | PF_R | PF_W;
1715
1716 for (ph = phdr; ph < phlimit; ph++) {
1717 switch (ph->p_type) {
1718 case PT_INTERP:
1719 obj->interp = (const char *)(ph->p_vaddr +
1720 obj->relocbase);
1721 break;
1722
1723 case PT_LOAD:
1724 if (nsegs == 0) { /* First load segment */
1725 obj->vaddrbase = rtld_trunc_page(ph->p_vaddr);
1726 obj->mapbase = obj->vaddrbase + obj->relocbase;
1727 } else { /* Last load segment */
1728 obj->mapsize = rtld_round_page(
1729 ph->p_vaddr + ph->p_memsz) -
1730 obj->vaddrbase;
1731 }
1732 nsegs++;
1733 break;
1734
1735 case PT_DYNAMIC:
1736 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr +
1737 obj->relocbase);
1738 break;
1739
1740 case PT_TLS:
1741 obj->tlsindex = 1;
1742 obj->tlssize = ph->p_memsz;
1743 obj->tlsalign = ph->p_align;
1744 obj->tlsinitsize = ph->p_filesz;
1745 obj->tlsinit = (void *)(ph->p_vaddr + obj->relocbase);
1746 obj->tlspoffset = ph->p_offset;
1747 break;
1748
1749 case PT_GNU_STACK:
1750 obj->stack_flags = ph->p_flags;
1751 break;
1752
1753 case PT_NOTE:
1754 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1755 note_end = note_start + ph->p_filesz;
1756 digest_notes(obj, note_start, note_end);
1757 break;
1758 }
1759 }
1760 if (nsegs < 1) {
1761 _rtld_error("%s: too few PT_LOAD segments", path);
1762 return (NULL);
1763 }
1764
1765 obj->entry = entry;
1766 return (obj);
1767 }
1768
1769 void
digest_notes(Obj_Entry * obj,Elf_Addr note_start,Elf_Addr note_end)1770 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1771 {
1772 const Elf_Note *note;
1773 const char *note_name;
1774 uintptr_t p;
1775
1776 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1777 note = (const Elf_Note *)((const char *)(note + 1) +
1778 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1779 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1780 if (arch_digest_note(obj, note))
1781 continue;
1782
1783 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1784 note->n_descsz != sizeof(int32_t))
1785 continue;
1786 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1787 note->n_type != NT_FREEBSD_FEATURE_CTL &&
1788 note->n_type != NT_FREEBSD_NOINIT_TAG)
1789 continue;
1790 note_name = (const char *)(note + 1);
1791 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1792 sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1793 continue;
1794 switch (note->n_type) {
1795 case NT_FREEBSD_ABI_TAG:
1796 /* FreeBSD osrel note */
1797 p = (uintptr_t)(note + 1);
1798 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1799 obj->osrel = *(const int32_t *)(p);
1800 dbg("note osrel %d", obj->osrel);
1801 break;
1802 case NT_FREEBSD_FEATURE_CTL:
1803 /* FreeBSD ABI feature control note */
1804 p = (uintptr_t)(note + 1);
1805 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1806 obj->fctl0 = *(const uint32_t *)(p);
1807 dbg("note fctl0 %#x", obj->fctl0);
1808 break;
1809 case NT_FREEBSD_NOINIT_TAG:
1810 /* FreeBSD 'crt does not call init' note */
1811 obj->crt_no_init = true;
1812 dbg("note crt_no_init");
1813 break;
1814 }
1815 }
1816 }
1817
1818 static Obj_Entry *
dlcheck(void * handle)1819 dlcheck(void *handle)
1820 {
1821 Obj_Entry *obj;
1822
1823 TAILQ_FOREACH(obj, &obj_list, next) {
1824 if (obj == (Obj_Entry *)handle)
1825 break;
1826 }
1827
1828 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1829 _rtld_error("Invalid shared object handle %p", handle);
1830 return (NULL);
1831 }
1832 return (obj);
1833 }
1834
1835 /*
1836 * If the given object is already in the donelist, return true. Otherwise
1837 * add the object to the list and return false.
1838 */
1839 static bool
donelist_check(DoneList * dlp,const Obj_Entry * obj)1840 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1841 {
1842 unsigned int i;
1843
1844 for (i = 0; i < dlp->num_used; i++)
1845 if (dlp->objs[i] == obj)
1846 return (true);
1847 /*
1848 * Our donelist allocation should always be sufficient. But if
1849 * our threads locking isn't working properly, more shared objects
1850 * could have been loaded since we allocated the list. That should
1851 * never happen, but we'll handle it properly just in case it does.
1852 */
1853 if (dlp->num_used < dlp->num_alloc)
1854 dlp->objs[dlp->num_used++] = obj;
1855 return (false);
1856 }
1857
1858 /*
1859 * SysV hash function for symbol table lookup. It is a slightly optimized
1860 * version of the hash specified by the System V ABI.
1861 */
1862 Elf32_Word
elf_hash(const char * name)1863 elf_hash(const char *name)
1864 {
1865 const unsigned char *p = (const unsigned char *)name;
1866 Elf32_Word h = 0;
1867
1868 while (*p != '\0') {
1869 h = (h << 4) + *p++;
1870 h ^= (h >> 24) & 0xf0;
1871 }
1872 return (h & 0x0fffffff);
1873 }
1874
1875 /*
1876 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1877 * unsigned in case it's implemented with a wider type.
1878 */
1879 static uint32_t
gnu_hash(const char * s)1880 gnu_hash(const char *s)
1881 {
1882 uint32_t h;
1883 unsigned char c;
1884
1885 h = 5381;
1886 for (c = *s; c != '\0'; c = *++s)
1887 h = h * 33 + c;
1888 return (h & 0xffffffff);
1889 }
1890
1891 /*
1892 * Find the library with the given name, and return its full pathname.
1893 * The returned string is dynamically allocated. Generates an error
1894 * message and returns NULL if the library cannot be found.
1895 *
1896 * If the second argument is non-NULL, then it refers to an already-
1897 * loaded shared object, whose library search path will be searched.
1898 *
1899 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1900 * descriptor (which is close-on-exec) will be passed out via the third
1901 * argument.
1902 *
1903 * The search order is:
1904 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1905 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1906 * LD_LIBRARY_PATH
1907 * DT_RUNPATH in the referencing file
1908 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1909 * from list)
1910 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1911 *
1912 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1913 */
1914 static char *
find_library(const char * xname,const Obj_Entry * refobj,int * fdp)1915 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1916 {
1917 char *pathname, *refobj_path;
1918 const char *name;
1919 bool nodeflib, objgiven;
1920
1921 objgiven = refobj != NULL;
1922
1923 if (libmap_disable || !objgiven ||
1924 (name = lm_find(refobj->path, xname)) == NULL)
1925 name = xname;
1926
1927 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
1928 if (name[0] != '/' && !trust) {
1929 _rtld_error(
1930 "Absolute pathname required for shared object \"%s\"",
1931 name);
1932 return (NULL);
1933 }
1934 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1935 __DECONST(char *, name)));
1936 }
1937
1938 dbg(" Searching for \"%s\"", name);
1939 refobj_path = objgiven ? refobj->path : NULL;
1940
1941 /*
1942 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall
1943 * back to pre-conforming behaviour if user requested so with
1944 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1945 * nodeflib.
1946 */
1947 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1948 pathname = search_library_path(name, ld_library_path,
1949 refobj_path, fdp);
1950 if (pathname != NULL)
1951 return (pathname);
1952 if (refobj != NULL) {
1953 pathname = search_library_path(name, refobj->rpath,
1954 refobj_path, fdp);
1955 if (pathname != NULL)
1956 return (pathname);
1957 }
1958 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1959 if (pathname != NULL)
1960 return (pathname);
1961 pathname = search_library_path(name, gethints(false),
1962 refobj_path, fdp);
1963 if (pathname != NULL)
1964 return (pathname);
1965 pathname = search_library_path(name, ld_standard_library_path,
1966 refobj_path, fdp);
1967 if (pathname != NULL)
1968 return (pathname);
1969 } else {
1970 nodeflib = objgiven ? refobj->z_nodeflib : false;
1971 if (objgiven) {
1972 pathname = search_library_path(name, refobj->rpath,
1973 refobj->path, fdp);
1974 if (pathname != NULL)
1975 return (pathname);
1976 }
1977 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1978 pathname = search_library_path(name, obj_main->rpath,
1979 refobj_path, fdp);
1980 if (pathname != NULL)
1981 return (pathname);
1982 }
1983 pathname = search_library_path(name, ld_library_path,
1984 refobj_path, fdp);
1985 if (pathname != NULL)
1986 return (pathname);
1987 if (objgiven) {
1988 pathname = search_library_path(name, refobj->runpath,
1989 refobj_path, fdp);
1990 if (pathname != NULL)
1991 return (pathname);
1992 }
1993 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1994 if (pathname != NULL)
1995 return (pathname);
1996 pathname = search_library_path(name, gethints(nodeflib),
1997 refobj_path, fdp);
1998 if (pathname != NULL)
1999 return (pathname);
2000 if (objgiven && !nodeflib) {
2001 pathname = search_library_path(name,
2002 ld_standard_library_path, refobj_path, fdp);
2003 if (pathname != NULL)
2004 return (pathname);
2005 }
2006 }
2007
2008 if (objgiven && refobj->path != NULL) {
2009 _rtld_error(
2010 "Shared object \"%s\" not found, required by \"%s\"",
2011 name, basename(refobj->path));
2012 } else {
2013 _rtld_error("Shared object \"%s\" not found", name);
2014 }
2015 return (NULL);
2016 }
2017
2018 /*
2019 * Given a symbol number in a referencing object, find the corresponding
2020 * definition of the symbol. Returns a pointer to the symbol, or NULL if
2021 * no definition was found. Returns a pointer to the Obj_Entry of the
2022 * defining object via the reference parameter DEFOBJ_OUT.
2023 */
2024 const Elf_Sym *
find_symdef(unsigned long symnum,const Obj_Entry * refobj,const Obj_Entry ** defobj_out,int flags,SymCache * cache,RtldLockState * lockstate)2025 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
2026 const Obj_Entry **defobj_out, int flags, SymCache *cache,
2027 RtldLockState *lockstate)
2028 {
2029 const Elf_Sym *ref;
2030 const Elf_Sym *def;
2031 const Obj_Entry *defobj;
2032 const Ver_Entry *ve;
2033 SymLook req;
2034 const char *name;
2035 int res;
2036
2037 /*
2038 * If we have already found this symbol, get the information from
2039 * the cache.
2040 */
2041 if (symnum >= refobj->dynsymcount)
2042 return (NULL); /* Bad object */
2043 if (cache != NULL && cache[symnum].sym != NULL) {
2044 *defobj_out = cache[symnum].obj;
2045 return (cache[symnum].sym);
2046 }
2047
2048 ref = refobj->symtab + symnum;
2049 name = refobj->strtab + ref->st_name;
2050 def = NULL;
2051 defobj = NULL;
2052 ve = NULL;
2053
2054 /*
2055 * We don't have to do a full scale lookup if the symbol is local.
2056 * We know it will bind to the instance in this load module; to
2057 * which we already have a pointer (ie ref). By not doing a lookup,
2058 * we not only improve performance, but it also avoids unresolvable
2059 * symbols when local symbols are not in the hash table. This has
2060 * been seen with the ia64 toolchain.
2061 */
2062 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
2063 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
2064 _rtld_error("%s: Bogus symbol table entry %lu",
2065 refobj->path, symnum);
2066 }
2067 symlook_init(&req, name);
2068 req.flags = flags;
2069 ve = req.ventry = fetch_ventry(refobj, symnum);
2070 req.lockstate = lockstate;
2071 res = symlook_default(&req, refobj);
2072 if (res == 0) {
2073 def = req.sym_out;
2074 defobj = req.defobj_out;
2075 }
2076 } else {
2077 def = ref;
2078 defobj = refobj;
2079 }
2080
2081 /*
2082 * If we found no definition and the reference is weak, treat the
2083 * symbol as having the value zero.
2084 */
2085 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2086 def = &sym_zero;
2087 defobj = obj_main;
2088 }
2089
2090 if (def != NULL) {
2091 *defobj_out = defobj;
2092 /*
2093 * Record the information in the cache to avoid subsequent
2094 * lookups.
2095 */
2096 if (cache != NULL) {
2097 cache[symnum].sym = def;
2098 cache[symnum].obj = defobj;
2099 }
2100 } else {
2101 if (refobj != &obj_rtld)
2102 _rtld_error("%s: Undefined symbol \"%s%s%s\"",
2103 refobj->path, name, ve != NULL ? "@" : "",
2104 ve != NULL ? ve->name : "");
2105 }
2106 return (def);
2107 }
2108
2109 /* Convert between native byte order and forced little resp. big endian. */
2110 #define COND_SWAP(n) (is_le ? le32toh(n) : be32toh(n))
2111
2112 /*
2113 * Return the search path from the ldconfig hints file, reading it if
2114 * necessary. If nostdlib is true, then the default search paths are
2115 * not added to result.
2116 *
2117 * Returns NULL if there are problems with the hints file,
2118 * or if the search path there is empty.
2119 */
2120 static const char *
gethints(bool nostdlib)2121 gethints(bool nostdlib)
2122 {
2123 static char *filtered_path;
2124 static const char *hints;
2125 static struct elfhints_hdr hdr;
2126 struct fill_search_info_args sargs, hargs;
2127 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2128 struct dl_serpath *SLPpath, *hintpath;
2129 char *p;
2130 struct stat hint_stat;
2131 unsigned int SLPndx, hintndx, fndx, fcount;
2132 int fd;
2133 size_t flen;
2134 uint32_t dl;
2135 uint32_t magic; /* Magic number */
2136 uint32_t version; /* File version (1) */
2137 uint32_t strtab; /* Offset of string table in file */
2138 uint32_t dirlist; /* Offset of directory list in string table */
2139 uint32_t dirlistlen; /* strlen(dirlist) */
2140 bool is_le; /* Does the hints file use little endian */
2141 bool skip;
2142
2143 /* First call, read the hints file */
2144 if (hints == NULL) {
2145 /* Keep from trying again in case the hints file is bad. */
2146 hints = "";
2147
2148 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) ==
2149 -1) {
2150 dbg("failed to open hints file \"%s\"",
2151 ld_elf_hints_path);
2152 return (NULL);
2153 }
2154
2155 /*
2156 * Check of hdr.dirlistlen value against type limit
2157 * intends to pacify static analyzers. Further
2158 * paranoia leads to checks that dirlist is fully
2159 * contained in the file range.
2160 */
2161 if (read(fd, &hdr, sizeof hdr) != sizeof hdr) {
2162 dbg("failed to read %lu bytes from hints file \"%s\"",
2163 (u_long)sizeof hdr, ld_elf_hints_path);
2164 cleanup1:
2165 close(fd);
2166 hdr.dirlistlen = 0;
2167 return (NULL);
2168 }
2169 dbg("host byte-order: %s-endian",
2170 le32toh(1) == 1 ? "little" : "big");
2171 dbg("hints file byte-order: %s-endian",
2172 hdr.magic == htole32(ELFHINTS_MAGIC) ? "little" : "big");
2173 is_le = /*htole32(1) == 1 || */ hdr.magic ==
2174 htole32(ELFHINTS_MAGIC);
2175 magic = COND_SWAP(hdr.magic);
2176 version = COND_SWAP(hdr.version);
2177 strtab = COND_SWAP(hdr.strtab);
2178 dirlist = COND_SWAP(hdr.dirlist);
2179 dirlistlen = COND_SWAP(hdr.dirlistlen);
2180 if (magic != ELFHINTS_MAGIC) {
2181 dbg("invalid magic number %#08x (expected: %#08x)",
2182 magic, ELFHINTS_MAGIC);
2183 goto cleanup1;
2184 }
2185 if (version != 1) {
2186 dbg("hints file version %d (expected: 1)", version);
2187 goto cleanup1;
2188 }
2189 if (dirlistlen > UINT_MAX / 2) {
2190 dbg("directory list is to long: %d > %d", dirlistlen,
2191 UINT_MAX / 2);
2192 goto cleanup1;
2193 }
2194 if (fstat(fd, &hint_stat) == -1) {
2195 dbg("failed to find length of hints file \"%s\"",
2196 ld_elf_hints_path);
2197 goto cleanup1;
2198 }
2199 dl = strtab;
2200 if (dl + dirlist < dl) {
2201 dbg("invalid string table position %d", dl);
2202 goto cleanup1;
2203 }
2204 dl += dirlist;
2205 if (dl + dirlistlen < dl) {
2206 dbg("invalid directory list offset %d", dirlist);
2207 goto cleanup1;
2208 }
2209 dl += dirlistlen;
2210 if (dl > hint_stat.st_size) {
2211 dbg("hints file \"%s\" is truncated (%d vs. %jd bytes)",
2212 ld_elf_hints_path, dl,
2213 (uintmax_t)hint_stat.st_size);
2214 goto cleanup1;
2215 }
2216 p = xmalloc(dirlistlen + 1);
2217 if (pread(fd, p, dirlistlen + 1, strtab + dirlist) !=
2218 (ssize_t)dirlistlen + 1 || p[dirlistlen] != '\0') {
2219 free(p);
2220 dbg(
2221 "failed to read %d bytes starting at %d from hints file \"%s\"",
2222 dirlistlen + 1, strtab + dirlist,
2223 ld_elf_hints_path);
2224 goto cleanup1;
2225 }
2226 hints = p;
2227 close(fd);
2228 }
2229
2230 /*
2231 * If caller agreed to receive list which includes the default
2232 * paths, we are done. Otherwise, if we still did not
2233 * calculated filtered result, do it now.
2234 */
2235 if (!nostdlib)
2236 return (hints[0] != '\0' ? hints : NULL);
2237 if (filtered_path != NULL)
2238 goto filt_ret;
2239
2240 /*
2241 * Obtain the list of all configured search paths, and the
2242 * list of the default paths.
2243 *
2244 * First estimate the size of the results.
2245 */
2246 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2247 smeta.dls_cnt = 0;
2248 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2249 hmeta.dls_cnt = 0;
2250
2251 sargs.request = RTLD_DI_SERINFOSIZE;
2252 sargs.serinfo = &smeta;
2253 hargs.request = RTLD_DI_SERINFOSIZE;
2254 hargs.serinfo = &hmeta;
2255
2256 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2257 &sargs);
2258 path_enumerate(hints, fill_search_info, NULL, &hargs);
2259
2260 SLPinfo = xmalloc(smeta.dls_size);
2261 hintinfo = xmalloc(hmeta.dls_size);
2262
2263 /*
2264 * Next fetch both sets of paths.
2265 */
2266 sargs.request = RTLD_DI_SERINFO;
2267 sargs.serinfo = SLPinfo;
2268 sargs.serpath = &SLPinfo->dls_serpath[0];
2269 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2270
2271 hargs.request = RTLD_DI_SERINFO;
2272 hargs.serinfo = hintinfo;
2273 hargs.serpath = &hintinfo->dls_serpath[0];
2274 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2275
2276 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2277 &sargs);
2278 path_enumerate(hints, fill_search_info, NULL, &hargs);
2279
2280 /*
2281 * Now calculate the difference between two sets, by excluding
2282 * standard paths from the full set.
2283 */
2284 fndx = 0;
2285 fcount = 0;
2286 filtered_path = xmalloc(dirlistlen + 1);
2287 hintpath = &hintinfo->dls_serpath[0];
2288 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2289 skip = false;
2290 SLPpath = &SLPinfo->dls_serpath[0];
2291 /*
2292 * Check each standard path against current.
2293 */
2294 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2295 /* matched, skip the path */
2296 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2297 skip = true;
2298 break;
2299 }
2300 }
2301 if (skip)
2302 continue;
2303 /*
2304 * Not matched against any standard path, add the path
2305 * to result. Separate consequtive paths with ':'.
2306 */
2307 if (fcount > 0) {
2308 filtered_path[fndx] = ':';
2309 fndx++;
2310 }
2311 fcount++;
2312 flen = strlen(hintpath->dls_name);
2313 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
2314 fndx += flen;
2315 }
2316 filtered_path[fndx] = '\0';
2317
2318 free(SLPinfo);
2319 free(hintinfo);
2320
2321 filt_ret:
2322 return (filtered_path[0] != '\0' ? filtered_path : NULL);
2323 }
2324
2325 static void
init_dag(Obj_Entry * root)2326 init_dag(Obj_Entry *root)
2327 {
2328 const Needed_Entry *needed;
2329 const Objlist_Entry *elm;
2330 DoneList donelist;
2331
2332 if (root->dag_inited)
2333 return;
2334 donelist_init(&donelist);
2335
2336 /* Root object belongs to own DAG. */
2337 objlist_push_tail(&root->dldags, root);
2338 objlist_push_tail(&root->dagmembers, root);
2339 donelist_check(&donelist, root);
2340
2341 /*
2342 * Add dependencies of root object to DAG in breadth order
2343 * by exploiting the fact that each new object get added
2344 * to the tail of the dagmembers list.
2345 */
2346 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2347 for (needed = elm->obj->needed; needed != NULL;
2348 needed = needed->next) {
2349 if (needed->obj == NULL ||
2350 donelist_check(&donelist, needed->obj))
2351 continue;
2352 objlist_push_tail(&needed->obj->dldags, root);
2353 objlist_push_tail(&root->dagmembers, needed->obj);
2354 }
2355 }
2356 root->dag_inited = true;
2357 }
2358
2359 static void
init_marker(Obj_Entry * marker)2360 init_marker(Obj_Entry *marker)
2361 {
2362 bzero(marker, sizeof(*marker));
2363 marker->marker = true;
2364 }
2365
2366 Obj_Entry *
globallist_curr(const Obj_Entry * obj)2367 globallist_curr(const Obj_Entry *obj)
2368 {
2369 for (;;) {
2370 if (obj == NULL)
2371 return (NULL);
2372 if (!obj->marker)
2373 return (__DECONST(Obj_Entry *, obj));
2374 obj = TAILQ_PREV(obj, obj_entry_q, next);
2375 }
2376 }
2377
2378 Obj_Entry *
globallist_next(const Obj_Entry * obj)2379 globallist_next(const Obj_Entry *obj)
2380 {
2381 for (;;) {
2382 obj = TAILQ_NEXT(obj, next);
2383 if (obj == NULL)
2384 return (NULL);
2385 if (!obj->marker)
2386 return (__DECONST(Obj_Entry *, obj));
2387 }
2388 }
2389
2390 /* Prevent the object from being unmapped while the bind lock is dropped. */
2391 static void
hold_object(Obj_Entry * obj)2392 hold_object(Obj_Entry *obj)
2393 {
2394 obj->holdcount++;
2395 }
2396
2397 static void
unhold_object(Obj_Entry * obj)2398 unhold_object(Obj_Entry *obj)
2399 {
2400 assert(obj->holdcount > 0);
2401 if (--obj->holdcount == 0 && obj->unholdfree)
2402 release_object(obj);
2403 }
2404
2405 static void
process_z(Obj_Entry * root)2406 process_z(Obj_Entry *root)
2407 {
2408 const Objlist_Entry *elm;
2409 Obj_Entry *obj;
2410
2411 /*
2412 * Walk over object DAG and process every dependent object
2413 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2414 * to grow their own DAG.
2415 *
2416 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2417 * symlook_global() to work.
2418 *
2419 * For DF_1_NODELETE, the DAG should have its reference upped.
2420 */
2421 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2422 obj = elm->obj;
2423 if (obj == NULL)
2424 continue;
2425 if (obj->z_nodelete && !obj->ref_nodel) {
2426 dbg("obj %s -z nodelete", obj->path);
2427 init_dag(obj);
2428 ref_dag(obj);
2429 obj->ref_nodel = true;
2430 }
2431 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2432 dbg("obj %s -z global", obj->path);
2433 objlist_push_tail(&list_global, obj);
2434 init_dag(obj);
2435 }
2436 }
2437 }
2438
2439 static void
parse_rtld_phdr(Obj_Entry * obj)2440 parse_rtld_phdr(Obj_Entry *obj)
2441 {
2442 const Elf_Phdr *ph;
2443 Elf_Addr note_start, note_end;
2444 bool first_seg;
2445
2446 first_seg = true;
2447 obj->stack_flags = PF_X | PF_R | PF_W;
2448 for (ph = obj->phdr;
2449 (const char *)ph < (const char *)obj->phdr + obj->phsize; ph++) {
2450 switch (ph->p_type) {
2451 case PT_LOAD:
2452 if (first_seg) {
2453 obj->vaddrbase = rtld_trunc_page(ph->p_vaddr);
2454 first_seg = false;
2455 }
2456 obj->mapsize = rtld_round_page(ph->p_vaddr +
2457 ph->p_memsz) - obj->vaddrbase;
2458 break;
2459 case PT_GNU_STACK:
2460 obj->stack_flags = ph->p_flags;
2461 break;
2462 case PT_NOTE:
2463 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2464 note_end = note_start + ph->p_filesz;
2465 digest_notes(obj, note_start, note_end);
2466 break;
2467 }
2468 }
2469 }
2470
2471 /*
2472 * Initialize the dynamic linker. The argument is the address at which
2473 * the dynamic linker has been mapped into memory. The primary task of
2474 * this function is to relocate the dynamic linker.
2475 */
2476 static void
init_rtld(caddr_t mapbase,Elf_Auxinfo ** aux_info)2477 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2478 {
2479 Obj_Entry objtmp; /* Temporary rtld object */
2480 const Elf_Ehdr *ehdr;
2481 const Elf_Dyn *dyn_rpath;
2482 const Elf_Dyn *dyn_soname;
2483 const Elf_Dyn *dyn_runpath;
2484
2485 /*
2486 * Conjure up an Obj_Entry structure for the dynamic linker.
2487 *
2488 * The "path" member can't be initialized yet because string constants
2489 * cannot yet be accessed. Below we will set it correctly.
2490 */
2491 memset(&objtmp, 0, sizeof(objtmp));
2492 objtmp.path = NULL;
2493 objtmp.rtld = true;
2494 objtmp.mapbase = mapbase;
2495 #ifdef PIC
2496 objtmp.relocbase = mapbase;
2497 #endif
2498
2499 objtmp.dynamic = rtld_dynamic(&objtmp);
2500 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2501 assert(objtmp.needed == NULL);
2502 assert(!objtmp.textrel);
2503 /*
2504 * Temporarily put the dynamic linker entry into the object list, so
2505 * that symbols can be found.
2506 */
2507 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2508
2509 ehdr = (Elf_Ehdr *)mapbase;
2510 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2511 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2512
2513 /* Initialize the object list. */
2514 TAILQ_INIT(&obj_list);
2515
2516 /* Now that non-local variables can be accesses, copy out obj_rtld. */
2517 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2518
2519 /* The page size is required by the dynamic memory allocator. */
2520 init_pagesizes(aux_info);
2521
2522 if (aux_info[AT_OSRELDATE] != NULL)
2523 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2524
2525 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2526
2527 /* Replace the path with a dynamically allocated copy. */
2528 obj_rtld.path = xstrdup(ld_path_rtld);
2529
2530 parse_rtld_phdr(&obj_rtld);
2531 if (obj_enforce_relro(&obj_rtld) == -1)
2532 rtld_die();
2533
2534 r_debug.r_version = R_DEBUG_VERSION;
2535 r_debug.r_brk = r_debug_state;
2536 r_debug.r_state = RT_CONSISTENT;
2537 r_debug.r_ldbase = obj_rtld.relocbase;
2538 }
2539
2540 /*
2541 * Retrieve the array of supported page sizes. The kernel provides the page
2542 * sizes in increasing order.
2543 */
2544 static void
init_pagesizes(Elf_Auxinfo ** aux_info)2545 init_pagesizes(Elf_Auxinfo **aux_info)
2546 {
2547 static size_t psa[MAXPAGESIZES];
2548 int mib[2];
2549 size_t len, size;
2550
2551 if (aux_info[AT_PAGESIZES] != NULL &&
2552 aux_info[AT_PAGESIZESLEN] != NULL) {
2553 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2554 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2555 } else {
2556 len = 2;
2557 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2558 size = sizeof(psa);
2559 else {
2560 /* As a fallback, retrieve the base page size. */
2561 size = sizeof(psa[0]);
2562 if (aux_info[AT_PAGESZ] != NULL) {
2563 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2564 goto psa_filled;
2565 } else {
2566 mib[0] = CTL_HW;
2567 mib[1] = HW_PAGESIZE;
2568 len = 2;
2569 }
2570 }
2571 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2572 _rtld_error("sysctl for hw.pagesize(s) failed");
2573 rtld_die();
2574 }
2575 psa_filled:
2576 pagesizes = psa;
2577 }
2578 npagesizes = size / sizeof(pagesizes[0]);
2579 /* Discard any invalid entries at the end of the array. */
2580 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2581 npagesizes--;
2582
2583 page_size = pagesizes[0];
2584 }
2585
2586 /*
2587 * Add the init functions from a needed object list (and its recursive
2588 * needed objects) to "list". This is not used directly; it is a helper
2589 * function for initlist_add_objects(). The write lock must be held
2590 * when this function is called.
2591 */
2592 static void
initlist_add_neededs(Needed_Entry * needed,Objlist * list,Objlist * iflist)2593 initlist_add_neededs(Needed_Entry *needed, Objlist *list, Objlist *iflist)
2594 {
2595 /* Recursively process the successor needed objects. */
2596 if (needed->next != NULL)
2597 initlist_add_neededs(needed->next, list, iflist);
2598
2599 /* Process the current needed object. */
2600 if (needed->obj != NULL)
2601 initlist_add_objects(needed->obj, needed->obj, list, iflist);
2602 }
2603
2604 /*
2605 * Scan all of the DAGs rooted in the range of objects from "obj" to
2606 * "tail" and add their init functions to "list". This recurses over
2607 * the DAGs and ensure the proper init ordering such that each object's
2608 * needed libraries are initialized before the object itself. At the
2609 * same time, this function adds the objects to the global finalization
2610 * list "list_fini" in the opposite order. The write lock must be
2611 * held when this function is called.
2612 */
2613 static void
initlist_for_loaded_obj(Obj_Entry * obj,Obj_Entry * tail,Objlist * list)2614 initlist_for_loaded_obj(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2615 {
2616 Objlist iflist; /* initfirst objs and their needed */
2617 Objlist_Entry *tmp;
2618
2619 objlist_init(&iflist);
2620 initlist_add_objects(obj, tail, list, &iflist);
2621
2622 STAILQ_FOREACH(tmp, &iflist, link) {
2623 Obj_Entry *tobj = tmp->obj;
2624
2625 if ((tobj->fini != (Elf_Addr)NULL ||
2626 tobj->fini_array != (Elf_Addr)NULL) &&
2627 !tobj->on_fini_list) {
2628 objlist_push_tail(&list_fini, tobj);
2629 tobj->on_fini_list = true;
2630 }
2631 }
2632
2633 /*
2634 * This might result in the same object appearing more
2635 * than once on the init list. objlist_call_init()
2636 * uses obj->init_scanned to avoid dup calls.
2637 */
2638 STAILQ_REVERSE(&iflist, Struct_Objlist_Entry, link);
2639 STAILQ_FOREACH(tmp, &iflist, link)
2640 objlist_push_head(list, tmp->obj);
2641
2642 objlist_clear(&iflist);
2643 }
2644
2645 static void
initlist_add_objects(Obj_Entry * obj,Obj_Entry * tail,Objlist * list,Objlist * iflist)2646 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list,
2647 Objlist *iflist)
2648 {
2649 Obj_Entry *nobj;
2650
2651 if (obj->init_done)
2652 return;
2653
2654 if (obj->z_initfirst || list == NULL) {
2655 /*
2656 * Ignore obj->init_scanned. The object might indeed
2657 * already be on the init list, but due to being
2658 * needed by an initfirst object, we must put it at
2659 * the head of the init list. obj->init_done protects
2660 * against double-initialization.
2661 */
2662 if (obj->needed != NULL)
2663 initlist_add_neededs(obj->needed, NULL, iflist);
2664 if (obj->needed_filtees != NULL)
2665 initlist_add_neededs(obj->needed_filtees, NULL,
2666 iflist);
2667 if (obj->needed_aux_filtees != NULL)
2668 initlist_add_neededs(obj->needed_aux_filtees,
2669 NULL, iflist);
2670 objlist_push_tail(iflist, obj);
2671 } else {
2672 if (obj->init_scanned)
2673 return;
2674 obj->init_scanned = true;
2675
2676 /* Recursively process the successor objects. */
2677 nobj = globallist_next(obj);
2678 if (nobj != NULL && obj != tail)
2679 initlist_add_objects(nobj, tail, list, iflist);
2680
2681 /* Recursively process the needed objects. */
2682 if (obj->needed != NULL)
2683 initlist_add_neededs(obj->needed, list, iflist);
2684 if (obj->needed_filtees != NULL)
2685 initlist_add_neededs(obj->needed_filtees, list,
2686 iflist);
2687 if (obj->needed_aux_filtees != NULL)
2688 initlist_add_neededs(obj->needed_aux_filtees, list,
2689 iflist);
2690
2691 /* Add the object to the init list. */
2692 objlist_push_tail(list, obj);
2693
2694 /*
2695 * Add the object to the global fini list in the
2696 * reverse order.
2697 */
2698 if ((obj->fini != (Elf_Addr)NULL ||
2699 obj->fini_array != (Elf_Addr)NULL) &&
2700 !obj->on_fini_list) {
2701 objlist_push_head(&list_fini, obj);
2702 obj->on_fini_list = true;
2703 }
2704 }
2705 }
2706
2707 static void
free_needed_filtees(Needed_Entry * n,RtldLockState * lockstate)2708 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2709 {
2710 Needed_Entry *needed, *needed1;
2711
2712 for (needed = n; needed != NULL; needed = needed->next) {
2713 if (needed->obj != NULL) {
2714 dlclose_locked(needed->obj, lockstate);
2715 needed->obj = NULL;
2716 }
2717 }
2718 for (needed = n; needed != NULL; needed = needed1) {
2719 needed1 = needed->next;
2720 free(needed);
2721 }
2722 }
2723
2724 static void
unload_filtees(Obj_Entry * obj,RtldLockState * lockstate)2725 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2726 {
2727 free_needed_filtees(obj->needed_filtees, lockstate);
2728 obj->needed_filtees = NULL;
2729 free_needed_filtees(obj->needed_aux_filtees, lockstate);
2730 obj->needed_aux_filtees = NULL;
2731 obj->filtees_loaded = false;
2732 }
2733
2734 static void
load_filtee1(Obj_Entry * obj,Needed_Entry * needed,int flags,RtldLockState * lockstate)2735 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2736 RtldLockState *lockstate)
2737 {
2738 for (; needed != NULL; needed = needed->next) {
2739 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2740 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW :
2741 RTLD_LAZY) | RTLD_LOCAL, lockstate);
2742 }
2743 }
2744
2745 static void
load_filtees(Obj_Entry * obj,int flags,RtldLockState * lockstate)2746 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2747 {
2748 if (obj->filtees_loaded || obj->filtees_loading)
2749 return;
2750 lock_restart_for_upgrade(lockstate);
2751 obj->filtees_loading = true;
2752 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2753 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2754 obj->filtees_loaded = true;
2755 obj->filtees_loading = false;
2756 }
2757
2758 static int
process_needed(Obj_Entry * obj,Needed_Entry * needed,int flags)2759 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2760 {
2761 Obj_Entry *obj1;
2762
2763 for (; needed != NULL; needed = needed->next) {
2764 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1,
2765 obj, flags & ~RTLD_LO_NOLOAD);
2766 if (obj1 == NULL && !ld_tracing &&
2767 (flags & RTLD_LO_FILTEES) == 0)
2768 return (-1);
2769 }
2770 return (0);
2771 }
2772
2773 /*
2774 * Given a shared object, traverse its list of needed objects, and load
2775 * each of them. Returns 0 on success. Generates an error message and
2776 * returns -1 on failure.
2777 */
2778 static int
load_needed_objects(Obj_Entry * first,int flags)2779 load_needed_objects(Obj_Entry *first, int flags)
2780 {
2781 Obj_Entry *obj;
2782
2783 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2784 if (obj->marker)
2785 continue;
2786 if (process_needed(obj, obj->needed, flags) == -1)
2787 return (-1);
2788 }
2789 return (0);
2790 }
2791
2792 static int
load_preload_objects(const char * penv,bool isfd)2793 load_preload_objects(const char *penv, bool isfd)
2794 {
2795 Obj_Entry *obj;
2796 const char *name;
2797 size_t len;
2798 char savech, *p, *psave;
2799 int fd;
2800 static const char delim[] = " \t:;";
2801
2802 if (penv == NULL)
2803 return (0);
2804
2805 p = psave = xstrdup(penv);
2806 p += strspn(p, delim);
2807 while (*p != '\0') {
2808 len = strcspn(p, delim);
2809
2810 savech = p[len];
2811 p[len] = '\0';
2812 if (isfd) {
2813 name = NULL;
2814 fd = parse_integer(p);
2815 if (fd == -1) {
2816 free(psave);
2817 return (-1);
2818 }
2819 } else {
2820 name = p;
2821 fd = -1;
2822 }
2823
2824 obj = load_object(name, fd, NULL, 0);
2825 if (obj == NULL) {
2826 free(psave);
2827 return (-1); /* XXX - cleanup */
2828 }
2829 obj->z_interpose = true;
2830 p[len] = savech;
2831 p += len;
2832 p += strspn(p, delim);
2833 }
2834 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2835
2836 free(psave);
2837 return (0);
2838 }
2839
2840 static const char *
printable_path(const char * path)2841 printable_path(const char *path)
2842 {
2843 return (path == NULL ? "<unknown>" : path);
2844 }
2845
2846 /*
2847 * Load a shared object into memory, if it is not already loaded. The
2848 * object may be specified by name or by user-supplied file descriptor
2849 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2850 * duplicate is.
2851 *
2852 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2853 * on failure.
2854 */
2855 static Obj_Entry *
load_object(const char * name,int fd_u,const Obj_Entry * refobj,int flags)2856 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2857 {
2858 Obj_Entry *obj;
2859 int fd;
2860 struct stat sb;
2861 char *path;
2862
2863 fd = -1;
2864 if (name != NULL) {
2865 TAILQ_FOREACH(obj, &obj_list, next) {
2866 if (obj->marker || obj->doomed)
2867 continue;
2868 if (object_match_name(obj, name))
2869 return (obj);
2870 }
2871
2872 path = find_library(name, refobj, &fd);
2873 if (path == NULL)
2874 return (NULL);
2875 } else
2876 path = NULL;
2877
2878 if (fd >= 0) {
2879 /*
2880 * search_library_pathfds() opens a fresh file descriptor for
2881 * the library, so there is no need to dup().
2882 */
2883 } else if (fd_u == -1) {
2884 /*
2885 * If we didn't find a match by pathname, or the name is not
2886 * supplied, open the file and check again by device and inode.
2887 * This avoids false mismatches caused by multiple links or ".."
2888 * in pathnames.
2889 *
2890 * To avoid a race, we open the file and use fstat() rather than
2891 * using stat().
2892 */
2893 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2894 _rtld_error("Cannot open \"%s\"", path);
2895 free(path);
2896 return (NULL);
2897 }
2898 } else {
2899 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2900 if (fd == -1) {
2901 _rtld_error("Cannot dup fd");
2902 free(path);
2903 return (NULL);
2904 }
2905 }
2906 if (fstat(fd, &sb) == -1) {
2907 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2908 close(fd);
2909 free(path);
2910 return (NULL);
2911 }
2912 TAILQ_FOREACH(obj, &obj_list, next) {
2913 if (obj->marker || obj->doomed)
2914 continue;
2915 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2916 break;
2917 }
2918 if (obj != NULL) {
2919 if (name != NULL)
2920 object_add_name(obj, name);
2921 free(path);
2922 close(fd);
2923 return (obj);
2924 }
2925 if (flags & RTLD_LO_NOLOAD) {
2926 free(path);
2927 close(fd);
2928 return (NULL);
2929 }
2930
2931 /* First use of this object, so we must map it in */
2932 obj = do_load_object(fd, name, path, &sb, flags);
2933 if (obj == NULL)
2934 free(path);
2935 close(fd);
2936
2937 return (obj);
2938 }
2939
2940 static Obj_Entry *
do_load_object(int fd,const char * name,char * path,struct stat * sbp,int flags)2941 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2942 int flags)
2943 {
2944 Obj_Entry *obj;
2945 struct statfs fs;
2946
2947 /*
2948 * First, make sure that environment variables haven't been
2949 * used to circumvent the noexec flag on a filesystem.
2950 * We ignore fstatfs(2) failures, since fd might reference
2951 * not a file, e.g. shmfd.
2952 */
2953 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 &&
2954 (fs.f_flags & MNT_NOEXEC) != 0) {
2955 _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2956 return (NULL);
2957 }
2958
2959 dbg("loading \"%s\"", printable_path(path));
2960 obj = map_object(fd, printable_path(path), sbp, false);
2961 if (obj == NULL)
2962 return (NULL);
2963
2964 /*
2965 * If DT_SONAME is present in the object, digest_dynamic2 already
2966 * added it to the object names.
2967 */
2968 if (name != NULL)
2969 object_add_name(obj, name);
2970 obj->path = path;
2971 if (!digest_dynamic(obj, 0))
2972 goto errp;
2973 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2974 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2975 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2976 dbg("refusing to load PIE executable \"%s\"", obj->path);
2977 _rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2978 goto errp;
2979 }
2980 if (obj->z_noopen &&
2981 (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) == RTLD_LO_DLOPEN) {
2982 dbg("refusing to load non-loadable \"%s\"", obj->path);
2983 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2984 goto errp;
2985 }
2986
2987 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2988 TAILQ_INSERT_TAIL(&obj_list, obj, next);
2989 obj_count++;
2990 obj_loads++;
2991 linkmap_add(obj); /* for GDB & dlinfo() */
2992 max_stack_flags |= obj->stack_flags;
2993
2994 dbg(" %p .. %p: %s", obj->mapbase, obj->mapbase + obj->mapsize - 1,
2995 obj->path);
2996 if (obj->textrel)
2997 dbg(" WARNING: %s has impure text", obj->path);
2998 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2999 obj->path);
3000
3001 return (obj);
3002
3003 errp:
3004 munmap(obj->mapbase, obj->mapsize);
3005 obj_free(obj);
3006 return (NULL);
3007 }
3008
3009 static int
load_kpreload(const void * addr)3010 load_kpreload(const void *addr)
3011 {
3012 Obj_Entry *obj;
3013 const Elf_Ehdr *ehdr;
3014 const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn;
3015 static const char kname[] = "[vdso]";
3016
3017 ehdr = addr;
3018 if (!check_elf_headers(ehdr, "kpreload"))
3019 return (-1);
3020 obj = obj_new();
3021 phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff);
3022 obj->phdr = phdr;
3023 obj->phsize = ehdr->e_phnum * sizeof(*phdr);
3024 phlimit = phdr + ehdr->e_phnum;
3025 seg0 = segn = NULL;
3026
3027 for (; phdr < phlimit; phdr++) {
3028 switch (phdr->p_type) {
3029 case PT_DYNAMIC:
3030 phdyn = phdr;
3031 break;
3032 case PT_GNU_STACK:
3033 /* Absense of PT_GNU_STACK implies stack_flags == 0. */
3034 obj->stack_flags = phdr->p_flags;
3035 break;
3036 case PT_LOAD:
3037 if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr)
3038 seg0 = phdr;
3039 if (segn == NULL ||
3040 segn->p_vaddr + segn->p_memsz <
3041 phdr->p_vaddr + phdr->p_memsz)
3042 segn = phdr;
3043 break;
3044 }
3045 }
3046
3047 obj->mapbase = __DECONST(caddr_t, addr);
3048 obj->mapsize = segn->p_vaddr + segn->p_memsz;
3049 obj->vaddrbase = 0;
3050 obj->relocbase = obj->mapbase;
3051
3052 object_add_name(obj, kname);
3053 obj->path = xstrdup(kname);
3054 obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
3055
3056 if (!digest_dynamic(obj, 0)) {
3057 obj_free(obj);
3058 return (-1);
3059 }
3060
3061 /*
3062 * We assume that kernel-preloaded object does not need
3063 * relocation. It is currently written into read-only page,
3064 * handling relocations would mean we need to allocate at
3065 * least one additional page per AS.
3066 */
3067 dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p",
3068 obj->path, obj->mapbase, obj->phdr, seg0,
3069 obj->relocbase + seg0->p_vaddr, obj->dynamic);
3070
3071 TAILQ_INSERT_TAIL(&obj_list, obj, next);
3072 obj_count++;
3073 obj_loads++;
3074 linkmap_add(obj); /* for GDB & dlinfo() */
3075 max_stack_flags |= obj->stack_flags;
3076
3077 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3078 obj->path);
3079 return (0);
3080 }
3081
3082 Obj_Entry *
obj_from_addr(const void * addr)3083 obj_from_addr(const void *addr)
3084 {
3085 Obj_Entry *obj;
3086
3087 TAILQ_FOREACH(obj, &obj_list, next) {
3088 if (obj->marker)
3089 continue;
3090 if (addr < (void *)obj->mapbase)
3091 continue;
3092 if (addr < (void *)(obj->mapbase + obj->mapsize))
3093 return obj;
3094 }
3095 return (NULL);
3096 }
3097
3098 static void
preinit_main(void)3099 preinit_main(void)
3100 {
3101 Elf_Addr *preinit_addr;
3102 int index;
3103
3104 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
3105 if (preinit_addr == NULL)
3106 return;
3107
3108 for (index = 0; index < obj_main->preinit_array_num; index++) {
3109 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
3110 dbg("calling preinit function for %s at %p",
3111 obj_main->path, (void *)preinit_addr[index]);
3112 LD_UTRACE(UTRACE_INIT_CALL, obj_main,
3113 (void *)preinit_addr[index], 0, 0, obj_main->path);
3114 call_init_pointer(obj_main, preinit_addr[index]);
3115 }
3116 }
3117 }
3118
3119 /*
3120 * Call the finalization functions for each of the objects in "list"
3121 * belonging to the DAG of "root" and referenced once. If NULL "root"
3122 * is specified, every finalization function will be called regardless
3123 * of the reference count and the list elements won't be freed. All of
3124 * the objects are expected to have non-NULL fini functions.
3125 */
3126 static void
objlist_call_fini(Objlist * list,Obj_Entry * root,RtldLockState * lockstate)3127 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
3128 {
3129 Objlist_Entry *elm;
3130 struct dlerror_save *saved_msg;
3131 Elf_Addr *fini_addr;
3132 int index;
3133
3134 assert(root == NULL || root->refcount == 1);
3135
3136 if (root != NULL)
3137 root->doomed = true;
3138
3139 /*
3140 * Preserve the current error message since a fini function might
3141 * call into the dynamic linker and overwrite it.
3142 */
3143 saved_msg = errmsg_save();
3144 do {
3145 STAILQ_FOREACH(elm, list, link) {
3146 if (root != NULL &&
3147 (elm->obj->refcount != 1 ||
3148 objlist_find(&root->dagmembers, elm->obj) ==
3149 NULL))
3150 continue;
3151 /* Remove object from fini list to prevent recursive
3152 * invocation. */
3153 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3154 /* Ensure that new references cannot be acquired. */
3155 elm->obj->doomed = true;
3156
3157 hold_object(elm->obj);
3158 lock_release(rtld_bind_lock, lockstate);
3159 /*
3160 * It is legal to have both DT_FINI and DT_FINI_ARRAY
3161 * defined. When this happens, DT_FINI_ARRAY is
3162 * processed first.
3163 */
3164 fini_addr = (Elf_Addr *)elm->obj->fini_array;
3165 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
3166 for (index = elm->obj->fini_array_num - 1;
3167 index >= 0; index--) {
3168 if (fini_addr[index] != 0 &&
3169 fini_addr[index] != 1) {
3170 dbg("calling fini function for %s at %p",
3171 elm->obj->path,
3172 (void *)fini_addr[index]);
3173 LD_UTRACE(UTRACE_FINI_CALL,
3174 elm->obj,
3175 (void *)fini_addr[index], 0,
3176 0, elm->obj->path);
3177 call_initfini_pointer(elm->obj,
3178 fini_addr[index]);
3179 }
3180 }
3181 }
3182 if (elm->obj->fini != (Elf_Addr)NULL) {
3183 dbg("calling fini function for %s at %p",
3184 elm->obj->path, (void *)elm->obj->fini);
3185 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
3186 (void *)elm->obj->fini, 0, 0,
3187 elm->obj->path);
3188 call_initfini_pointer(elm->obj, elm->obj->fini);
3189 }
3190 wlock_acquire(rtld_bind_lock, lockstate);
3191 unhold_object(elm->obj);
3192 /* No need to free anything if process is going down. */
3193 if (root != NULL)
3194 free(elm);
3195 /*
3196 * We must restart the list traversal after every fini
3197 * call because a dlclose() call from the fini function
3198 * or from another thread might have modified the
3199 * reference counts.
3200 */
3201 break;
3202 }
3203 } while (elm != NULL);
3204 errmsg_restore(saved_msg);
3205 }
3206
3207 /*
3208 * Call the initialization functions for each of the objects in
3209 * "list". All of the objects are expected to have non-NULL init
3210 * functions.
3211 */
3212 static void
objlist_call_init(Objlist * list,RtldLockState * lockstate)3213 objlist_call_init(Objlist *list, RtldLockState *lockstate)
3214 {
3215 Objlist_Entry *elm;
3216 Obj_Entry *obj;
3217 struct dlerror_save *saved_msg;
3218 Elf_Addr *init_addr;
3219 void (*reg)(void (*)(void));
3220 int index;
3221
3222 /*
3223 * Clean init_scanned flag so that objects can be rechecked and
3224 * possibly initialized earlier if any of vectors called below
3225 * cause the change by using dlopen.
3226 */
3227 TAILQ_FOREACH(obj, &obj_list, next) {
3228 if (obj->marker)
3229 continue;
3230 obj->init_scanned = false;
3231 }
3232
3233 /*
3234 * Preserve the current error message since an init function might
3235 * call into the dynamic linker and overwrite it.
3236 */
3237 saved_msg = errmsg_save();
3238 STAILQ_FOREACH(elm, list, link) {
3239 if (elm->obj->init_done) /* Initialized early. */
3240 continue;
3241 /*
3242 * Race: other thread might try to use this object before
3243 * current one completes the initialization. Not much can be
3244 * done here without better locking.
3245 */
3246 elm->obj->init_done = true;
3247 hold_object(elm->obj);
3248 reg = NULL;
3249 if (elm->obj == obj_main && obj_main->crt_no_init) {
3250 reg = (void (*)(void (*)(void)))
3251 get_program_var_addr("__libc_atexit", lockstate);
3252 }
3253 lock_release(rtld_bind_lock, lockstate);
3254 if (reg != NULL) {
3255 reg(rtld_exit);
3256 rtld_exit_ptr = rtld_nop_exit;
3257 }
3258
3259 /*
3260 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
3261 * When this happens, DT_INIT is processed first.
3262 */
3263 if (elm->obj->init != (Elf_Addr)NULL) {
3264 dbg("calling init function for %s at %p",
3265 elm->obj->path, (void *)elm->obj->init);
3266 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3267 (void *)elm->obj->init, 0, 0, elm->obj->path);
3268 call_init_pointer(elm->obj, elm->obj->init);
3269 }
3270 init_addr = (Elf_Addr *)elm->obj->init_array;
3271 if (init_addr != NULL) {
3272 for (index = 0; index < elm->obj->init_array_num;
3273 index++) {
3274 if (init_addr[index] != 0 &&
3275 init_addr[index] != 1) {
3276 dbg("calling init function for %s at %p",
3277 elm->obj->path,
3278 (void *)init_addr[index]);
3279 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3280 (void *)init_addr[index], 0, 0,
3281 elm->obj->path);
3282 call_init_pointer(elm->obj,
3283 init_addr[index]);
3284 }
3285 }
3286 }
3287 wlock_acquire(rtld_bind_lock, lockstate);
3288 unhold_object(elm->obj);
3289 }
3290 errmsg_restore(saved_msg);
3291 }
3292
3293 static void
objlist_clear(Objlist * list)3294 objlist_clear(Objlist *list)
3295 {
3296 Objlist_Entry *elm;
3297
3298 while (!STAILQ_EMPTY(list)) {
3299 elm = STAILQ_FIRST(list);
3300 STAILQ_REMOVE_HEAD(list, link);
3301 free(elm);
3302 }
3303 }
3304
3305 static Objlist_Entry *
objlist_find(Objlist * list,const Obj_Entry * obj)3306 objlist_find(Objlist *list, const Obj_Entry *obj)
3307 {
3308 Objlist_Entry *elm;
3309
3310 STAILQ_FOREACH(elm, list, link)
3311 if (elm->obj == obj)
3312 return elm;
3313 return (NULL);
3314 }
3315
3316 static void
objlist_init(Objlist * list)3317 objlist_init(Objlist *list)
3318 {
3319 STAILQ_INIT(list);
3320 }
3321
3322 static void
objlist_push_head(Objlist * list,Obj_Entry * obj)3323 objlist_push_head(Objlist *list, Obj_Entry *obj)
3324 {
3325 Objlist_Entry *elm;
3326
3327 elm = NEW(Objlist_Entry);
3328 elm->obj = obj;
3329 STAILQ_INSERT_HEAD(list, elm, link);
3330 }
3331
3332 static void
objlist_push_tail(Objlist * list,Obj_Entry * obj)3333 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3334 {
3335 Objlist_Entry *elm;
3336
3337 elm = NEW(Objlist_Entry);
3338 elm->obj = obj;
3339 STAILQ_INSERT_TAIL(list, elm, link);
3340 }
3341
3342 static void
objlist_put_after(Objlist * list,Obj_Entry * listobj,Obj_Entry * obj)3343 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3344 {
3345 Objlist_Entry *elm, *listelm;
3346
3347 STAILQ_FOREACH(listelm, list, link) {
3348 if (listelm->obj == listobj)
3349 break;
3350 }
3351 elm = NEW(Objlist_Entry);
3352 elm->obj = obj;
3353 if (listelm != NULL)
3354 STAILQ_INSERT_AFTER(list, listelm, elm, link);
3355 else
3356 STAILQ_INSERT_TAIL(list, elm, link);
3357 }
3358
3359 static void
objlist_remove(Objlist * list,Obj_Entry * obj)3360 objlist_remove(Objlist *list, Obj_Entry *obj)
3361 {
3362 Objlist_Entry *elm;
3363
3364 if ((elm = objlist_find(list, obj)) != NULL) {
3365 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3366 free(elm);
3367 }
3368 }
3369
3370 /*
3371 * Relocate dag rooted in the specified object.
3372 * Returns 0 on success, or -1 on failure.
3373 */
3374
3375 static int
relocate_object_dag(Obj_Entry * root,bool bind_now,Obj_Entry * rtldobj,int flags,RtldLockState * lockstate)3376 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3377 int flags, RtldLockState *lockstate)
3378 {
3379 Objlist_Entry *elm;
3380 int error;
3381
3382 error = 0;
3383 STAILQ_FOREACH(elm, &root->dagmembers, link) {
3384 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3385 lockstate);
3386 if (error == -1)
3387 break;
3388 }
3389 return (error);
3390 }
3391
3392 /*
3393 * Prepare for, or clean after, relocating an object marked with
3394 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
3395 * segments are remapped read-write. After relocations are done, the
3396 * segment's permissions are returned back to the modes specified in
3397 * the phdrs. If any relocation happened, or always for wired
3398 * program, COW is triggered.
3399 */
3400 static int
reloc_textrel_prot(Obj_Entry * obj,bool before)3401 reloc_textrel_prot(Obj_Entry *obj, bool before)
3402 {
3403 const Elf_Phdr *ph;
3404 void *base;
3405 size_t l, sz;
3406 int prot;
3407
3408 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0; l--, ph++) {
3409 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3410 continue;
3411 base = obj->relocbase + rtld_trunc_page(ph->p_vaddr);
3412 sz = rtld_round_page(ph->p_vaddr + ph->p_filesz) -
3413 rtld_trunc_page(ph->p_vaddr);
3414 prot = before ? (PROT_READ | PROT_WRITE) :
3415 convert_prot(ph->p_flags);
3416 if (mprotect(base, sz, prot) == -1) {
3417 _rtld_error("%s: Cannot write-%sable text segment: %s",
3418 obj->path, before ? "en" : "dis",
3419 rtld_strerror(errno));
3420 return (-1);
3421 }
3422 }
3423 return (0);
3424 }
3425
3426 /* Process RELR relative relocations. */
3427 static void
reloc_relr(Obj_Entry * obj)3428 reloc_relr(Obj_Entry *obj)
3429 {
3430 const Elf_Relr *relr, *relrlim;
3431 Elf_Addr *where;
3432
3433 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize);
3434 for (relr = obj->relr; relr < relrlim; relr++) {
3435 Elf_Relr entry = *relr;
3436
3437 if ((entry & 1) == 0) {
3438 where = (Elf_Addr *)(obj->relocbase + entry);
3439 *where++ += (Elf_Addr)obj->relocbase;
3440 } else {
3441 for (long i = 0; (entry >>= 1) != 0; i++)
3442 if ((entry & 1) != 0)
3443 where[i] += (Elf_Addr)obj->relocbase;
3444 where += CHAR_BIT * sizeof(Elf_Relr) - 1;
3445 }
3446 }
3447 }
3448
3449 /*
3450 * Relocate single object.
3451 * Returns 0 on success, or -1 on failure.
3452 */
3453 static int
relocate_object(Obj_Entry * obj,bool bind_now,Obj_Entry * rtldobj,int flags,RtldLockState * lockstate)3454 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, int flags,
3455 RtldLockState *lockstate)
3456 {
3457 if (obj->relocated)
3458 return (0);
3459 obj->relocated = true;
3460 if (obj != rtldobj)
3461 dbg("relocating \"%s\"", obj->path);
3462
3463 if (obj->symtab == NULL || obj->strtab == NULL ||
3464 !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3465 dbg("object %s has no run-time symbol table", obj->path);
3466
3467 /* There are relocations to the write-protected text segment. */
3468 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3469 return (-1);
3470
3471 /* Process the non-PLT non-IFUNC relocations. */
3472 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3473 return (-1);
3474 reloc_relr(obj);
3475
3476 /* Re-protected the text segment. */
3477 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3478 return (-1);
3479
3480 /* Set the special PLT or GOT entries. */
3481 init_pltgot(obj);
3482
3483 /* Process the PLT relocations. */
3484 if (reloc_plt(obj, flags, lockstate) == -1)
3485 return (-1);
3486 /* Relocate the jump slots if we are doing immediate binding. */
3487 if ((obj->bind_now || bind_now) &&
3488 reloc_jmpslots(obj, flags, lockstate) == -1)
3489 return (-1);
3490
3491 if (obj != rtldobj && !obj->mainprog && obj_enforce_relro(obj) == -1)
3492 return (-1);
3493
3494 /*
3495 * Set up the magic number and version in the Obj_Entry. These
3496 * were checked in the crt1.o from the original ElfKit, so we
3497 * set them for backward compatibility.
3498 */
3499 obj->magic = RTLD_MAGIC;
3500 obj->version = RTLD_VERSION;
3501
3502 return (0);
3503 }
3504
3505 /*
3506 * Relocate newly-loaded shared objects. The argument is a pointer to
3507 * the Obj_Entry for the first such object. All objects from the first
3508 * to the end of the list of objects are relocated. Returns 0 on success,
3509 * or -1 on failure.
3510 */
3511 static int
relocate_objects(Obj_Entry * first,bool bind_now,Obj_Entry * rtldobj,int flags,RtldLockState * lockstate)3512 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj, int flags,
3513 RtldLockState *lockstate)
3514 {
3515 Obj_Entry *obj;
3516 int error;
3517
3518 for (error = 0, obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3519 if (obj->marker)
3520 continue;
3521 error = relocate_object(obj, bind_now, rtldobj, flags,
3522 lockstate);
3523 if (error == -1)
3524 break;
3525 }
3526 return (error);
3527 }
3528
3529 /*
3530 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3531 * referencing STT_GNU_IFUNC symbols is postponed till the other
3532 * relocations are done. The indirect functions specified as
3533 * ifunc are allowed to call other symbols, so we need to have
3534 * objects relocated before asking for resolution from indirects.
3535 *
3536 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3537 * instead of the usual lazy handling of PLT slots. It is
3538 * consistent with how GNU does it.
3539 */
3540 static int
resolve_object_ifunc(Obj_Entry * obj,bool bind_now,int flags,RtldLockState * lockstate)3541 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3542 RtldLockState *lockstate)
3543 {
3544 if (obj->ifuncs_resolved)
3545 return (0);
3546 obj->ifuncs_resolved = true;
3547 if (!obj->irelative && !obj->irelative_nonplt &&
3548 !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3549 !obj->non_plt_gnu_ifunc)
3550 return (0);
3551 if (obj_disable_relro(obj) == -1 ||
3552 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3553 (obj->irelative_nonplt &&
3554 reloc_iresolve_nonplt(obj, lockstate) == -1) ||
3555 ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3556 reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3557 (obj->non_plt_gnu_ifunc &&
3558 reloc_non_plt(obj, &obj_rtld, flags | SYMLOOK_IFUNC,
3559 lockstate) == -1) ||
3560 obj_enforce_relro(obj) == -1)
3561 return (-1);
3562 return (0);
3563 }
3564
3565 static int
initlist_objects_ifunc(Objlist * list,bool bind_now,int flags,RtldLockState * lockstate)3566 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3567 RtldLockState *lockstate)
3568 {
3569 Objlist_Entry *elm;
3570 Obj_Entry *obj;
3571
3572 STAILQ_FOREACH(elm, list, link) {
3573 obj = elm->obj;
3574 if (obj->marker)
3575 continue;
3576 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
3577 return (-1);
3578 }
3579 return (0);
3580 }
3581
3582 /*
3583 * Cleanup procedure. It will be called (by the atexit mechanism) just
3584 * before the process exits.
3585 */
3586 static void
rtld_exit(void)3587 rtld_exit(void)
3588 {
3589 RtldLockState lockstate;
3590
3591 wlock_acquire(rtld_bind_lock, &lockstate);
3592 dbg("rtld_exit()");
3593 objlist_call_fini(&list_fini, NULL, &lockstate);
3594 /* No need to remove the items from the list, since we are exiting. */
3595 if (!libmap_disable)
3596 lm_fini();
3597 lock_release(rtld_bind_lock, &lockstate);
3598 }
3599
3600 static void
rtld_nop_exit(void)3601 rtld_nop_exit(void)
3602 {
3603 }
3604
3605 /*
3606 * Iterate over a search path, translate each element, and invoke the
3607 * callback on the result.
3608 */
3609 static void *
path_enumerate(const char * path,path_enum_proc callback,const char * refobj_path,void * arg)3610 path_enumerate(const char *path, path_enum_proc callback,
3611 const char *refobj_path, void *arg)
3612 {
3613 const char *trans;
3614 if (path == NULL)
3615 return (NULL);
3616
3617 path += strspn(path, ":;");
3618 while (*path != '\0') {
3619 size_t len;
3620 char *res;
3621
3622 len = strcspn(path, ":;");
3623 trans = lm_findn(refobj_path, path, len);
3624 if (trans)
3625 res = callback(trans, strlen(trans), arg);
3626 else
3627 res = callback(path, len, arg);
3628
3629 if (res != NULL)
3630 return (res);
3631
3632 path += len;
3633 path += strspn(path, ":;");
3634 }
3635
3636 return (NULL);
3637 }
3638
3639 struct try_library_args {
3640 const char *name;
3641 size_t namelen;
3642 char *buffer;
3643 size_t buflen;
3644 int fd;
3645 };
3646
3647 static void *
try_library_path(const char * dir,size_t dirlen,void * param)3648 try_library_path(const char *dir, size_t dirlen, void *param)
3649 {
3650 struct try_library_args *arg;
3651 int fd;
3652
3653 arg = param;
3654 if (*dir == '/' || trust) {
3655 char *pathname;
3656
3657 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3658 return (NULL);
3659
3660 pathname = arg->buffer;
3661 strncpy(pathname, dir, dirlen);
3662 pathname[dirlen] = '/';
3663 strcpy(pathname + dirlen + 1, arg->name);
3664
3665 dbg(" Trying \"%s\"", pathname);
3666 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3667 if (fd >= 0) {
3668 dbg(" Opened \"%s\", fd %d", pathname, fd);
3669 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3670 strcpy(pathname, arg->buffer);
3671 arg->fd = fd;
3672 return (pathname);
3673 } else {
3674 dbg(" Failed to open \"%s\": %s", pathname,
3675 rtld_strerror(errno));
3676 }
3677 }
3678 return (NULL);
3679 }
3680
3681 static char *
search_library_path(const char * name,const char * path,const char * refobj_path,int * fdp)3682 search_library_path(const char *name, const char *path, const char *refobj_path,
3683 int *fdp)
3684 {
3685 char *p;
3686 struct try_library_args arg;
3687
3688 if (path == NULL)
3689 return (NULL);
3690
3691 arg.name = name;
3692 arg.namelen = strlen(name);
3693 arg.buffer = xmalloc(PATH_MAX);
3694 arg.buflen = PATH_MAX;
3695 arg.fd = -1;
3696
3697 p = path_enumerate(path, try_library_path, refobj_path, &arg);
3698 *fdp = arg.fd;
3699
3700 free(arg.buffer);
3701
3702 return (p);
3703 }
3704
3705 /*
3706 * Finds the library with the given name using the directory descriptors
3707 * listed in the LD_LIBRARY_PATH_FDS environment variable.
3708 *
3709 * Returns a freshly-opened close-on-exec file descriptor for the library,
3710 * or -1 if the library cannot be found.
3711 */
3712 static char *
search_library_pathfds(const char * name,const char * path,int * fdp)3713 search_library_pathfds(const char *name, const char *path, int *fdp)
3714 {
3715 char *envcopy, *fdstr, *found, *last_token;
3716 size_t len;
3717 int dirfd, fd;
3718
3719 dbg("%s('%s', '%s', fdp)", __func__, name, path);
3720
3721 /* Don't load from user-specified libdirs into setuid binaries. */
3722 if (!trust)
3723 return (NULL);
3724
3725 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3726 if (path == NULL)
3727 return (NULL);
3728
3729 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3730 if (name[0] == '/') {
3731 dbg("Absolute path (%s) passed to %s", name, __func__);
3732 return (NULL);
3733 }
3734
3735 /*
3736 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
3737 * copy of the path, as strtok_r rewrites separator tokens
3738 * with '\0'.
3739 */
3740 found = NULL;
3741 envcopy = xstrdup(path);
3742 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3743 fdstr = strtok_r(NULL, ":", &last_token)) {
3744 dirfd = parse_integer(fdstr);
3745 if (dirfd < 0) {
3746 _rtld_error("failed to parse directory FD: '%s'",
3747 fdstr);
3748 break;
3749 }
3750 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3751 if (fd >= 0) {
3752 *fdp = fd;
3753 len = strlen(fdstr) + strlen(name) + 3;
3754 found = xmalloc(len);
3755 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) <
3756 0) {
3757 _rtld_error("error generating '%d/%s'", dirfd,
3758 name);
3759 rtld_die();
3760 }
3761 dbg("open('%s') => %d", found, fd);
3762 break;
3763 }
3764 }
3765 free(envcopy);
3766
3767 return (found);
3768 }
3769
3770 int
dlclose(void * handle)3771 dlclose(void *handle)
3772 {
3773 RtldLockState lockstate;
3774 int error;
3775
3776 wlock_acquire(rtld_bind_lock, &lockstate);
3777 error = dlclose_locked(handle, &lockstate);
3778 lock_release(rtld_bind_lock, &lockstate);
3779 return (error);
3780 }
3781
3782 static int
dlclose_locked(void * handle,RtldLockState * lockstate)3783 dlclose_locked(void *handle, RtldLockState *lockstate)
3784 {
3785 Obj_Entry *root;
3786
3787 root = dlcheck(handle);
3788 if (root == NULL)
3789 return (-1);
3790 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3791 root->path);
3792
3793 /* Unreference the object and its dependencies. */
3794 root->dl_refcount--;
3795
3796 if (root->refcount == 1) {
3797 /*
3798 * The object will be no longer referenced, so we must unload
3799 * it. First, call the fini functions.
3800 */
3801 objlist_call_fini(&list_fini, root, lockstate);
3802
3803 unref_dag(root);
3804
3805 /* Finish cleaning up the newly-unreferenced objects. */
3806 GDB_STATE(RT_DELETE, &root->linkmap);
3807 unload_object(root, lockstate);
3808 GDB_STATE(RT_CONSISTENT, NULL);
3809 } else
3810 unref_dag(root);
3811
3812 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3813 return (0);
3814 }
3815
3816 char *
dlerror(void)3817 dlerror(void)
3818 {
3819 if (*(lockinfo.dlerror_seen()) != 0)
3820 return (NULL);
3821 *lockinfo.dlerror_seen() = 1;
3822 return (lockinfo.dlerror_loc());
3823 }
3824
3825 /*
3826 * This function is deprecated and has no effect.
3827 */
3828 void
dllockinit(void * context,void * (* _lock_create)(void * context)__unused,void (* _rlock_acquire)(void * lock)__unused,void (* _wlock_acquire)(void * lock)__unused,void (* _lock_release)(void * lock)__unused,void (* _lock_destroy)(void * lock)__unused,void (* context_destroy)(void * context))3829 dllockinit(void *context, void *(*_lock_create)(void *context)__unused,
3830 void (*_rlock_acquire)(void *lock) __unused,
3831 void (*_wlock_acquire)(void *lock) __unused,
3832 void (*_lock_release)(void *lock) __unused,
3833 void (*_lock_destroy)(void *lock) __unused,
3834 void (*context_destroy)(void *context))
3835 {
3836 static void *cur_context;
3837 static void (*cur_context_destroy)(void *);
3838
3839 /* Just destroy the context from the previous call, if necessary. */
3840 if (cur_context_destroy != NULL)
3841 cur_context_destroy(cur_context);
3842 cur_context = context;
3843 cur_context_destroy = context_destroy;
3844 }
3845
3846 void *
dlopen(const char * name,int mode)3847 dlopen(const char *name, int mode)
3848 {
3849 return (rtld_dlopen(name, -1, mode));
3850 }
3851
3852 void *
fdlopen(int fd,int mode)3853 fdlopen(int fd, int mode)
3854 {
3855 return (rtld_dlopen(NULL, fd, mode));
3856 }
3857
3858 static void *
rtld_dlopen(const char * name,int fd,int mode)3859 rtld_dlopen(const char *name, int fd, int mode)
3860 {
3861 RtldLockState lockstate;
3862 int lo_flags;
3863
3864 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3865 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3866 if (ld_tracing != NULL) {
3867 rlock_acquire(rtld_bind_lock, &lockstate);
3868 if (sigsetjmp(lockstate.env, 0) != 0)
3869 lock_upgrade(rtld_bind_lock, &lockstate);
3870 environ = __DECONST(char **,
3871 *get_program_var_addr("environ", &lockstate));
3872 lock_release(rtld_bind_lock, &lockstate);
3873 }
3874 lo_flags = RTLD_LO_DLOPEN;
3875 if (mode & RTLD_NODELETE)
3876 lo_flags |= RTLD_LO_NODELETE;
3877 if (mode & RTLD_NOLOAD)
3878 lo_flags |= RTLD_LO_NOLOAD;
3879 if (mode & RTLD_DEEPBIND)
3880 lo_flags |= RTLD_LO_DEEPBIND;
3881 if (ld_tracing != NULL)
3882 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3883
3884 return (dlopen_object(name, fd, obj_main, lo_flags,
3885 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3886 }
3887
3888 static void
dlopen_cleanup(Obj_Entry * obj,RtldLockState * lockstate)3889 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3890 {
3891 obj->dl_refcount--;
3892 unref_dag(obj);
3893 if (obj->refcount == 0)
3894 unload_object(obj, lockstate);
3895 }
3896
3897 static Obj_Entry *
dlopen_object(const char * name,int fd,Obj_Entry * refobj,int lo_flags,int mode,RtldLockState * lockstate)3898 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3899 int mode, RtldLockState *lockstate)
3900 {
3901 Obj_Entry *obj;
3902 Objlist initlist;
3903 RtldLockState mlockstate;
3904 int result;
3905
3906 dbg(
3907 "dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3908 name != NULL ? name : "<null>", fd,
3909 refobj == NULL ? "<null>" : refobj->path, lo_flags, mode);
3910 objlist_init(&initlist);
3911
3912 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3913 wlock_acquire(rtld_bind_lock, &mlockstate);
3914 lockstate = &mlockstate;
3915 }
3916 GDB_STATE(RT_ADD, NULL);
3917
3918 obj = NULL;
3919 if (name == NULL && fd == -1) {
3920 obj = obj_main;
3921 obj->refcount++;
3922 } else {
3923 obj = load_object(name, fd, refobj, lo_flags);
3924 }
3925
3926 if (obj != NULL) {
3927 obj->dl_refcount++;
3928 if ((mode & RTLD_GLOBAL) != 0 &&
3929 objlist_find(&list_global, obj) == NULL)
3930 objlist_push_tail(&list_global, obj);
3931
3932 if (!obj->init_done) {
3933 /* We loaded something new and have to init something.
3934 */
3935 if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3936 obj->deepbind = true;
3937 result = 0;
3938 if ((lo_flags & (RTLD_LO_EARLY |
3939 RTLD_LO_IGNSTLS)) == 0 &&
3940 obj->static_tls && !allocate_tls_offset(obj)) {
3941 _rtld_error(
3942 "%s: No space available for static Thread Local Storage",
3943 obj->path);
3944 result = -1;
3945 }
3946 if (result != -1)
3947 result = load_needed_objects(obj,
3948 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY |
3949 RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3950 init_dag(obj);
3951 ref_dag(obj);
3952 if (result != -1)
3953 result = rtld_verify_versions(&obj->dagmembers);
3954 if (result != -1 && ld_tracing)
3955 goto trace;
3956 if (result == -1 || relocate_object_dag(obj,
3957 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3958 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3959 lockstate) == -1) {
3960 dlopen_cleanup(obj, lockstate);
3961 obj = NULL;
3962 } else if ((lo_flags & RTLD_LO_EARLY) != 0) {
3963 /*
3964 * Do not call the init functions for early
3965 * loaded filtees. The image is still not
3966 * initialized enough for them to work.
3967 *
3968 * Our object is found by the global object list
3969 * and will be ordered among all init calls done
3970 * right before transferring control to main.
3971 */
3972 } else {
3973 /* Make list of init functions to call. */
3974 initlist_for_loaded_obj(obj, obj, &initlist);
3975 }
3976 /*
3977 * Process all no_delete or global objects here, given
3978 * them own DAGs to prevent their dependencies from
3979 * being unloaded. This has to be done after we have
3980 * loaded all of the dependencies, so that we do not
3981 * miss any.
3982 */
3983 if (obj != NULL)
3984 process_z(obj);
3985 } else {
3986 /*
3987 * Bump the reference counts for objects on this DAG. If
3988 * this is the first dlopen() call for the object that
3989 * was already loaded as a dependency, initialize the
3990 * dag starting at it.
3991 */
3992 init_dag(obj);
3993 ref_dag(obj);
3994
3995 if ((lo_flags & RTLD_LO_TRACE) != 0)
3996 goto trace;
3997 }
3998 if (obj != NULL &&
3999 ((lo_flags & RTLD_LO_NODELETE) != 0 || obj->z_nodelete) &&
4000 !obj->ref_nodel) {
4001 dbg("obj %s nodelete", obj->path);
4002 ref_dag(obj);
4003 obj->z_nodelete = obj->ref_nodel = true;
4004 }
4005 }
4006
4007 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
4008 name);
4009 GDB_STATE(RT_CONSISTENT, obj ? &obj->linkmap : NULL);
4010
4011 if ((lo_flags & RTLD_LO_EARLY) == 0) {
4012 map_stacks_exec(lockstate);
4013 if (obj != NULL)
4014 distribute_static_tls(&initlist);
4015 }
4016
4017 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) ==
4018 RTLD_NOW, (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
4019 lockstate) == -1) {
4020 objlist_clear(&initlist);
4021 dlopen_cleanup(obj, lockstate);
4022 if (lockstate == &mlockstate)
4023 lock_release(rtld_bind_lock, lockstate);
4024 return (NULL);
4025 }
4026
4027 if ((lo_flags & RTLD_LO_EARLY) == 0) {
4028 /* Call the init functions. */
4029 objlist_call_init(&initlist, lockstate);
4030 }
4031 objlist_clear(&initlist);
4032 if (lockstate == &mlockstate)
4033 lock_release(rtld_bind_lock, lockstate);
4034 return (obj);
4035 trace:
4036 trace_loaded_objects(obj, false);
4037 if (lockstate == &mlockstate)
4038 lock_release(rtld_bind_lock, lockstate);
4039 exit(0);
4040 }
4041
4042 static void *
do_dlsym(void * handle,const char * name,void * retaddr,const Ver_Entry * ve,int flags)4043 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
4044 int flags)
4045 {
4046 DoneList donelist;
4047 const Obj_Entry *obj, *defobj;
4048 const Elf_Sym *def;
4049 SymLook req;
4050 RtldLockState lockstate;
4051 tls_index ti;
4052 void *sym;
4053 int res;
4054
4055 def = NULL;
4056 defobj = NULL;
4057 symlook_init(&req, name);
4058 req.ventry = ve;
4059 req.flags = flags | SYMLOOK_IN_PLT;
4060 req.lockstate = &lockstate;
4061
4062 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
4063 rlock_acquire(rtld_bind_lock, &lockstate);
4064 if (sigsetjmp(lockstate.env, 0) != 0)
4065 lock_upgrade(rtld_bind_lock, &lockstate);
4066 if (handle == NULL || handle == RTLD_NEXT || handle == RTLD_DEFAULT ||
4067 handle == RTLD_SELF) {
4068 if ((obj = obj_from_addr(retaddr)) == NULL) {
4069 _rtld_error("Cannot determine caller's shared object");
4070 lock_release(rtld_bind_lock, &lockstate);
4071 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
4072 return (NULL);
4073 }
4074 if (handle == NULL) { /* Just the caller's shared object. */
4075 res = symlook_obj(&req, obj);
4076 if (res == 0) {
4077 def = req.sym_out;
4078 defobj = req.defobj_out;
4079 }
4080 } else if (handle == RTLD_NEXT || /* Objects after caller's */
4081 handle == RTLD_SELF) { /* ... caller included */
4082 if (handle == RTLD_NEXT)
4083 obj = globallist_next(obj);
4084 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4085 if (obj->marker)
4086 continue;
4087 res = symlook_obj(&req, obj);
4088 if (res == 0) {
4089 if (def == NULL ||
4090 (ld_dynamic_weak &&
4091 ELF_ST_BIND(
4092 req.sym_out->st_info) !=
4093 STB_WEAK)) {
4094 def = req.sym_out;
4095 defobj = req.defobj_out;
4096 if (!ld_dynamic_weak ||
4097 ELF_ST_BIND(def->st_info) !=
4098 STB_WEAK)
4099 break;
4100 }
4101 }
4102 }
4103 /*
4104 * Search the dynamic linker itself, and possibly
4105 * resolve the symbol from there. This is how the
4106 * application links to dynamic linker services such as
4107 * dlopen. Note that we ignore ld_dynamic_weak == false
4108 * case, always overriding weak symbols by rtld
4109 * definitions.
4110 */
4111 if (def == NULL ||
4112 ELF_ST_BIND(def->st_info) == STB_WEAK) {
4113 res = symlook_obj(&req, &obj_rtld);
4114 if (res == 0) {
4115 def = req.sym_out;
4116 defobj = req.defobj_out;
4117 }
4118 }
4119 } else {
4120 assert(handle == RTLD_DEFAULT);
4121 res = symlook_default(&req, obj);
4122 if (res == 0) {
4123 defobj = req.defobj_out;
4124 def = req.sym_out;
4125 }
4126 }
4127 } else {
4128 if ((obj = dlcheck(handle)) == NULL) {
4129 lock_release(rtld_bind_lock, &lockstate);
4130 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
4131 return (NULL);
4132 }
4133
4134 donelist_init(&donelist);
4135 if (obj->mainprog) {
4136 /* Handle obtained by dlopen(NULL, ...) implies global
4137 * scope. */
4138 res = symlook_global(&req, &donelist);
4139 if (res == 0) {
4140 def = req.sym_out;
4141 defobj = req.defobj_out;
4142 }
4143 /*
4144 * Search the dynamic linker itself, and possibly
4145 * resolve the symbol from there. This is how the
4146 * application links to dynamic linker services such as
4147 * dlopen.
4148 */
4149 if (def == NULL ||
4150 ELF_ST_BIND(def->st_info) == STB_WEAK) {
4151 res = symlook_obj(&req, &obj_rtld);
4152 if (res == 0) {
4153 def = req.sym_out;
4154 defobj = req.defobj_out;
4155 }
4156 }
4157 } else {
4158 /* Search the whole DAG rooted at the given object. */
4159 res = symlook_list(&req, &obj->dagmembers, &donelist);
4160 if (res == 0) {
4161 def = req.sym_out;
4162 defobj = req.defobj_out;
4163 }
4164 }
4165 }
4166
4167 if (def != NULL) {
4168 lock_release(rtld_bind_lock, &lockstate);
4169
4170 /*
4171 * The value required by the caller is derived from the value
4172 * of the symbol. this is simply the relocated value of the
4173 * symbol.
4174 */
4175 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
4176 sym = make_function_pointer(def, defobj);
4177 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
4178 sym = rtld_resolve_ifunc(defobj, def);
4179 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
4180 ti.ti_module = defobj->tlsindex;
4181 ti.ti_offset = def->st_value - TLS_DTV_OFFSET;
4182 sym = __tls_get_addr(&ti);
4183 } else
4184 sym = defobj->relocbase + def->st_value;
4185 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
4186 return (sym);
4187 }
4188
4189 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
4190 ve != NULL ? ve->name : "");
4191 lock_release(rtld_bind_lock, &lockstate);
4192 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
4193 return (NULL);
4194 }
4195
4196 void *
dlsym(void * handle,const char * name)4197 dlsym(void *handle, const char *name)
4198 {
4199 return (do_dlsym(handle, name, __builtin_return_address(0), NULL,
4200 SYMLOOK_DLSYM));
4201 }
4202
4203 dlfunc_t
dlfunc(void * handle,const char * name)4204 dlfunc(void *handle, const char *name)
4205 {
4206 union {
4207 void *d;
4208 dlfunc_t f;
4209 } rv;
4210
4211 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
4212 SYMLOOK_DLSYM);
4213 return (rv.f);
4214 }
4215
4216 void *
dlvsym(void * handle,const char * name,const char * version)4217 dlvsym(void *handle, const char *name, const char *version)
4218 {
4219 Ver_Entry ventry;
4220
4221 ventry.name = version;
4222 ventry.file = NULL;
4223 ventry.hash = elf_hash(version);
4224 ventry.flags = 0;
4225 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry,
4226 SYMLOOK_DLSYM));
4227 }
4228
4229 int
_rtld_addr_phdr(const void * addr,struct dl_phdr_info * phdr_info)4230 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
4231 {
4232 const Obj_Entry *obj;
4233 RtldLockState lockstate;
4234
4235 rlock_acquire(rtld_bind_lock, &lockstate);
4236 obj = obj_from_addr(addr);
4237 if (obj == NULL) {
4238 _rtld_error("No shared object contains address");
4239 lock_release(rtld_bind_lock, &lockstate);
4240 return (0);
4241 }
4242 rtld_fill_dl_phdr_info(obj, phdr_info);
4243 lock_release(rtld_bind_lock, &lockstate);
4244 return (1);
4245 }
4246
4247 int
dladdr(const void * addr,Dl_info * info)4248 dladdr(const void *addr, Dl_info *info)
4249 {
4250 const Obj_Entry *obj;
4251 const Elf_Sym *def;
4252 void *symbol_addr;
4253 unsigned long symoffset;
4254 RtldLockState lockstate;
4255
4256 rlock_acquire(rtld_bind_lock, &lockstate);
4257 obj = obj_from_addr(addr);
4258 if (obj == NULL) {
4259 _rtld_error("No shared object contains address");
4260 lock_release(rtld_bind_lock, &lockstate);
4261 return (0);
4262 }
4263 info->dli_fname = obj->path;
4264 info->dli_fbase = obj->mapbase;
4265 info->dli_saddr = (void *)0;
4266 info->dli_sname = NULL;
4267
4268 /*
4269 * Walk the symbol list looking for the symbol whose address is
4270 * closest to the address sent in.
4271 */
4272 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
4273 def = obj->symtab + symoffset;
4274
4275 /*
4276 * For skip the symbol if st_shndx is either SHN_UNDEF or
4277 * SHN_COMMON.
4278 */
4279 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
4280 continue;
4281
4282 /*
4283 * If the symbol is greater than the specified address, or if it
4284 * is further away from addr than the current nearest symbol,
4285 * then reject it.
4286 */
4287 symbol_addr = obj->relocbase + def->st_value;
4288 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
4289 continue;
4290
4291 /* Update our idea of the nearest symbol. */
4292 info->dli_sname = obj->strtab + def->st_name;
4293 info->dli_saddr = symbol_addr;
4294
4295 /* Exact match? */
4296 if (info->dli_saddr == addr)
4297 break;
4298 }
4299 lock_release(rtld_bind_lock, &lockstate);
4300 return (1);
4301 }
4302
4303 int
dlinfo(void * handle,int request,void * p)4304 dlinfo(void *handle, int request, void *p)
4305 {
4306 const Obj_Entry *obj;
4307 RtldLockState lockstate;
4308 int error;
4309
4310 rlock_acquire(rtld_bind_lock, &lockstate);
4311
4312 if (handle == NULL || handle == RTLD_SELF) {
4313 void *retaddr;
4314
4315 retaddr = __builtin_return_address(0); /* __GNUC__ only */
4316 if ((obj = obj_from_addr(retaddr)) == NULL)
4317 _rtld_error("Cannot determine caller's shared object");
4318 } else
4319 obj = dlcheck(handle);
4320
4321 if (obj == NULL) {
4322 lock_release(rtld_bind_lock, &lockstate);
4323 return (-1);
4324 }
4325
4326 error = 0;
4327 switch (request) {
4328 case RTLD_DI_LINKMAP:
4329 *((struct link_map const **)p) = &obj->linkmap;
4330 break;
4331 case RTLD_DI_ORIGIN:
4332 error = rtld_dirname(obj->path, p);
4333 break;
4334
4335 case RTLD_DI_SERINFOSIZE:
4336 case RTLD_DI_SERINFO:
4337 error = do_search_info(obj, request, (struct dl_serinfo *)p);
4338 break;
4339
4340 default:
4341 _rtld_error("Invalid request %d passed to dlinfo()", request);
4342 error = -1;
4343 }
4344
4345 lock_release(rtld_bind_lock, &lockstate);
4346
4347 return (error);
4348 }
4349
4350 static void
rtld_fill_dl_phdr_info(const Obj_Entry * obj,struct dl_phdr_info * phdr_info)4351 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4352 {
4353 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4354 phdr_info->dlpi_name = obj->path;
4355 phdr_info->dlpi_phdr = obj->phdr;
4356 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4357 phdr_info->dlpi_tls_modid = obj->tlsindex;
4358 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(_tcb_get(),
4359 obj->tlsindex, 0, true);
4360 phdr_info->dlpi_adds = obj_loads;
4361 phdr_info->dlpi_subs = obj_loads - obj_count;
4362 }
4363
4364 /*
4365 * It's completely UB to actually use this, so extreme caution is advised. It's
4366 * probably not what you want.
4367 */
4368 int
_dl_iterate_phdr_locked(__dl_iterate_hdr_callback callback,void * param)4369 _dl_iterate_phdr_locked(__dl_iterate_hdr_callback callback, void *param)
4370 {
4371 struct dl_phdr_info phdr_info;
4372 Obj_Entry *obj;
4373 int error;
4374
4375 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;
4376 obj = globallist_next(obj)) {
4377 rtld_fill_dl_phdr_info(obj, &phdr_info);
4378 error = callback(&phdr_info, sizeof(phdr_info), param);
4379 if (error != 0)
4380 return (error);
4381 }
4382
4383 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4384 return (callback(&phdr_info, sizeof(phdr_info), param));
4385 }
4386
4387 int
dl_iterate_phdr(__dl_iterate_hdr_callback callback,void * param)4388 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4389 {
4390 struct dl_phdr_info phdr_info;
4391 Obj_Entry *obj, marker;
4392 RtldLockState bind_lockstate, phdr_lockstate;
4393 int error;
4394
4395 init_marker(&marker);
4396 error = 0;
4397
4398 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4399 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4400 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4401 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4402 rtld_fill_dl_phdr_info(obj, &phdr_info);
4403 hold_object(obj);
4404 lock_release(rtld_bind_lock, &bind_lockstate);
4405
4406 error = callback(&phdr_info, sizeof phdr_info, param);
4407
4408 wlock_acquire(rtld_bind_lock, &bind_lockstate);
4409 unhold_object(obj);
4410 obj = globallist_next(&marker);
4411 TAILQ_REMOVE(&obj_list, &marker, next);
4412 if (error != 0) {
4413 lock_release(rtld_bind_lock, &bind_lockstate);
4414 lock_release(rtld_phdr_lock, &phdr_lockstate);
4415 return (error);
4416 }
4417 }
4418
4419 if (error == 0) {
4420 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4421 lock_release(rtld_bind_lock, &bind_lockstate);
4422 error = callback(&phdr_info, sizeof(phdr_info), param);
4423 }
4424 lock_release(rtld_phdr_lock, &phdr_lockstate);
4425 return (error);
4426 }
4427
4428 static void *
fill_search_info(const char * dir,size_t dirlen,void * param)4429 fill_search_info(const char *dir, size_t dirlen, void *param)
4430 {
4431 struct fill_search_info_args *arg;
4432
4433 arg = param;
4434
4435 if (arg->request == RTLD_DI_SERINFOSIZE) {
4436 arg->serinfo->dls_cnt++;
4437 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen +
4438 1;
4439 } else {
4440 struct dl_serpath *s_entry;
4441
4442 s_entry = arg->serpath;
4443 s_entry->dls_name = arg->strspace;
4444 s_entry->dls_flags = arg->flags;
4445
4446 strncpy(arg->strspace, dir, dirlen);
4447 arg->strspace[dirlen] = '\0';
4448
4449 arg->strspace += dirlen + 1;
4450 arg->serpath++;
4451 }
4452
4453 return (NULL);
4454 }
4455
4456 static int
do_search_info(const Obj_Entry * obj,int request,struct dl_serinfo * info)4457 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4458 {
4459 struct dl_serinfo _info;
4460 struct fill_search_info_args args;
4461
4462 args.request = RTLD_DI_SERINFOSIZE;
4463 args.serinfo = &_info;
4464
4465 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4466 _info.dls_cnt = 0;
4467
4468 path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4469 path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4470 path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4471 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL,
4472 &args);
4473 if (!obj->z_nodeflib)
4474 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
4475 &args);
4476
4477 if (request == RTLD_DI_SERINFOSIZE) {
4478 info->dls_size = _info.dls_size;
4479 info->dls_cnt = _info.dls_cnt;
4480 return (0);
4481 }
4482
4483 if (info->dls_cnt != _info.dls_cnt ||
4484 info->dls_size != _info.dls_size) {
4485 _rtld_error(
4486 "Uninitialized Dl_serinfo struct passed to dlinfo()");
4487 return (-1);
4488 }
4489
4490 args.request = RTLD_DI_SERINFO;
4491 args.serinfo = info;
4492 args.serpath = &info->dls_serpath[0];
4493 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4494
4495 args.flags = LA_SER_RUNPATH;
4496 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4497 return (-1);
4498
4499 args.flags = LA_SER_LIBPATH;
4500 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) !=
4501 NULL)
4502 return (-1);
4503
4504 args.flags = LA_SER_RUNPATH;
4505 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4506 return (-1);
4507
4508 args.flags = LA_SER_CONFIG;
4509 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL,
4510 &args) != NULL)
4511 return (-1);
4512
4513 args.flags = LA_SER_DEFAULT;
4514 if (!obj->z_nodeflib &&
4515 path_enumerate(ld_standard_library_path, fill_search_info, NULL,
4516 &args) != NULL)
4517 return (-1);
4518 return (0);
4519 }
4520
4521 static int
rtld_dirname(const char * path,char * bname)4522 rtld_dirname(const char *path, char *bname)
4523 {
4524 const char *endp;
4525
4526 /* Empty or NULL string gets treated as "." */
4527 if (path == NULL || *path == '\0') {
4528 bname[0] = '.';
4529 bname[1] = '\0';
4530 return (0);
4531 }
4532
4533 /* Strip trailing slashes */
4534 endp = path + strlen(path) - 1;
4535 while (endp > path && *endp == '/')
4536 endp--;
4537
4538 /* Find the start of the dir */
4539 while (endp > path && *endp != '/')
4540 endp--;
4541
4542 /* Either the dir is "/" or there are no slashes */
4543 if (endp == path) {
4544 bname[0] = *endp == '/' ? '/' : '.';
4545 bname[1] = '\0';
4546 return (0);
4547 } else {
4548 do {
4549 endp--;
4550 } while (endp > path && *endp == '/');
4551 }
4552
4553 if (endp - path + 2 > PATH_MAX) {
4554 _rtld_error("Filename is too long: %s", path);
4555 return (-1);
4556 }
4557
4558 strncpy(bname, path, endp - path + 1);
4559 bname[endp - path + 1] = '\0';
4560 return (0);
4561 }
4562
4563 static int
rtld_dirname_abs(const char * path,char * base)4564 rtld_dirname_abs(const char *path, char *base)
4565 {
4566 char *last;
4567
4568 if (realpath(path, base) == NULL) {
4569 _rtld_error("realpath \"%s\" failed (%s)", path,
4570 rtld_strerror(errno));
4571 return (-1);
4572 }
4573 dbg("%s -> %s", path, base);
4574 last = strrchr(base, '/');
4575 if (last == NULL) {
4576 _rtld_error("non-abs result from realpath \"%s\"", path);
4577 return (-1);
4578 }
4579 if (last != base)
4580 *last = '\0';
4581 return (0);
4582 }
4583
4584 static void
linkmap_add(Obj_Entry * obj)4585 linkmap_add(Obj_Entry *obj)
4586 {
4587 struct link_map *l, *prev;
4588
4589 l = &obj->linkmap;
4590 l->l_name = obj->path;
4591 l->l_base = obj->mapbase;
4592 l->l_ld = obj->dynamic;
4593 l->l_addr = obj->relocbase;
4594
4595 if (r_debug.r_map == NULL) {
4596 r_debug.r_map = l;
4597 return;
4598 }
4599
4600 /*
4601 * Scan to the end of the list, but not past the entry for the
4602 * dynamic linker, which we want to keep at the very end.
4603 */
4604 for (prev = r_debug.r_map;
4605 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4606 prev = prev->l_next)
4607 ;
4608
4609 /* Link in the new entry. */
4610 l->l_prev = prev;
4611 l->l_next = prev->l_next;
4612 if (l->l_next != NULL)
4613 l->l_next->l_prev = l;
4614 prev->l_next = l;
4615 }
4616
4617 static void
linkmap_delete(Obj_Entry * obj)4618 linkmap_delete(Obj_Entry *obj)
4619 {
4620 struct link_map *l;
4621
4622 l = &obj->linkmap;
4623 if (l->l_prev == NULL) {
4624 if ((r_debug.r_map = l->l_next) != NULL)
4625 l->l_next->l_prev = NULL;
4626 return;
4627 }
4628
4629 if ((l->l_prev->l_next = l->l_next) != NULL)
4630 l->l_next->l_prev = l->l_prev;
4631 }
4632
4633 /*
4634 * Function for the debugger to set a breakpoint on to gain control.
4635 *
4636 * The two parameters allow the debugger to easily find and determine
4637 * what the runtime loader is doing and to whom it is doing it.
4638 *
4639 * When the loadhook trap is hit (r_debug_state, set at program
4640 * initialization), the arguments can be found on the stack:
4641 *
4642 * +8 struct link_map *m
4643 * +4 struct r_debug *rd
4644 * +0 RetAddr
4645 */
4646 void
r_debug_state(struct r_debug * rd __unused,struct link_map * m __unused)4647 r_debug_state(struct r_debug *rd __unused, struct link_map *m __unused)
4648 {
4649 /*
4650 * The following is a hack to force the compiler to emit calls to
4651 * this function, even when optimizing. If the function is empty,
4652 * the compiler is not obliged to emit any code for calls to it,
4653 * even when marked __noinline. However, gdb depends on those
4654 * calls being made.
4655 */
4656 __compiler_membar();
4657 }
4658
4659 /*
4660 * A function called after init routines have completed. This can be used to
4661 * break before a program's entry routine is called, and can be used when
4662 * main is not available in the symbol table.
4663 */
4664 void
_r_debug_postinit(struct link_map * m __unused)4665 _r_debug_postinit(struct link_map *m __unused)
4666 {
4667 /* See r_debug_state(). */
4668 __compiler_membar();
4669 }
4670
4671 static void
release_object(Obj_Entry * obj)4672 release_object(Obj_Entry *obj)
4673 {
4674 if (obj->holdcount > 0) {
4675 obj->unholdfree = true;
4676 return;
4677 }
4678 munmap(obj->mapbase, obj->mapsize);
4679 linkmap_delete(obj);
4680 obj_free(obj);
4681 }
4682
4683 /*
4684 * Get address of the pointer variable in the main program.
4685 * Prefer non-weak symbol over the weak one.
4686 */
4687 static const void **
get_program_var_addr(const char * name,RtldLockState * lockstate)4688 get_program_var_addr(const char *name, RtldLockState *lockstate)
4689 {
4690 SymLook req;
4691 DoneList donelist;
4692
4693 symlook_init(&req, name);
4694 req.lockstate = lockstate;
4695 donelist_init(&donelist);
4696 if (symlook_global(&req, &donelist) != 0)
4697 return (NULL);
4698 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4699 return ((const void **)make_function_pointer(req.sym_out,
4700 req.defobj_out));
4701 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4702 return ((const void **)rtld_resolve_ifunc(req.defobj_out,
4703 req.sym_out));
4704 else
4705 return ((const void **)(req.defobj_out->relocbase +
4706 req.sym_out->st_value));
4707 }
4708
4709 /*
4710 * Set a pointer variable in the main program to the given value. This
4711 * is used to set key variables such as "environ" before any of the
4712 * init functions are called.
4713 */
4714 static void
set_program_var(const char * name,const void * value)4715 set_program_var(const char *name, const void *value)
4716 {
4717 const void **addr;
4718
4719 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4720 dbg("\"%s\": *%p <-- %p", name, addr, value);
4721 *addr = value;
4722 }
4723 }
4724
4725 /*
4726 * Search the global objects, including dependencies and main object,
4727 * for the given symbol.
4728 */
4729 static int
symlook_global(SymLook * req,DoneList * donelist)4730 symlook_global(SymLook *req, DoneList *donelist)
4731 {
4732 SymLook req1;
4733 const Objlist_Entry *elm;
4734 int res;
4735
4736 symlook_init_from_req(&req1, req);
4737
4738 /* Search all objects loaded at program start up. */
4739 if (req->defobj_out == NULL || (ld_dynamic_weak &&
4740 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4741 res = symlook_list(&req1, &list_main, donelist);
4742 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4743 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4744 req->sym_out = req1.sym_out;
4745 req->defobj_out = req1.defobj_out;
4746 assert(req->defobj_out != NULL);
4747 }
4748 }
4749
4750 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4751 STAILQ_FOREACH(elm, &list_global, link) {
4752 if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4753 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4754 break;
4755 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4756 if (res == 0 && (req->defobj_out == NULL ||
4757 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4758 req->sym_out = req1.sym_out;
4759 req->defobj_out = req1.defobj_out;
4760 assert(req->defobj_out != NULL);
4761 }
4762 }
4763
4764 return (req->sym_out != NULL ? 0 : ESRCH);
4765 }
4766
4767 /*
4768 * Given a symbol name in a referencing object, find the corresponding
4769 * definition of the symbol. Returns a pointer to the symbol, or NULL if
4770 * no definition was found. Returns a pointer to the Obj_Entry of the
4771 * defining object via the reference parameter DEFOBJ_OUT.
4772 */
4773 static int
symlook_default(SymLook * req,const Obj_Entry * refobj)4774 symlook_default(SymLook *req, const Obj_Entry *refobj)
4775 {
4776 DoneList donelist;
4777 const Objlist_Entry *elm;
4778 SymLook req1;
4779 int res;
4780
4781 donelist_init(&donelist);
4782 symlook_init_from_req(&req1, req);
4783
4784 /*
4785 * Look first in the referencing object if linked symbolically,
4786 * and similarly handle protected symbols.
4787 */
4788 res = symlook_obj(&req1, refobj);
4789 if (res == 0 && (refobj->symbolic ||
4790 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED ||
4791 refobj->deepbind)) {
4792 req->sym_out = req1.sym_out;
4793 req->defobj_out = req1.defobj_out;
4794 assert(req->defobj_out != NULL);
4795 }
4796 if (refobj->symbolic || req->defobj_out != NULL || refobj->deepbind)
4797 donelist_check(&donelist, refobj);
4798
4799 if (!refobj->deepbind)
4800 symlook_global(req, &donelist);
4801
4802 /* Search all dlopened DAGs containing the referencing object. */
4803 STAILQ_FOREACH(elm, &refobj->dldags, link) {
4804 if (req->sym_out != NULL && (!ld_dynamic_weak ||
4805 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4806 break;
4807 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4808 if (res == 0 && (req->sym_out == NULL ||
4809 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4810 req->sym_out = req1.sym_out;
4811 req->defobj_out = req1.defobj_out;
4812 assert(req->defobj_out != NULL);
4813 }
4814 }
4815
4816 if (refobj->deepbind)
4817 symlook_global(req, &donelist);
4818
4819 /*
4820 * Search the dynamic linker itself, and possibly resolve the
4821 * symbol from there. This is how the application links to
4822 * dynamic linker services such as dlopen.
4823 */
4824 if (req->sym_out == NULL ||
4825 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4826 res = symlook_obj(&req1, &obj_rtld);
4827 if (res == 0) {
4828 req->sym_out = req1.sym_out;
4829 req->defobj_out = req1.defobj_out;
4830 assert(req->defobj_out != NULL);
4831 }
4832 }
4833
4834 return (req->sym_out != NULL ? 0 : ESRCH);
4835 }
4836
4837 static int
symlook_list(SymLook * req,const Objlist * objlist,DoneList * dlp)4838 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4839 {
4840 const Elf_Sym *def;
4841 const Obj_Entry *defobj;
4842 const Objlist_Entry *elm;
4843 SymLook req1;
4844 int res;
4845
4846 def = NULL;
4847 defobj = NULL;
4848 STAILQ_FOREACH(elm, objlist, link) {
4849 if (donelist_check(dlp, elm->obj))
4850 continue;
4851 symlook_init_from_req(&req1, req);
4852 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4853 if (def == NULL || (ld_dynamic_weak &&
4854 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4855 def = req1.sym_out;
4856 defobj = req1.defobj_out;
4857 if (!ld_dynamic_weak ||
4858 ELF_ST_BIND(def->st_info) != STB_WEAK)
4859 break;
4860 }
4861 }
4862 }
4863 if (def != NULL) {
4864 req->sym_out = def;
4865 req->defobj_out = defobj;
4866 return (0);
4867 }
4868 return (ESRCH);
4869 }
4870
4871 /*
4872 * Search the chain of DAGS cointed to by the given Needed_Entry
4873 * for a symbol of the given name. Each DAG is scanned completely
4874 * before advancing to the next one. Returns a pointer to the symbol,
4875 * or NULL if no definition was found.
4876 */
4877 static int
symlook_needed(SymLook * req,const Needed_Entry * needed,DoneList * dlp)4878 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4879 {
4880 const Elf_Sym *def;
4881 const Needed_Entry *n;
4882 const Obj_Entry *defobj;
4883 SymLook req1;
4884 int res;
4885
4886 def = NULL;
4887 defobj = NULL;
4888 symlook_init_from_req(&req1, req);
4889 for (n = needed; n != NULL; n = n->next) {
4890 if (n->obj == NULL || (res = symlook_list(&req1,
4891 &n->obj->dagmembers, dlp)) != 0)
4892 continue;
4893 if (def == NULL || (ld_dynamic_weak &&
4894 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4895 def = req1.sym_out;
4896 defobj = req1.defobj_out;
4897 if (!ld_dynamic_weak ||
4898 ELF_ST_BIND(def->st_info) != STB_WEAK)
4899 break;
4900 }
4901 }
4902 if (def != NULL) {
4903 req->sym_out = def;
4904 req->defobj_out = defobj;
4905 return (0);
4906 }
4907 return (ESRCH);
4908 }
4909
4910 static int
symlook_obj_load_filtees(SymLook * req,SymLook * req1,const Obj_Entry * obj,Needed_Entry * needed)4911 symlook_obj_load_filtees(SymLook *req, SymLook *req1, const Obj_Entry *obj,
4912 Needed_Entry *needed)
4913 {
4914 DoneList donelist;
4915 int flags;
4916
4917 flags = (req->flags & SYMLOOK_EARLY) != 0 ? RTLD_LO_EARLY : 0;
4918 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4919 donelist_init(&donelist);
4920 symlook_init_from_req(req1, req);
4921 return (symlook_needed(req1, needed, &donelist));
4922 }
4923
4924 /*
4925 * Search the symbol table of a single shared object for a symbol of
4926 * the given name and version, if requested. Returns a pointer to the
4927 * symbol, or NULL if no definition was found. If the object is
4928 * filter, return filtered symbol from filtee.
4929 *
4930 * The symbol's hash value is passed in for efficiency reasons; that
4931 * eliminates many recomputations of the hash value.
4932 */
4933 int
symlook_obj(SymLook * req,const Obj_Entry * obj)4934 symlook_obj(SymLook *req, const Obj_Entry *obj)
4935 {
4936 SymLook req1;
4937 int res, mres;
4938
4939 /*
4940 * If there is at least one valid hash at this point, we prefer to
4941 * use the faster GNU version if available.
4942 */
4943 if (obj->valid_hash_gnu)
4944 mres = symlook_obj1_gnu(req, obj);
4945 else if (obj->valid_hash_sysv)
4946 mres = symlook_obj1_sysv(req, obj);
4947 else
4948 return (EINVAL);
4949
4950 if (mres == 0) {
4951 if (obj->needed_filtees != NULL) {
4952 res = symlook_obj_load_filtees(req, &req1, obj,
4953 obj->needed_filtees);
4954 if (res == 0) {
4955 req->sym_out = req1.sym_out;
4956 req->defobj_out = req1.defobj_out;
4957 }
4958 return (res);
4959 }
4960 if (obj->needed_aux_filtees != NULL) {
4961 res = symlook_obj_load_filtees(req, &req1, obj,
4962 obj->needed_aux_filtees);
4963 if (res == 0) {
4964 req->sym_out = req1.sym_out;
4965 req->defobj_out = req1.defobj_out;
4966 return (res);
4967 }
4968 }
4969 }
4970 return (mres);
4971 }
4972
4973 /* Symbol match routine common to both hash functions */
4974 static bool
matched_symbol(SymLook * req,const Obj_Entry * obj,Sym_Match_Result * result,const unsigned long symnum)4975 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4976 const unsigned long symnum)
4977 {
4978 Elf_Versym verndx;
4979 const Elf_Sym *symp;
4980 const char *strp;
4981
4982 symp = obj->symtab + symnum;
4983 strp = obj->strtab + symp->st_name;
4984
4985 switch (ELF_ST_TYPE(symp->st_info)) {
4986 case STT_FUNC:
4987 case STT_NOTYPE:
4988 case STT_OBJECT:
4989 case STT_COMMON:
4990 case STT_GNU_IFUNC:
4991 if (symp->st_value == 0)
4992 return (false);
4993 /* fallthrough */
4994 case STT_TLS:
4995 if (symp->st_shndx != SHN_UNDEF)
4996 break;
4997 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4998 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4999 break;
5000 /* fallthrough */
5001 default:
5002 return (false);
5003 }
5004 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
5005 return (false);
5006
5007 if (req->ventry == NULL) {
5008 if (obj->versyms != NULL) {
5009 verndx = VER_NDX(obj->versyms[symnum]);
5010 if (verndx > obj->vernum) {
5011 _rtld_error(
5012 "%s: symbol %s references wrong version %d",
5013 obj->path, obj->strtab + symnum, verndx);
5014 return (false);
5015 }
5016 /*
5017 * If we are not called from dlsym (i.e. this
5018 * is a normal relocation from unversioned
5019 * binary), accept the symbol immediately if
5020 * it happens to have first version after this
5021 * shared object became versioned. Otherwise,
5022 * if symbol is versioned and not hidden,
5023 * remember it. If it is the only symbol with
5024 * this name exported by the shared object, it
5025 * will be returned as a match by the calling
5026 * function. If symbol is global (verndx < 2)
5027 * accept it unconditionally.
5028 */
5029 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
5030 verndx == VER_NDX_GIVEN) {
5031 result->sym_out = symp;
5032 return (true);
5033 } else if (verndx >= VER_NDX_GIVEN) {
5034 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) ==
5035 0) {
5036 if (result->vsymp == NULL)
5037 result->vsymp = symp;
5038 result->vcount++;
5039 }
5040 return (false);
5041 }
5042 }
5043 result->sym_out = symp;
5044 return (true);
5045 }
5046 if (obj->versyms == NULL) {
5047 if (object_match_name(obj, req->ventry->name)) {
5048 _rtld_error(
5049 "%s: object %s should provide version %s for symbol %s",
5050 obj_rtld.path, obj->path, req->ventry->name,
5051 obj->strtab + symnum);
5052 return (false);
5053 }
5054 } else {
5055 verndx = VER_NDX(obj->versyms[symnum]);
5056 if (verndx > obj->vernum) {
5057 _rtld_error("%s: symbol %s references wrong version %d",
5058 obj->path, obj->strtab + symnum, verndx);
5059 return (false);
5060 }
5061 if (obj->vertab[verndx].hash != req->ventry->hash ||
5062 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
5063 /*
5064 * Version does not match. Look if this is a
5065 * global symbol and if it is not hidden. If
5066 * global symbol (verndx < 2) is available,
5067 * use it. Do not return symbol if we are
5068 * called by dlvsym, because dlvsym looks for
5069 * a specific version and default one is not
5070 * what dlvsym wants.
5071 */
5072 if ((req->flags & SYMLOOK_DLSYM) ||
5073 (verndx >= VER_NDX_GIVEN) ||
5074 (obj->versyms[symnum] & VER_NDX_HIDDEN))
5075 return (false);
5076 }
5077 }
5078 result->sym_out = symp;
5079 return (true);
5080 }
5081
5082 /*
5083 * Search for symbol using SysV hash function.
5084 * obj->buckets is known not to be NULL at this point; the test for this was
5085 * performed with the obj->valid_hash_sysv assignment.
5086 */
5087 static int
symlook_obj1_sysv(SymLook * req,const Obj_Entry * obj)5088 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
5089 {
5090 unsigned long symnum;
5091 Sym_Match_Result matchres;
5092
5093 matchres.sym_out = NULL;
5094 matchres.vsymp = NULL;
5095 matchres.vcount = 0;
5096
5097 for (symnum = obj->buckets[req->hash % obj->nbuckets];
5098 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
5099 if (symnum >= obj->nchains)
5100 return (ESRCH); /* Bad object */
5101
5102 if (matched_symbol(req, obj, &matchres, symnum)) {
5103 req->sym_out = matchres.sym_out;
5104 req->defobj_out = obj;
5105 return (0);
5106 }
5107 }
5108 if (matchres.vcount == 1) {
5109 req->sym_out = matchres.vsymp;
5110 req->defobj_out = obj;
5111 return (0);
5112 }
5113 return (ESRCH);
5114 }
5115
5116 /* Search for symbol using GNU hash function */
5117 static int
symlook_obj1_gnu(SymLook * req,const Obj_Entry * obj)5118 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
5119 {
5120 Elf_Addr bloom_word;
5121 const Elf32_Word *hashval;
5122 Elf32_Word bucket;
5123 Sym_Match_Result matchres;
5124 unsigned int h1, h2;
5125 unsigned long symnum;
5126
5127 matchres.sym_out = NULL;
5128 matchres.vsymp = NULL;
5129 matchres.vcount = 0;
5130
5131 /* Pick right bitmask word from Bloom filter array */
5132 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
5133 obj->maskwords_bm_gnu];
5134
5135 /* Calculate modulus word size of gnu hash and its derivative */
5136 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
5137 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
5138
5139 /* Filter out the "definitely not in set" queries */
5140 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
5141 return (ESRCH);
5142
5143 /* Locate hash chain and corresponding value element*/
5144 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
5145 if (bucket == 0)
5146 return (ESRCH);
5147 hashval = &obj->chain_zero_gnu[bucket];
5148 do {
5149 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
5150 symnum = hashval - obj->chain_zero_gnu;
5151 if (matched_symbol(req, obj, &matchres, symnum)) {
5152 req->sym_out = matchres.sym_out;
5153 req->defobj_out = obj;
5154 return (0);
5155 }
5156 }
5157 } while ((*hashval++ & 1) == 0);
5158 if (matchres.vcount == 1) {
5159 req->sym_out = matchres.vsymp;
5160 req->defobj_out = obj;
5161 return (0);
5162 }
5163 return (ESRCH);
5164 }
5165
5166 static void
trace_calc_fmts(const char ** main_local,const char ** fmt1,const char ** fmt2)5167 trace_calc_fmts(const char **main_local, const char **fmt1, const char **fmt2)
5168 {
5169 *main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME);
5170 if (*main_local == NULL)
5171 *main_local = "";
5172
5173 *fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1);
5174 if (*fmt1 == NULL)
5175 *fmt1 = "\t%o => %p (%x)\n";
5176
5177 *fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2);
5178 if (*fmt2 == NULL)
5179 *fmt2 = "\t%o (%x)\n";
5180 }
5181
5182 static void
trace_print_obj(Obj_Entry * obj,const char * name,const char * path,const char * main_local,const char * fmt1,const char * fmt2)5183 trace_print_obj(Obj_Entry *obj, const char *name, const char *path,
5184 const char *main_local, const char *fmt1, const char *fmt2)
5185 {
5186 const char *fmt;
5187 int c;
5188
5189 if (fmt1 == NULL)
5190 fmt = fmt2;
5191 else
5192 /* XXX bogus */
5193 fmt = strncmp(name, "lib", 3) == 0 ? fmt1 : fmt2;
5194
5195 while ((c = *fmt++) != '\0') {
5196 switch (c) {
5197 default:
5198 rtld_putchar(c);
5199 continue;
5200 case '\\':
5201 switch (c = *fmt) {
5202 case '\0':
5203 continue;
5204 case 'n':
5205 rtld_putchar('\n');
5206 break;
5207 case 't':
5208 rtld_putchar('\t');
5209 break;
5210 }
5211 break;
5212 case '%':
5213 switch (c = *fmt) {
5214 case '\0':
5215 continue;
5216 case '%':
5217 default:
5218 rtld_putchar(c);
5219 break;
5220 case 'A':
5221 rtld_putstr(main_local);
5222 break;
5223 case 'a':
5224 rtld_putstr(obj_main->path);
5225 break;
5226 case 'o':
5227 rtld_putstr(name);
5228 break;
5229 case 'p':
5230 rtld_putstr(path);
5231 break;
5232 case 'x':
5233 rtld_printf("%p",
5234 obj != NULL ? obj->mapbase : NULL);
5235 break;
5236 }
5237 break;
5238 }
5239 ++fmt;
5240 }
5241 }
5242
5243 static void
trace_loaded_objects(Obj_Entry * obj,bool show_preload)5244 trace_loaded_objects(Obj_Entry *obj, bool show_preload)
5245 {
5246 const char *fmt1, *fmt2, *main_local;
5247 const char *name, *path;
5248 bool first_spurious, list_containers;
5249
5250 trace_calc_fmts(&main_local, &fmt1, &fmt2);
5251 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL) != NULL;
5252
5253 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5254 Needed_Entry *needed;
5255
5256 if (obj->marker)
5257 continue;
5258 if (list_containers && obj->needed != NULL)
5259 rtld_printf("%s:\n", obj->path);
5260 for (needed = obj->needed; needed; needed = needed->next) {
5261 if (needed->obj != NULL) {
5262 if (needed->obj->traced && !list_containers)
5263 continue;
5264 needed->obj->traced = true;
5265 path = needed->obj->path;
5266 } else
5267 path = "not found";
5268
5269 name = obj->strtab + needed->name;
5270 trace_print_obj(needed->obj, name, path, main_local,
5271 fmt1, fmt2);
5272 }
5273 }
5274
5275 if (show_preload) {
5276 if (ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2) == NULL)
5277 fmt2 = "\t%p (%x)\n";
5278 first_spurious = true;
5279
5280 TAILQ_FOREACH(obj, &obj_list, next) {
5281 if (obj->marker || obj == obj_main || obj->traced)
5282 continue;
5283
5284 if (list_containers && first_spurious) {
5285 rtld_printf("[preloaded]\n");
5286 first_spurious = false;
5287 }
5288
5289 Name_Entry *fname = STAILQ_FIRST(&obj->names);
5290 name = fname == NULL ? "<unknown>" : fname->name;
5291 trace_print_obj(obj, name, obj->path, main_local, NULL,
5292 fmt2);
5293 }
5294 }
5295 }
5296
5297 /*
5298 * Unload a dlopened object and its dependencies from memory and from
5299 * our data structures. It is assumed that the DAG rooted in the
5300 * object has already been unreferenced, and that the object has a
5301 * reference count of 0.
5302 */
5303 static void
unload_object(Obj_Entry * root,RtldLockState * lockstate)5304 unload_object(Obj_Entry *root, RtldLockState *lockstate)
5305 {
5306 Obj_Entry marker, *obj, *next;
5307
5308 assert(root->refcount == 0);
5309
5310 /*
5311 * Pass over the DAG removing unreferenced objects from
5312 * appropriate lists.
5313 */
5314 unlink_object(root);
5315
5316 /* Unmap all objects that are no longer referenced. */
5317 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
5318 next = TAILQ_NEXT(obj, next);
5319 if (obj->marker || obj->refcount != 0)
5320 continue;
5321 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize,
5322 0, obj->path);
5323 dbg("unloading \"%s\"", obj->path);
5324 /*
5325 * Unlink the object now to prevent new references from
5326 * being acquired while the bind lock is dropped in
5327 * recursive dlclose() invocations.
5328 */
5329 TAILQ_REMOVE(&obj_list, obj, next);
5330 obj_count--;
5331
5332 if (obj->filtees_loaded) {
5333 if (next != NULL) {
5334 init_marker(&marker);
5335 TAILQ_INSERT_BEFORE(next, &marker, next);
5336 unload_filtees(obj, lockstate);
5337 next = TAILQ_NEXT(&marker, next);
5338 TAILQ_REMOVE(&obj_list, &marker, next);
5339 } else
5340 unload_filtees(obj, lockstate);
5341 }
5342 release_object(obj);
5343 }
5344 }
5345
5346 static void
unlink_object(Obj_Entry * root)5347 unlink_object(Obj_Entry *root)
5348 {
5349 Objlist_Entry *elm;
5350
5351 if (root->refcount == 0) {
5352 /* Remove the object from the RTLD_GLOBAL list. */
5353 objlist_remove(&list_global, root);
5354
5355 /* Remove the object from all objects' DAG lists. */
5356 STAILQ_FOREACH(elm, &root->dagmembers, link) {
5357 objlist_remove(&elm->obj->dldags, root);
5358 if (elm->obj != root)
5359 unlink_object(elm->obj);
5360 }
5361 }
5362 }
5363
5364 static void
ref_dag(Obj_Entry * root)5365 ref_dag(Obj_Entry *root)
5366 {
5367 Objlist_Entry *elm;
5368
5369 assert(root->dag_inited);
5370 STAILQ_FOREACH(elm, &root->dagmembers, link)
5371 elm->obj->refcount++;
5372 }
5373
5374 static void
unref_dag(Obj_Entry * root)5375 unref_dag(Obj_Entry *root)
5376 {
5377 Objlist_Entry *elm;
5378
5379 assert(root->dag_inited);
5380 STAILQ_FOREACH(elm, &root->dagmembers, link)
5381 elm->obj->refcount--;
5382 }
5383
5384 /*
5385 * Common code for MD __tls_get_addr().
5386 */
5387 static void *
tls_get_addr_slow(struct tcb * tcb,int index,size_t offset,bool locked)5388 tls_get_addr_slow(struct tcb *tcb, int index, size_t offset, bool locked)
5389 {
5390 struct dtv *newdtv, *dtv;
5391 RtldLockState lockstate;
5392 int to_copy;
5393
5394 dtv = tcb->tcb_dtv;
5395 /* Check dtv generation in case new modules have arrived */
5396 if (dtv->dtv_gen != tls_dtv_generation) {
5397 if (!locked)
5398 wlock_acquire(rtld_bind_lock, &lockstate);
5399 newdtv = xcalloc(1, sizeof(struct dtv) + tls_max_index *
5400 sizeof(struct dtv_slot));
5401 to_copy = dtv->dtv_size;
5402 if (to_copy > tls_max_index)
5403 to_copy = tls_max_index;
5404 memcpy(newdtv->dtv_slots, dtv->dtv_slots, to_copy *
5405 sizeof(struct dtv_slot));
5406 newdtv->dtv_gen = tls_dtv_generation;
5407 newdtv->dtv_size = tls_max_index;
5408 free(dtv);
5409 if (!locked)
5410 lock_release(rtld_bind_lock, &lockstate);
5411 dtv = tcb->tcb_dtv = newdtv;
5412 }
5413
5414 /* Dynamically allocate module TLS if necessary */
5415 if (dtv->dtv_slots[index - 1].dtvs_tls == 0) {
5416 /* Signal safe, wlock will block out signals. */
5417 if (!locked)
5418 wlock_acquire(rtld_bind_lock, &lockstate);
5419 if (!dtv->dtv_slots[index - 1].dtvs_tls)
5420 dtv->dtv_slots[index - 1].dtvs_tls =
5421 allocate_module_tls(tcb, index);
5422 if (!locked)
5423 lock_release(rtld_bind_lock, &lockstate);
5424 }
5425 return (dtv->dtv_slots[index - 1].dtvs_tls + offset);
5426 }
5427
5428 void *
tls_get_addr_common(struct tcb * tcb,int index,size_t offset)5429 tls_get_addr_common(struct tcb *tcb, int index, size_t offset)
5430 {
5431 struct dtv *dtv;
5432
5433 dtv = tcb->tcb_dtv;
5434 /* Check dtv generation in case new modules have arrived */
5435 if (__predict_true(dtv->dtv_gen == tls_dtv_generation &&
5436 dtv->dtv_slots[index - 1].dtvs_tls != 0))
5437 return (dtv->dtv_slots[index - 1].dtvs_tls + offset);
5438 return (tls_get_addr_slow(tcb, index, offset, false));
5439 }
5440
5441 static struct tcb *
tcb_from_tcb_list_entry(struct tcb_list_entry * tcbelm)5442 tcb_from_tcb_list_entry(struct tcb_list_entry *tcbelm)
5443 {
5444 #ifdef TLS_VARIANT_I
5445 return ((struct tcb *)((char *)tcbelm - tcb_list_entry_offset));
5446 #else
5447 return ((struct tcb *)((char *)tcbelm + tcb_list_entry_offset));
5448 #endif
5449 }
5450
5451 static struct tcb_list_entry *
tcb_list_entry_from_tcb(struct tcb * tcb)5452 tcb_list_entry_from_tcb(struct tcb *tcb)
5453 {
5454 #ifdef TLS_VARIANT_I
5455 return ((struct tcb_list_entry *)((char *)tcb + tcb_list_entry_offset));
5456 #else
5457 return ((struct tcb_list_entry *)((char *)tcb - tcb_list_entry_offset));
5458 #endif
5459 }
5460
5461 static void
tcb_list_insert(struct tcb * tcb)5462 tcb_list_insert(struct tcb *tcb)
5463 {
5464 struct tcb_list_entry *tcbelm;
5465
5466 tcbelm = tcb_list_entry_from_tcb(tcb);
5467 TAILQ_INSERT_TAIL(&tcb_list, tcbelm, next);
5468 }
5469
5470 static void
tcb_list_remove(struct tcb * tcb)5471 tcb_list_remove(struct tcb *tcb)
5472 {
5473 struct tcb_list_entry *tcbelm;
5474
5475 tcbelm = tcb_list_entry_from_tcb(tcb);
5476 TAILQ_REMOVE(&tcb_list, tcbelm, next);
5477 }
5478
5479 #ifdef TLS_VARIANT_I
5480
5481 /*
5482 * Return pointer to allocated TLS block
5483 */
5484 static void *
get_tls_block_ptr(void * tcb,size_t tcbsize)5485 get_tls_block_ptr(void *tcb, size_t tcbsize)
5486 {
5487 size_t extra_size, post_size, pre_size, tls_block_size;
5488 size_t tls_init_align;
5489
5490 tls_init_align = MAX(obj_main->tlsalign, 1);
5491
5492 /* Compute fragments sizes. */
5493 extra_size = tcbsize - TLS_TCB_SIZE;
5494 post_size = calculate_tls_post_size(tls_init_align);
5495 tls_block_size = tcbsize + post_size;
5496 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5497
5498 return ((char *)tcb - pre_size - extra_size);
5499 }
5500
5501 /*
5502 * Allocate Static TLS using the Variant I method.
5503 *
5504 * For details on the layout, see lib/libc/gen/tls.c.
5505 *
5506 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5507 * it is based on tls_last_offset, and TLS offsets here are really TCB
5508 * offsets, whereas libc's tls_static_space is just the executable's static
5509 * TLS segment.
5510 *
5511 * NB: This differs from NetBSD's ld.elf_so, where TLS offsets are relative to
5512 * the end of the TCB.
5513 */
5514 void *
allocate_tls(Obj_Entry * objs,void * oldtcb,size_t tcbsize,size_t tcbalign)5515 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5516 {
5517 Obj_Entry *obj;
5518 char *tls_block;
5519 struct dtv *dtv;
5520 struct tcb *tcb;
5521 char *addr;
5522 size_t i;
5523 size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5524 size_t tls_init_align, tls_init_offset;
5525
5526 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5527 return (oldtcb);
5528
5529 assert(tcbsize >= TLS_TCB_SIZE);
5530 maxalign = MAX(tcbalign, tls_static_max_align);
5531 tls_init_align = MAX(obj_main->tlsalign, 1);
5532
5533 /* Compute fragments sizes. */
5534 extra_size = tcbsize - TLS_TCB_SIZE;
5535 post_size = calculate_tls_post_size(tls_init_align);
5536 tls_block_size = tcbsize + post_size;
5537 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5538 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE -
5539 post_size;
5540
5541 /* Allocate whole TLS block */
5542 tls_block = xmalloc_aligned(tls_block_size, maxalign, 0);
5543 tcb = (struct tcb *)(tls_block + pre_size + extra_size);
5544
5545 if (oldtcb != NULL) {
5546 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5547 tls_static_space);
5548 free(get_tls_block_ptr(oldtcb, tcbsize));
5549
5550 /* Adjust the DTV. */
5551 dtv = tcb->tcb_dtv;
5552 for (i = 0; i < dtv->dtv_size; i++) {
5553 if ((uintptr_t)dtv->dtv_slots[i].dtvs_tls >=
5554 (uintptr_t)oldtcb &&
5555 (uintptr_t)dtv->dtv_slots[i].dtvs_tls <
5556 (uintptr_t)oldtcb + tls_static_space) {
5557 dtv->dtv_slots[i].dtvs_tls = (char *)tcb +
5558 (dtv->dtv_slots[i].dtvs_tls -
5559 (char *)oldtcb);
5560 }
5561 }
5562 } else {
5563 dtv = xcalloc(1, sizeof(struct dtv) + tls_max_index *
5564 sizeof(struct dtv_slot));
5565 tcb->tcb_dtv = dtv;
5566 dtv->dtv_gen = tls_dtv_generation;
5567 dtv->dtv_size = tls_max_index;
5568
5569 for (obj = globallist_curr(objs); obj != NULL;
5570 obj = globallist_next(obj)) {
5571 if (obj->tlsoffset == 0)
5572 continue;
5573 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5574 addr = (char *)tcb + obj->tlsoffset;
5575 if (tls_init_offset > 0)
5576 memset(addr, 0, tls_init_offset);
5577 if (obj->tlsinitsize > 0) {
5578 memcpy(addr + tls_init_offset, obj->tlsinit,
5579 obj->tlsinitsize);
5580 }
5581 if (obj->tlssize > obj->tlsinitsize) {
5582 memset(addr + tls_init_offset +
5583 obj->tlsinitsize,
5584 0,
5585 obj->tlssize - obj->tlsinitsize -
5586 tls_init_offset);
5587 }
5588 dtv->dtv_slots[obj->tlsindex - 1].dtvs_tls = addr;
5589 }
5590 }
5591
5592 tcb_list_insert(tcb);
5593 return (tcb);
5594 }
5595
5596 void
free_tls(void * tcb,size_t tcbsize,size_t tcbalign __unused)5597 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5598 {
5599 struct dtv *dtv;
5600 uintptr_t tlsstart, tlsend;
5601 size_t post_size;
5602 size_t i, tls_init_align __unused;
5603
5604 tcb_list_remove(tcb);
5605
5606 assert(tcbsize >= TLS_TCB_SIZE);
5607 tls_init_align = MAX(obj_main->tlsalign, 1);
5608
5609 /* Compute fragments sizes. */
5610 post_size = calculate_tls_post_size(tls_init_align);
5611
5612 tlsstart = (uintptr_t)tcb + TLS_TCB_SIZE + post_size;
5613 tlsend = (uintptr_t)tcb + tls_static_space;
5614
5615 dtv = ((struct tcb *)tcb)->tcb_dtv;
5616 for (i = 0; i < dtv->dtv_size; i++) {
5617 if (dtv->dtv_slots[i].dtvs_tls != NULL &&
5618 ((uintptr_t)dtv->dtv_slots[i].dtvs_tls < tlsstart ||
5619 (uintptr_t)dtv->dtv_slots[i].dtvs_tls >= tlsend)) {
5620 free(dtv->dtv_slots[i].dtvs_tls);
5621 }
5622 }
5623 free(dtv);
5624 free(get_tls_block_ptr(tcb, tcbsize));
5625 }
5626
5627 #endif /* TLS_VARIANT_I */
5628
5629 #ifdef TLS_VARIANT_II
5630
5631 /*
5632 * Allocate Static TLS using the Variant II method.
5633 */
5634 void *
allocate_tls(Obj_Entry * objs,void * oldtcb,size_t tcbsize,size_t tcbalign)5635 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5636 {
5637 Obj_Entry *obj;
5638 size_t size, ralign;
5639 char *tls_block;
5640 struct dtv *dtv, *olddtv;
5641 struct tcb *tcb;
5642 char *addr;
5643 size_t i;
5644
5645 ralign = tcbalign;
5646 if (tls_static_max_align > ralign)
5647 ralign = tls_static_max_align;
5648 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5649
5650 assert(tcbsize >= 2 * sizeof(uintptr_t));
5651 tls_block = xmalloc_aligned(size, ralign, 0 /* XXX */);
5652 dtv = xcalloc(1, sizeof(struct dtv) + tls_max_index *
5653 sizeof(struct dtv_slot));
5654
5655 tcb = (struct tcb *)(tls_block + roundup(tls_static_space, ralign));
5656 tcb->tcb_self = tcb;
5657 tcb->tcb_dtv = dtv;
5658
5659 dtv->dtv_gen = tls_dtv_generation;
5660 dtv->dtv_size = tls_max_index;
5661
5662 if (oldtcb != NULL) {
5663 /*
5664 * Copy the static TLS block over whole.
5665 */
5666 memcpy((char *)tcb - tls_static_space,
5667 (const char *)oldtcb - tls_static_space,
5668 tls_static_space);
5669
5670 /*
5671 * If any dynamic TLS blocks have been created tls_get_addr(),
5672 * move them over.
5673 */
5674 olddtv = ((struct tcb *)oldtcb)->tcb_dtv;
5675 for (i = 0; i < olddtv->dtv_size; i++) {
5676 if ((uintptr_t)olddtv->dtv_slots[i].dtvs_tls <
5677 (uintptr_t)oldtcb - size ||
5678 (uintptr_t)olddtv->dtv_slots[i].dtvs_tls >
5679 (uintptr_t)oldtcb) {
5680 dtv->dtv_slots[i].dtvs_tls =
5681 olddtv->dtv_slots[i].dtvs_tls;
5682 olddtv->dtv_slots[i].dtvs_tls = NULL;
5683 }
5684 }
5685
5686 /*
5687 * We assume that this block was the one we created with
5688 * allocate_initial_tls().
5689 */
5690 free_tls(oldtcb, 2 * sizeof(uintptr_t), sizeof(uintptr_t));
5691 } else {
5692 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5693 if (obj->marker || obj->tlsoffset == 0)
5694 continue;
5695 addr = (char *)tcb - obj->tlsoffset;
5696 memset(addr + obj->tlsinitsize, 0, obj->tlssize -
5697 obj->tlsinitsize);
5698 if (obj->tlsinit) {
5699 memcpy(addr, obj->tlsinit, obj->tlsinitsize);
5700 obj->static_tls_copied = true;
5701 }
5702 dtv->dtv_slots[obj->tlsindex - 1].dtvs_tls = addr;
5703 }
5704 }
5705
5706 tcb_list_insert(tcb);
5707 return (tcb);
5708 }
5709
5710 void
free_tls(void * tcb,size_t tcbsize __unused,size_t tcbalign)5711 free_tls(void *tcb, size_t tcbsize __unused, size_t tcbalign)
5712 {
5713 struct dtv *dtv;
5714 size_t size, ralign;
5715 size_t i;
5716 uintptr_t tlsstart, tlsend;
5717
5718 tcb_list_remove(tcb);
5719
5720 /*
5721 * Figure out the size of the initial TLS block so that we can
5722 * find stuff which ___tls_get_addr() allocated dynamically.
5723 */
5724 ralign = tcbalign;
5725 if (tls_static_max_align > ralign)
5726 ralign = tls_static_max_align;
5727 size = roundup(tls_static_space, ralign);
5728
5729 dtv = ((struct tcb *)tcb)->tcb_dtv;
5730 tlsend = (uintptr_t)tcb;
5731 tlsstart = tlsend - size;
5732 for (i = 0; i < dtv->dtv_size; i++) {
5733 if (dtv->dtv_slots[i].dtvs_tls != NULL &&
5734 ((uintptr_t)dtv->dtv_slots[i].dtvs_tls < tlsstart ||
5735 (uintptr_t)dtv->dtv_slots[i].dtvs_tls > tlsend)) {
5736 free(dtv->dtv_slots[i].dtvs_tls);
5737 }
5738 }
5739
5740 free((void *)tlsstart);
5741 free(dtv);
5742 }
5743
5744 #endif /* TLS_VARIANT_II */
5745
5746 /*
5747 * Allocate TLS block for module with given index.
5748 */
5749 void *
allocate_module_tls(struct tcb * tcb,int index)5750 allocate_module_tls(struct tcb *tcb, int index)
5751 {
5752 Obj_Entry *obj;
5753 char *p;
5754
5755 TAILQ_FOREACH(obj, &obj_list, next) {
5756 if (obj->marker)
5757 continue;
5758 if (obj->tlsindex == index)
5759 break;
5760 }
5761 if (obj == NULL) {
5762 _rtld_error("Can't find module with TLS index %d", index);
5763 rtld_die();
5764 }
5765
5766 if (obj->tls_static) {
5767 #ifdef TLS_VARIANT_I
5768 p = (char *)tcb + obj->tlsoffset;
5769 #else
5770 p = (char *)tcb - obj->tlsoffset;
5771 #endif
5772 return (p);
5773 }
5774
5775 obj->tls_dynamic = true;
5776
5777 p = xmalloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5778 memcpy(p, obj->tlsinit, obj->tlsinitsize);
5779 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5780 return (p);
5781 }
5782
5783 static bool
allocate_tls_offset_common(size_t * offp,size_t tlssize,size_t tlsalign,size_t tlspoffset __unused)5784 allocate_tls_offset_common(size_t *offp, size_t tlssize, size_t tlsalign,
5785 size_t tlspoffset __unused)
5786 {
5787 size_t off;
5788
5789 if (tls_last_offset == 0)
5790 off = calculate_first_tls_offset(tlssize, tlsalign,
5791 tlspoffset);
5792 else
5793 off = calculate_tls_offset(tls_last_offset, tls_last_size,
5794 tlssize, tlsalign, tlspoffset);
5795
5796 *offp = off;
5797 #ifdef TLS_VARIANT_I
5798 off += tlssize;
5799 #endif
5800
5801 /*
5802 * If we have already fixed the size of the static TLS block, we
5803 * must stay within that size. When allocating the static TLS, we
5804 * leave a small amount of space spare to be used for dynamically
5805 * loading modules which use static TLS.
5806 */
5807 if (tls_static_space != 0) {
5808 if (off > tls_static_space)
5809 return (false);
5810 } else if (tlsalign > tls_static_max_align) {
5811 tls_static_max_align = tlsalign;
5812 }
5813
5814 tls_last_offset = off;
5815 tls_last_size = tlssize;
5816
5817 return (true);
5818 }
5819
5820 bool
allocate_tls_offset(Obj_Entry * obj)5821 allocate_tls_offset(Obj_Entry *obj)
5822 {
5823 if (obj->tls_dynamic)
5824 return (false);
5825
5826 if (obj->tls_static)
5827 return (true);
5828
5829 if (obj->tlssize == 0) {
5830 obj->tls_static = true;
5831 return (true);
5832 }
5833
5834 if (!allocate_tls_offset_common(&obj->tlsoffset, obj->tlssize,
5835 obj->tlsalign, obj->tlspoffset))
5836 return (false);
5837
5838 obj->tls_static = true;
5839
5840 return (true);
5841 }
5842
5843 void
free_tls_offset(Obj_Entry * obj)5844 free_tls_offset(Obj_Entry *obj)
5845 {
5846 /*
5847 * If we were the last thing to allocate out of the static TLS
5848 * block, we give our space back to the 'allocator'. This is a
5849 * simplistic workaround to allow libGL.so.1 to be loaded and
5850 * unloaded multiple times.
5851 */
5852 size_t off = obj->tlsoffset;
5853
5854 #ifdef TLS_VARIANT_I
5855 off += obj->tlssize;
5856 #endif
5857 if (off == tls_last_offset) {
5858 tls_last_offset -= obj->tlssize;
5859 tls_last_size = 0;
5860 }
5861 }
5862
5863 void *
_rtld_allocate_tls(void * oldtcb,size_t tcbsize,size_t tcbalign)5864 _rtld_allocate_tls(void *oldtcb, size_t tcbsize, size_t tcbalign)
5865 {
5866 void *ret;
5867 RtldLockState lockstate;
5868
5869 wlock_acquire(rtld_bind_lock, &lockstate);
5870 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtcb,
5871 tcbsize, tcbalign);
5872 lock_release(rtld_bind_lock, &lockstate);
5873 return (ret);
5874 }
5875
5876 void
_rtld_free_tls(void * tcb,size_t tcbsize,size_t tcbalign)5877 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5878 {
5879 RtldLockState lockstate;
5880
5881 wlock_acquire(rtld_bind_lock, &lockstate);
5882 free_tls(tcb, tcbsize, tcbalign);
5883 lock_release(rtld_bind_lock, &lockstate);
5884 }
5885
5886 static void
object_add_name(Obj_Entry * obj,const char * name)5887 object_add_name(Obj_Entry *obj, const char *name)
5888 {
5889 Name_Entry *entry;
5890 size_t len;
5891
5892 len = strlen(name);
5893 entry = malloc(sizeof(Name_Entry) + len);
5894
5895 if (entry != NULL) {
5896 strcpy(entry->name, name);
5897 STAILQ_INSERT_TAIL(&obj->names, entry, link);
5898 }
5899 }
5900
5901 static int
object_match_name(const Obj_Entry * obj,const char * name)5902 object_match_name(const Obj_Entry *obj, const char *name)
5903 {
5904 Name_Entry *entry;
5905
5906 STAILQ_FOREACH(entry, &obj->names, link) {
5907 if (strcmp(name, entry->name) == 0)
5908 return (1);
5909 }
5910 return (0);
5911 }
5912
5913 static Obj_Entry *
locate_dependency(const Obj_Entry * obj,const char * name)5914 locate_dependency(const Obj_Entry *obj, const char *name)
5915 {
5916 const Objlist_Entry *entry;
5917 const Needed_Entry *needed;
5918
5919 STAILQ_FOREACH(entry, &list_main, link) {
5920 if (object_match_name(entry->obj, name))
5921 return (entry->obj);
5922 }
5923
5924 for (needed = obj->needed; needed != NULL; needed = needed->next) {
5925 if (strcmp(obj->strtab + needed->name, name) == 0 ||
5926 (needed->obj != NULL && object_match_name(needed->obj,
5927 name))) {
5928 /*
5929 * If there is DT_NEEDED for the name we are looking
5930 * for, we are all set. Note that object might not be
5931 * found if dependency was not loaded yet, so the
5932 * function can return NULL here. This is expected and
5933 * handled properly by the caller.
5934 */
5935 return (needed->obj);
5936 }
5937 }
5938 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5939 obj->path, name);
5940 rtld_die();
5941 }
5942
5943 static int
check_object_provided_version(Obj_Entry * refobj,const Obj_Entry * depobj,const Elf_Vernaux * vna)5944 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5945 const Elf_Vernaux *vna)
5946 {
5947 const Elf_Verdef *vd;
5948 const char *vername;
5949
5950 vername = refobj->strtab + vna->vna_name;
5951 vd = depobj->verdef;
5952 if (vd == NULL) {
5953 _rtld_error("%s: version %s required by %s not defined",
5954 depobj->path, vername, refobj->path);
5955 return (-1);
5956 }
5957 for (;;) {
5958 if (vd->vd_version != VER_DEF_CURRENT) {
5959 _rtld_error(
5960 "%s: Unsupported version %d of Elf_Verdef entry",
5961 depobj->path, vd->vd_version);
5962 return (-1);
5963 }
5964 if (vna->vna_hash == vd->vd_hash) {
5965 const Elf_Verdaux *aux =
5966 (const Elf_Verdaux *)((const char *)vd +
5967 vd->vd_aux);
5968 if (strcmp(vername, depobj->strtab + aux->vda_name) ==
5969 0)
5970 return (0);
5971 }
5972 if (vd->vd_next == 0)
5973 break;
5974 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5975 }
5976 if (vna->vna_flags & VER_FLG_WEAK)
5977 return (0);
5978 _rtld_error("%s: version %s required by %s not found", depobj->path,
5979 vername, refobj->path);
5980 return (-1);
5981 }
5982
5983 static int
rtld_verify_object_versions(Obj_Entry * obj)5984 rtld_verify_object_versions(Obj_Entry *obj)
5985 {
5986 const Elf_Verneed *vn;
5987 const Elf_Verdef *vd;
5988 const Elf_Verdaux *vda;
5989 const Elf_Vernaux *vna;
5990 const Obj_Entry *depobj;
5991 int maxvernum, vernum;
5992
5993 if (obj->ver_checked)
5994 return (0);
5995 obj->ver_checked = true;
5996
5997 maxvernum = 0;
5998 /*
5999 * Walk over defined and required version records and figure out
6000 * max index used by any of them. Do very basic sanity checking
6001 * while there.
6002 */
6003 vn = obj->verneed;
6004 while (vn != NULL) {
6005 if (vn->vn_version != VER_NEED_CURRENT) {
6006 _rtld_error(
6007 "%s: Unsupported version %d of Elf_Verneed entry",
6008 obj->path, vn->vn_version);
6009 return (-1);
6010 }
6011 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
6012 for (;;) {
6013 vernum = VER_NEED_IDX(vna->vna_other);
6014 if (vernum > maxvernum)
6015 maxvernum = vernum;
6016 if (vna->vna_next == 0)
6017 break;
6018 vna = (const Elf_Vernaux *)((const char *)vna +
6019 vna->vna_next);
6020 }
6021 if (vn->vn_next == 0)
6022 break;
6023 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
6024 }
6025
6026 vd = obj->verdef;
6027 while (vd != NULL) {
6028 if (vd->vd_version != VER_DEF_CURRENT) {
6029 _rtld_error(
6030 "%s: Unsupported version %d of Elf_Verdef entry",
6031 obj->path, vd->vd_version);
6032 return (-1);
6033 }
6034 vernum = VER_DEF_IDX(vd->vd_ndx);
6035 if (vernum > maxvernum)
6036 maxvernum = vernum;
6037 if (vd->vd_next == 0)
6038 break;
6039 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
6040 }
6041
6042 if (maxvernum == 0)
6043 return (0);
6044
6045 /*
6046 * Store version information in array indexable by version index.
6047 * Verify that object version requirements are satisfied along the
6048 * way.
6049 */
6050 obj->vernum = maxvernum + 1;
6051 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
6052
6053 vd = obj->verdef;
6054 while (vd != NULL) {
6055 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
6056 vernum = VER_DEF_IDX(vd->vd_ndx);
6057 assert(vernum <= maxvernum);
6058 vda = (const Elf_Verdaux *)((const char *)vd +
6059 vd->vd_aux);
6060 obj->vertab[vernum].hash = vd->vd_hash;
6061 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
6062 obj->vertab[vernum].file = NULL;
6063 obj->vertab[vernum].flags = 0;
6064 }
6065 if (vd->vd_next == 0)
6066 break;
6067 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
6068 }
6069
6070 vn = obj->verneed;
6071 while (vn != NULL) {
6072 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
6073 if (depobj == NULL)
6074 return (-1);
6075 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
6076 for (;;) {
6077 if (check_object_provided_version(obj, depobj, vna))
6078 return (-1);
6079 vernum = VER_NEED_IDX(vna->vna_other);
6080 assert(vernum <= maxvernum);
6081 obj->vertab[vernum].hash = vna->vna_hash;
6082 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
6083 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
6084 obj->vertab[vernum].flags = (vna->vna_other &
6085 VER_NEED_HIDDEN) != 0 ? VER_INFO_HIDDEN : 0;
6086 if (vna->vna_next == 0)
6087 break;
6088 vna = (const Elf_Vernaux *)((const char *)vna +
6089 vna->vna_next);
6090 }
6091 if (vn->vn_next == 0)
6092 break;
6093 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
6094 }
6095 return (0);
6096 }
6097
6098 static int
rtld_verify_versions(const Objlist * objlist)6099 rtld_verify_versions(const Objlist *objlist)
6100 {
6101 Objlist_Entry *entry;
6102 int rc;
6103
6104 rc = 0;
6105 STAILQ_FOREACH(entry, objlist, link) {
6106 /*
6107 * Skip dummy objects or objects that have their version
6108 * requirements already checked.
6109 */
6110 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
6111 continue;
6112 if (rtld_verify_object_versions(entry->obj) == -1) {
6113 rc = -1;
6114 if (ld_tracing == NULL)
6115 break;
6116 }
6117 }
6118 if (rc == 0 || ld_tracing != NULL)
6119 rc = rtld_verify_object_versions(&obj_rtld);
6120 return (rc);
6121 }
6122
6123 const Ver_Entry *
fetch_ventry(const Obj_Entry * obj,unsigned long symnum)6124 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
6125 {
6126 Elf_Versym vernum;
6127
6128 if (obj->vertab) {
6129 vernum = VER_NDX(obj->versyms[symnum]);
6130 if (vernum >= obj->vernum) {
6131 _rtld_error("%s: symbol %s has wrong verneed value %d",
6132 obj->path, obj->strtab + symnum, vernum);
6133 } else if (obj->vertab[vernum].hash != 0) {
6134 return (&obj->vertab[vernum]);
6135 }
6136 }
6137 return (NULL);
6138 }
6139
6140 int
_rtld_get_stack_prot(void)6141 _rtld_get_stack_prot(void)
6142 {
6143 return (stack_prot);
6144 }
6145
6146 int
_rtld_is_dlopened(void * arg)6147 _rtld_is_dlopened(void *arg)
6148 {
6149 Obj_Entry *obj;
6150 RtldLockState lockstate;
6151 int res;
6152
6153 rlock_acquire(rtld_bind_lock, &lockstate);
6154 obj = dlcheck(arg);
6155 if (obj == NULL)
6156 obj = obj_from_addr(arg);
6157 if (obj == NULL) {
6158 _rtld_error("No shared object contains address");
6159 lock_release(rtld_bind_lock, &lockstate);
6160 return (-1);
6161 }
6162 res = obj->dlopened ? 1 : 0;
6163 lock_release(rtld_bind_lock, &lockstate);
6164 return (res);
6165 }
6166
6167 static int
obj_remap_relro(Obj_Entry * obj,int prot)6168 obj_remap_relro(Obj_Entry *obj, int prot)
6169 {
6170 const Elf_Phdr *ph;
6171 caddr_t relro_page;
6172 size_t relro_size;
6173
6174 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr +
6175 obj->phsize; ph++) {
6176 if (ph->p_type != PT_GNU_RELRO)
6177 continue;
6178 relro_page = obj->relocbase + rtld_trunc_page(ph->p_vaddr);
6179 relro_size = rtld_round_page(ph->p_vaddr + ph->p_memsz) -
6180 rtld_trunc_page(ph->p_vaddr);
6181 if (mprotect(relro_page, relro_size, prot) == -1) {
6182 _rtld_error(
6183 "%s: Cannot set relro protection to %#x: %s",
6184 obj->path, prot, rtld_strerror(errno));
6185 return (-1);
6186 }
6187 break;
6188 }
6189 return (0);
6190 }
6191
6192 static int
obj_disable_relro(Obj_Entry * obj)6193 obj_disable_relro(Obj_Entry *obj)
6194 {
6195 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
6196 }
6197
6198 static int
obj_enforce_relro(Obj_Entry * obj)6199 obj_enforce_relro(Obj_Entry *obj)
6200 {
6201 return (obj_remap_relro(obj, PROT_READ));
6202 }
6203
6204 static void
map_stacks_exec(RtldLockState * lockstate)6205 map_stacks_exec(RtldLockState *lockstate)
6206 {
6207 void (*thr_map_stacks_exec)(void);
6208
6209 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
6210 return;
6211 thr_map_stacks_exec = (void (*)(void))(
6212 uintptr_t)get_program_var_addr("__pthread_map_stacks_exec",
6213 lockstate);
6214 if (thr_map_stacks_exec != NULL) {
6215 stack_prot |= PROT_EXEC;
6216 thr_map_stacks_exec();
6217 }
6218 }
6219
6220 static void
distribute_static_tls(Objlist * list)6221 distribute_static_tls(Objlist *list)
6222 {
6223 struct tcb_list_entry *tcbelm;
6224 Objlist_Entry *objelm;
6225 struct tcb *tcb;
6226 Obj_Entry *obj;
6227 char *tlsbase;
6228
6229 STAILQ_FOREACH(objelm, list, link) {
6230 obj = objelm->obj;
6231 if (obj->marker || !obj->tls_static || obj->static_tls_copied)
6232 continue;
6233 TAILQ_FOREACH(tcbelm, &tcb_list, next) {
6234 tcb = tcb_from_tcb_list_entry(tcbelm);
6235 #ifdef TLS_VARIANT_I
6236 tlsbase = (char *)tcb + obj->tlsoffset;
6237 #else
6238 tlsbase = (char *)tcb - obj->tlsoffset;
6239 #endif
6240 memcpy(tlsbase, obj->tlsinit, obj->tlsinitsize);
6241 memset(tlsbase + obj->tlsinitsize, 0,
6242 obj->tlssize - obj->tlsinitsize);
6243 }
6244 obj->static_tls_copied = true;
6245 }
6246 }
6247
6248 void
symlook_init(SymLook * dst,const char * name)6249 symlook_init(SymLook *dst, const char *name)
6250 {
6251 bzero(dst, sizeof(*dst));
6252 dst->name = name;
6253 dst->hash = elf_hash(name);
6254 dst->hash_gnu = gnu_hash(name);
6255 }
6256
6257 static void
symlook_init_from_req(SymLook * dst,const SymLook * src)6258 symlook_init_from_req(SymLook *dst, const SymLook *src)
6259 {
6260 dst->name = src->name;
6261 dst->hash = src->hash;
6262 dst->hash_gnu = src->hash_gnu;
6263 dst->ventry = src->ventry;
6264 dst->flags = src->flags;
6265 dst->defobj_out = NULL;
6266 dst->sym_out = NULL;
6267 dst->lockstate = src->lockstate;
6268 }
6269
6270 static int
open_binary_fd(const char * argv0,bool search_in_path,const char ** binpath_res)6271 open_binary_fd(const char *argv0, bool search_in_path, const char **binpath_res)
6272 {
6273 char *binpath, *pathenv, *pe, *res1;
6274 const char *res;
6275 int fd;
6276
6277 binpath = NULL;
6278 res = NULL;
6279 if (search_in_path && strchr(argv0, '/') == NULL) {
6280 binpath = xmalloc(PATH_MAX);
6281 pathenv = getenv("PATH");
6282 if (pathenv == NULL) {
6283 _rtld_error("-p and no PATH environment variable");
6284 rtld_die();
6285 }
6286 pathenv = strdup(pathenv);
6287 if (pathenv == NULL) {
6288 _rtld_error("Cannot allocate memory");
6289 rtld_die();
6290 }
6291 fd = -1;
6292 errno = ENOENT;
6293 while ((pe = strsep(&pathenv, ":")) != NULL) {
6294 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
6295 continue;
6296 if (binpath[0] != '\0' &&
6297 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
6298 continue;
6299 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
6300 continue;
6301 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
6302 if (fd != -1 || errno != ENOENT) {
6303 res = binpath;
6304 break;
6305 }
6306 }
6307 free(pathenv);
6308 } else {
6309 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
6310 res = argv0;
6311 }
6312
6313 if (fd == -1) {
6314 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
6315 rtld_die();
6316 }
6317 if (res != NULL && res[0] != '/') {
6318 res1 = xmalloc(PATH_MAX);
6319 if (realpath(res, res1) != NULL) {
6320 if (res != argv0)
6321 free(__DECONST(char *, res));
6322 res = res1;
6323 } else {
6324 free(res1);
6325 }
6326 }
6327 *binpath_res = res;
6328 return (fd);
6329 }
6330
6331 /*
6332 * Parse a set of command-line arguments.
6333 */
6334 static int
parse_args(char * argv[],int argc,bool * use_pathp,int * fdp,const char ** argv0,bool * dir_ignore)6335 parse_args(char *argv[], int argc, bool *use_pathp, int *fdp,
6336 const char **argv0, bool *dir_ignore)
6337 {
6338 const char *arg;
6339 char machine[64];
6340 size_t sz;
6341 int arglen, fd, i, j, mib[2];
6342 char opt;
6343 bool seen_b, seen_f;
6344
6345 dbg("Parsing command-line arguments");
6346 *use_pathp = false;
6347 *fdp = -1;
6348 *dir_ignore = false;
6349 seen_b = seen_f = false;
6350
6351 for (i = 1; i < argc; i++) {
6352 arg = argv[i];
6353 dbg("argv[%d]: '%s'", i, arg);
6354
6355 /*
6356 * rtld arguments end with an explicit "--" or with the first
6357 * non-prefixed argument.
6358 */
6359 if (strcmp(arg, "--") == 0) {
6360 i++;
6361 break;
6362 }
6363 if (arg[0] != '-')
6364 break;
6365
6366 /*
6367 * All other arguments are single-character options that can
6368 * be combined, so we need to search through `arg` for them.
6369 */
6370 arglen = strlen(arg);
6371 for (j = 1; j < arglen; j++) {
6372 opt = arg[j];
6373 if (opt == 'h') {
6374 print_usage(argv[0]);
6375 _exit(0);
6376 } else if (opt == 'b') {
6377 if (seen_f) {
6378 _rtld_error("Both -b and -f specified");
6379 rtld_die();
6380 }
6381 if (j != arglen - 1) {
6382 _rtld_error("Invalid options: %s", arg);
6383 rtld_die();
6384 }
6385 i++;
6386 *argv0 = argv[i];
6387 seen_b = true;
6388 break;
6389 } else if (opt == 'd') {
6390 *dir_ignore = true;
6391 } else if (opt == 'f') {
6392 if (seen_b) {
6393 _rtld_error("Both -b and -f specified");
6394 rtld_die();
6395 }
6396
6397 /*
6398 * -f XX can be used to specify a
6399 * descriptor for the binary named at
6400 * the command line (i.e., the later
6401 * argument will specify the process
6402 * name but the descriptor is what
6403 * will actually be executed).
6404 *
6405 * -f must be the last option in the
6406 * group, e.g., -abcf <fd>.
6407 */
6408 if (j != arglen - 1) {
6409 _rtld_error("Invalid options: %s", arg);
6410 rtld_die();
6411 }
6412 i++;
6413 fd = parse_integer(argv[i]);
6414 if (fd == -1) {
6415 _rtld_error(
6416 "Invalid file descriptor: '%s'",
6417 argv[i]);
6418 rtld_die();
6419 }
6420 *fdp = fd;
6421 seen_f = true;
6422 break;
6423 } else if (opt == 'o') {
6424 struct ld_env_var_desc *l;
6425 char *n, *v;
6426 u_int ll;
6427
6428 if (j != arglen - 1) {
6429 _rtld_error("Invalid options: %s", arg);
6430 rtld_die();
6431 }
6432 i++;
6433 n = argv[i];
6434 v = strchr(n, '=');
6435 if (v == NULL) {
6436 _rtld_error("No '=' in -o parameter");
6437 rtld_die();
6438 }
6439 for (ll = 0; ll < nitems(ld_env_vars); ll++) {
6440 l = &ld_env_vars[ll];
6441 if (v - n == (ptrdiff_t)strlen(l->n) &&
6442 strncmp(n, l->n, v - n) == 0) {
6443 l->val = v + 1;
6444 break;
6445 }
6446 }
6447 if (ll == nitems(ld_env_vars)) {
6448 _rtld_error("Unknown LD_ option %s", n);
6449 rtld_die();
6450 }
6451 } else if (opt == 'p') {
6452 *use_pathp = true;
6453 } else if (opt == 'u') {
6454 u_int ll;
6455
6456 for (ll = 0; ll < nitems(ld_env_vars); ll++)
6457 ld_env_vars[ll].val = NULL;
6458 } else if (opt == 'v') {
6459 machine[0] = '\0';
6460 mib[0] = CTL_HW;
6461 mib[1] = HW_MACHINE;
6462 sz = sizeof(machine);
6463 sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
6464 ld_elf_hints_path = ld_get_env_var(
6465 LD_ELF_HINTS_PATH);
6466 set_ld_elf_hints_path();
6467 rtld_printf(
6468 "FreeBSD ld-elf.so.1 %s\n"
6469 "FreeBSD_version %d\n"
6470 "Default lib path %s\n"
6471 "Hints lib path %s\n"
6472 "Env prefix %s\n"
6473 "Default hint file %s\n"
6474 "Hint file %s\n"
6475 "libmap file %s\n"
6476 "Optional static TLS size %zd bytes\n",
6477 machine, __FreeBSD_version,
6478 ld_standard_library_path, gethints(false),
6479 ld_env_prefix, ld_elf_hints_default,
6480 ld_elf_hints_path, ld_path_libmap_conf,
6481 ld_static_tls_extra);
6482 _exit(0);
6483 } else {
6484 _rtld_error("Invalid argument: '%s'", arg);
6485 print_usage(argv[0]);
6486 rtld_die();
6487 }
6488 }
6489 }
6490
6491 if (!seen_b)
6492 *argv0 = argv[i];
6493 return (i);
6494 }
6495
6496 /*
6497 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
6498 */
6499 static int
parse_integer(const char * str)6500 parse_integer(const char *str)
6501 {
6502 static const int RADIX = 10; /* XXXJA: possibly support hex? */
6503 const char *orig;
6504 int n;
6505 char c;
6506
6507 orig = str;
6508 n = 0;
6509 for (c = *str; c != '\0'; c = *++str) {
6510 if (c < '0' || c > '9')
6511 return (-1);
6512
6513 n *= RADIX;
6514 n += c - '0';
6515 }
6516
6517 /* Make sure we actually parsed something. */
6518 if (str == orig)
6519 return (-1);
6520 return (n);
6521 }
6522
6523 static void
print_usage(const char * argv0)6524 print_usage(const char *argv0)
6525 {
6526 rtld_printf(
6527 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n"
6528 "\n"
6529 "Options:\n"
6530 " -h Display this help message\n"
6531 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n"
6532 " -d Ignore lack of exec permissions for the binary\n"
6533 " -f <FD> Execute <FD> instead of searching for <binary>\n"
6534 " -o <OPT>=<VAL> Set LD_<OPT> to <VAL>, without polluting env\n"
6535 " -p Search in PATH for named binary\n"
6536 " -u Ignore LD_ environment variables\n"
6537 " -v Display identification information\n"
6538 " -- End of RTLD options\n"
6539 " <binary> Name of process to execute\n"
6540 " <args> Arguments to the executed process\n",
6541 argv0);
6542 }
6543
6544 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt }
6545 static const struct auxfmt {
6546 const char *name;
6547 const char *fmt;
6548 } auxfmts[] = {
6549 AUXFMT(AT_NULL, NULL),
6550 AUXFMT(AT_IGNORE, NULL),
6551 AUXFMT(AT_EXECFD, "%ld"),
6552 AUXFMT(AT_PHDR, "%p"),
6553 AUXFMT(AT_PHENT, "%lu"),
6554 AUXFMT(AT_PHNUM, "%lu"),
6555 AUXFMT(AT_PAGESZ, "%lu"),
6556 AUXFMT(AT_BASE, "%#lx"),
6557 AUXFMT(AT_FLAGS, "%#lx"),
6558 AUXFMT(AT_ENTRY, "%p"),
6559 AUXFMT(AT_NOTELF, NULL),
6560 AUXFMT(AT_UID, "%ld"),
6561 AUXFMT(AT_EUID, "%ld"),
6562 AUXFMT(AT_GID, "%ld"),
6563 AUXFMT(AT_EGID, "%ld"),
6564 AUXFMT(AT_EXECPATH, "%s"),
6565 AUXFMT(AT_CANARY, "%p"),
6566 AUXFMT(AT_CANARYLEN, "%lu"),
6567 AUXFMT(AT_OSRELDATE, "%lu"),
6568 AUXFMT(AT_NCPUS, "%lu"),
6569 AUXFMT(AT_PAGESIZES, "%p"),
6570 AUXFMT(AT_PAGESIZESLEN, "%lu"),
6571 AUXFMT(AT_TIMEKEEP, "%p"),
6572 AUXFMT(AT_STACKPROT, "%#lx"),
6573 AUXFMT(AT_EHDRFLAGS, "%#lx"),
6574 AUXFMT(AT_HWCAP, "%#lx"),
6575 AUXFMT(AT_HWCAP2, "%#lx"),
6576 AUXFMT(AT_BSDFLAGS, "%#lx"),
6577 AUXFMT(AT_ARGC, "%lu"),
6578 AUXFMT(AT_ARGV, "%p"),
6579 AUXFMT(AT_ENVC, "%p"),
6580 AUXFMT(AT_ENVV, "%p"),
6581 AUXFMT(AT_PS_STRINGS, "%p"),
6582 AUXFMT(AT_FXRNG, "%p"),
6583 AUXFMT(AT_KPRELOAD, "%p"),
6584 AUXFMT(AT_USRSTACKBASE, "%#lx"),
6585 AUXFMT(AT_USRSTACKLIM, "%#lx"),
6586 /* AT_CHERI_STATS */
6587 AUXFMT(AT_HWCAP3, "%#lx"),
6588 AUXFMT(AT_HWCAP4, "%#lx"),
6589
6590 };
6591
6592 static bool
is_ptr_fmt(const char * fmt)6593 is_ptr_fmt(const char *fmt)
6594 {
6595 char last;
6596
6597 last = fmt[strlen(fmt) - 1];
6598 return (last == 'p' || last == 's');
6599 }
6600
6601 static void
dump_auxv(Elf_Auxinfo ** aux_info)6602 dump_auxv(Elf_Auxinfo **aux_info)
6603 {
6604 Elf_Auxinfo *auxp;
6605 const struct auxfmt *fmt;
6606 int i;
6607
6608 for (i = 0; i < AT_COUNT; i++) {
6609 auxp = aux_info[i];
6610 if (auxp == NULL)
6611 continue;
6612 fmt = &auxfmts[i];
6613 if (fmt->fmt == NULL)
6614 continue;
6615 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name);
6616 if (is_ptr_fmt(fmt->fmt)) {
6617 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6618 auxp->a_un.a_ptr);
6619 } else {
6620 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6621 auxp->a_un.a_val);
6622 }
6623 rtld_fdprintf(STDOUT_FILENO, "\n");
6624 }
6625 }
6626
6627 const char *
rtld_get_var(const char * name)6628 rtld_get_var(const char *name)
6629 {
6630 const struct ld_env_var_desc *lvd;
6631 u_int i;
6632
6633 for (i = 0; i < nitems(ld_env_vars); i++) {
6634 lvd = &ld_env_vars[i];
6635 if (strcmp(lvd->n, name) == 0)
6636 return (lvd->val);
6637 }
6638 return (NULL);
6639 }
6640
6641 int
rtld_set_var(const char * name,const char * val)6642 rtld_set_var(const char *name, const char *val)
6643 {
6644 struct ld_env_var_desc *lvd;
6645 u_int i;
6646
6647 for (i = 0; i < nitems(ld_env_vars); i++) {
6648 lvd = &ld_env_vars[i];
6649 if (strcmp(lvd->n, name) != 0)
6650 continue;
6651 if (!lvd->can_update || (lvd->unsecure && !trust))
6652 return (EPERM);
6653 if (lvd->owned)
6654 free(__DECONST(char *, lvd->val));
6655 if (val != NULL)
6656 lvd->val = xstrdup(val);
6657 else
6658 lvd->val = NULL;
6659 lvd->owned = true;
6660 if (lvd->debug)
6661 debug = lvd->val != NULL && *lvd->val != '\0';
6662 return (0);
6663 }
6664 return (ENOENT);
6665 }
6666
6667 /*
6668 * Overrides for libc_pic-provided functions.
6669 */
6670
6671 int
__getosreldate(void)6672 __getosreldate(void)
6673 {
6674 size_t len;
6675 int oid[2];
6676 int error, osrel;
6677
6678 if (osreldate != 0)
6679 return (osreldate);
6680
6681 oid[0] = CTL_KERN;
6682 oid[1] = KERN_OSRELDATE;
6683 osrel = 0;
6684 len = sizeof(osrel);
6685 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6686 if (error == 0 && osrel > 0 && len == sizeof(osrel))
6687 osreldate = osrel;
6688 return (osreldate);
6689 }
6690 const char *
rtld_strerror(int errnum)6691 rtld_strerror(int errnum)
6692 {
6693 if (errnum < 0 || errnum >= sys_nerr)
6694 return ("Unknown error");
6695 return (sys_errlist[errnum]);
6696 }
6697
6698 char *
getenv(const char * name)6699 getenv(const char *name)
6700 {
6701 return (__DECONST(char *, rtld_get_env_val(environ, name,
6702 strlen(name))));
6703 }
6704
6705 /* malloc */
6706 void *
malloc(size_t nbytes)6707 malloc(size_t nbytes)
6708 {
6709 return (__crt_malloc(nbytes));
6710 }
6711
6712 void *
calloc(size_t num,size_t size)6713 calloc(size_t num, size_t size)
6714 {
6715 return (__crt_calloc(num, size));
6716 }
6717
6718 void
free(void * cp)6719 free(void *cp)
6720 {
6721 __crt_free(cp);
6722 }
6723
6724 void *
realloc(void * cp,size_t nbytes)6725 realloc(void *cp, size_t nbytes)
6726 {
6727 return (__crt_realloc(cp, nbytes));
6728 }
6729
6730 extern int _rtld_version__FreeBSD_version __exported;
6731 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6732
6733 extern char _rtld_version_laddr_offset __exported;
6734 char _rtld_version_laddr_offset;
6735
6736 extern char _rtld_version_dlpi_tls_data __exported;
6737 char _rtld_version_dlpi_tls_data;
6738