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