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