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