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