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