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