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