1 /*-
2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4 * Copyright 2009-2012 Konstantin Belousov <kib@FreeBSD.ORG>.
5 * Copyright 2012 John Marino <draco@marino.st>.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * $FreeBSD$
29 */
30
31 /*
32 * Dynamic linker for ELF.
33 *
34 * John Polstra <jdp@polstra.com>.
35 */
36
37 #ifndef __GNUC__
38 #error "GCC is needed to compile this file"
39 #endif
40
41 #include <sys/param.h>
42 #include <sys/mount.h>
43 #include <sys/mman.h>
44 #include <sys/stat.h>
45 #include <sys/sysctl.h>
46 #include <sys/utsname.h>
47 #include <sys/ktrace.h>
48 #include <sys/resident.h>
49 #include <sys/tls.h>
50
51 #include <machine/tls.h>
52
53 #include <dlfcn.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <stdarg.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include "debug.h"
64 #include "rtld.h"
65 #include "libmap.h"
66 #include "rtld_printf.h"
67 #include "notes.h"
68
69 #define cpu_sfence() __asm __volatile("" : : : "memory");
70
71 #define PATH_RTLD "/usr/libexec/ld-elf.so.2"
72 #define LD_ARY_CACHE 16
73
74 /* Types. */
75 typedef void (*func_ptr_type)();
76 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
77
78 /*
79 * Function declarations.
80 */
81 static int __getstatictlsextra(void);
82 static const char *_getenv_ld(const char *id);
83 static void die(void) __dead2;
84 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
85 const Elf_Dyn **, const Elf_Dyn **);
86 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
87 const Elf_Dyn *);
88 static void digest_dynamic(Obj_Entry *, int);
89 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
90 static void distribute_static_tls(Objlist *, RtldLockState *);
91 static Obj_Entry *dlcheck(void *);
92 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
93 int lo_flags, int mode, RtldLockState *lockstate);
94 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
95 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
96 static bool donelist_check(DoneList *, const Obj_Entry *);
97 static void errmsg_restore(char *);
98 static char *errmsg_save(void);
99 static void *fill_search_info(const char *, size_t, void *);
100 static char *find_library(const char *, const Obj_Entry *, int *);
101 static const char *gethints(bool);
102 static void init_dag(Obj_Entry *);
103 static void init_rtld(caddr_t, Elf_Auxinfo **);
104 static void initlist_add_neededs(Needed_Entry *, Objlist *);
105 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
106 static void linkmap_add(Obj_Entry *);
107 static void linkmap_delete(Obj_Entry *);
108 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
109 static void unload_filtees(Obj_Entry *);
110 static int load_needed_objects(Obj_Entry *, int);
111 static int load_preload_objects(void);
112 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
113 static void map_stacks_exec(RtldLockState *);
114 static Obj_Entry *obj_from_addr(const void *);
115 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
116 static void objlist_call_init(Objlist *, RtldLockState *);
117 static void objlist_clear(Objlist *);
118 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
119 static void objlist_init(Objlist *);
120 static void objlist_push_head(Objlist *, Obj_Entry *);
121 static void objlist_push_tail(Objlist *, Obj_Entry *);
122 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
123 static void objlist_remove(Objlist *, Obj_Entry *);
124 static int parse_libdir(const char *);
125 static void *path_enumerate(const char *, path_enum_proc, void *);
126 static int relocate_object_dag(Obj_Entry *root, bool bind_now,
127 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
128 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
129 int flags, RtldLockState *lockstate);
130 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
131 RtldLockState *);
132 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
133 int flags, RtldLockState *lockstate);
134 static int rtld_dirname(const char *, char *);
135 static int rtld_dirname_abs(const char *, char *);
136 static void *rtld_dlopen(const char *name, int fd, int mode);
137 static void rtld_exit(void);
138 static char *search_library_path(const char *, const char *);
139 static char *search_library_pathfds(const char *, const char *, int *);
140 static const void **get_program_var_addr(const char *, RtldLockState *);
141 static void set_program_var(const char *, const void *);
142 static int symlook_default(SymLook *, const Obj_Entry *refobj);
143 static int symlook_global(SymLook *, DoneList *);
144 static void symlook_init_from_req(SymLook *, const SymLook *);
145 static int symlook_list(SymLook *, const Objlist *, DoneList *);
146 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
147 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
148 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
149 static void trace_loaded_objects(Obj_Entry *);
150 static void unlink_object(Obj_Entry *);
151 static void unload_object(Obj_Entry *);
152 static void unref_dag(Obj_Entry *);
153 static void ref_dag(Obj_Entry *);
154 static char *origin_subst_one(char *, const char *, const char *, bool);
155 static char *origin_subst(char *, const char *);
156 static void preinit_main(void);
157 static int rtld_verify_versions(const Objlist *);
158 static int rtld_verify_object_versions(Obj_Entry *);
159 static void object_add_name(Obj_Entry *, const char *);
160 static int object_match_name(const Obj_Entry *, const char *);
161 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
162 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
163 struct dl_phdr_info *phdr_info);
164 static uint_fast32_t gnu_hash (const char *);
165 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
166 const unsigned long);
167
168 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
169 void _r_debug_postinit(struct link_map *) __noinline;
170
171 /*
172 * Data declarations.
173 */
174 static char *error_message; /* Message for dlerror(), or NULL */
175 struct r_debug r_debug; /* for GDB; */
176 static bool libmap_disable; /* Disable libmap */
177 static bool ld_loadfltr; /* Immediate filters processing */
178 static char *libmap_override; /* Maps to use in addition to libmap.conf */
179 static bool trust; /* False for setuid and setgid programs */
180 static bool dangerous_ld_env; /* True if environment variables have been
181 used to affect the libraries loaded */
182 static const char *ld_bind_now; /* Environment variable for immediate binding */
183 static const char *ld_debug; /* Environment variable for debugging */
184 static const char *ld_library_path; /* Environment variable for search path */
185 static const char *ld_library_dirs; /* Env variable for library descriptors */
186 static char *ld_preload; /* Environment variable for libraries to
187 load first */
188 static const char *ld_elf_hints_path; /* Env var. for alternative hints path */
189 static const char *ld_tracing; /* Called from ldd to print libs */
190 static const char *ld_utrace; /* Use utrace() to log events. */
191 static int (*rtld_functrace)( /* Optional function call tracing hook */
192 const char *caller_obj,
193 const char *callee_obj,
194 const char *callee_func,
195 void *stack);
196 static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
197 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
198 static Obj_Entry **obj_tail; /* Link field of last object in list */
199 static Obj_Entry **preload_tail;
200 static Obj_Entry *obj_main; /* The main program shared object */
201 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
202 static unsigned int obj_count; /* Number of objects in obj_list */
203 static unsigned int obj_loads; /* Number of objects in obj_list */
204
205 static int ld_resident; /* Non-zero if resident */
206 static const char *ld_ary[LD_ARY_CACHE];
207 static int ld_index;
208 static Objlist initlist;
209
210 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
211 STAILQ_HEAD_INITIALIZER(list_global);
212 static Objlist list_main = /* Objects loaded at program startup */
213 STAILQ_HEAD_INITIALIZER(list_main);
214 static Objlist list_fini = /* Objects needing fini() calls */
215 STAILQ_HEAD_INITIALIZER(list_fini);
216
217 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
218 const char *__ld_sharedlib_base;
219
220 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
221
222 extern Elf_Dyn _DYNAMIC;
223 #pragma weak _DYNAMIC
224 #ifndef RTLD_IS_DYNAMIC
225 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
226 #endif
227
228 #ifdef ENABLE_OSRELDATE
229 int osreldate;
230 #endif
231
232 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
233 #if 0
234 static int max_stack_flags;
235 #endif
236
237 /*
238 * Global declarations normally provided by crt1. The dynamic linker is
239 * not built with crt1, so we have to provide them ourselves.
240 */
241 char *__progname;
242 char **environ;
243
244 /*
245 * Used to pass argc, argv to init functions.
246 */
247 int main_argc;
248 char **main_argv;
249
250 /*
251 * Globals to control TLS allocation.
252 */
253 size_t tls_last_offset; /* Static TLS offset of last module */
254 size_t tls_last_size; /* Static TLS size of last module */
255 size_t tls_static_space; /* Static TLS space allocated */
256 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
257 int tls_max_index = 1; /* Largest module index allocated */
258
259 /*
260 * Fill in a DoneList with an allocation large enough to hold all of
261 * the currently-loaded objects. Keep this as a macro since it calls
262 * alloca and we want that to occur within the scope of the caller.
263 */
264 #define donelist_init(dlp) \
265 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
266 assert((dlp)->objs != NULL), \
267 (dlp)->num_alloc = obj_count, \
268 (dlp)->num_used = 0)
269
270 #define UTRACE_DLOPEN_START 1
271 #define UTRACE_DLOPEN_STOP 2
272 #define UTRACE_DLCLOSE_START 3
273 #define UTRACE_DLCLOSE_STOP 4
274 #define UTRACE_LOAD_OBJECT 5
275 #define UTRACE_UNLOAD_OBJECT 6
276 #define UTRACE_ADD_RUNDEP 7
277 #define UTRACE_PRELOAD_FINISHED 8
278 #define UTRACE_INIT_CALL 9
279 #define UTRACE_FINI_CALL 10
280
281 struct utrace_rtld {
282 char sig[4]; /* 'RTLD' */
283 int event;
284 void *handle;
285 void *mapbase; /* Used for 'parent' and 'init/fini' */
286 size_t mapsize;
287 int refcnt; /* Used for 'mode' */
288 char name[MAXPATHLEN];
289 };
290
291 #define LD_UTRACE(e, h, mb, ms, r, n) do { \
292 if (ld_utrace != NULL) \
293 ld_utrace_log(e, h, mb, ms, r, n); \
294 } while (0)
295
296 static void
ld_utrace_log(int event,void * handle,void * mapbase,size_t mapsize,int refcnt,const char * name)297 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
298 int refcnt, const char *name)
299 {
300 struct utrace_rtld ut;
301
302 ut.sig[0] = 'R';
303 ut.sig[1] = 'T';
304 ut.sig[2] = 'L';
305 ut.sig[3] = 'D';
306 ut.event = event;
307 ut.handle = handle;
308 ut.mapbase = mapbase;
309 ut.mapsize = mapsize;
310 ut.refcnt = refcnt;
311 bzero(ut.name, sizeof(ut.name));
312 if (name)
313 strlcpy(ut.name, name, sizeof(ut.name));
314 utrace(&ut, sizeof(ut));
315 }
316
317 /*
318 * Main entry point for dynamic linking. The first argument is the
319 * stack pointer. The stack is expected to be laid out as described
320 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
321 * Specifically, the stack pointer points to a word containing
322 * ARGC. Following that in the stack is a null-terminated sequence
323 * of pointers to argument strings. Then comes a null-terminated
324 * sequence of pointers to environment strings. Finally, there is a
325 * sequence of "auxiliary vector" entries.
326 *
327 * The second argument points to a place to store the dynamic linker's
328 * exit procedure pointer and the third to a place to store the main
329 * program's object.
330 *
331 * The return value is the main program's entry point.
332 */
333 func_ptr_type
_rtld(Elf_Addr * sp,func_ptr_type * exit_proc,Obj_Entry ** objp)334 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
335 {
336 Elf_Auxinfo *aux_info[AT_COUNT];
337 int i;
338 int argc;
339 char **argv;
340 char **env;
341 Elf_Auxinfo *aux;
342 Elf_Auxinfo *auxp;
343 const char *argv0;
344 Objlist_Entry *entry;
345 Obj_Entry *obj;
346 Obj_Entry *last_interposer;
347
348 /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
349 Obj_Entry **preload_tail;
350 Objlist initlist;
351 from global to here. It will break the DWARF2 unwind scheme.
352 */
353
354 /*
355 * On entry, the dynamic linker itself has not been relocated yet.
356 * Be very careful not to reference any global data until after
357 * init_rtld has returned. It is OK to reference file-scope statics
358 * and string constants, and to call static and global functions.
359 */
360
361 /* Find the auxiliary vector on the stack. */
362 argc = *sp++;
363 argv = (char **) sp;
364 sp += argc + 1; /* Skip over arguments and NULL terminator */
365 env = (char **) sp;
366
367 /*
368 * If we aren't already resident we have to dig out some more info.
369 * Note that auxinfo does not exist when we are resident.
370 *
371 * I'm not sure about the ld_resident check. It seems to read zero
372 * prior to relocation, which is what we want. When running from a
373 * resident copy everything will be relocated so we are definitely
374 * good there.
375 */
376 if (ld_resident == 0) {
377 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
378 ;
379 aux = (Elf_Auxinfo *) sp;
380
381 /* Digest the auxiliary vector. */
382 for (i = 0; i < AT_COUNT; i++)
383 aux_info[i] = NULL;
384 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
385 if (auxp->a_type < AT_COUNT)
386 aux_info[auxp->a_type] = auxp;
387 }
388
389 /* Initialize and relocate ourselves. */
390 assert(aux_info[AT_BASE] != NULL);
391 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
392 }
393
394 ld_index = 0; /* don't use old env cache in case we are resident */
395 __progname = obj_rtld.path;
396 argv0 = argv[0] != NULL ? argv[0] : "(null)";
397 environ = env;
398 main_argc = argc;
399 main_argv = argv;
400
401 trust = !issetugid();
402
403 ld_bind_now = _getenv_ld("LD_BIND_NOW");
404 /*
405 * If the process is tainted, then we un-set the dangerous environment
406 * variables. The process will be marked as tainted until setuid(2)
407 * is called. If any child process calls setuid(2) we do not want any
408 * future processes to honor the potentially un-safe variables.
409 */
410 if (!trust) {
411 if ( unsetenv("LD_DEBUG")
412 || unsetenv("LD_PRELOAD")
413 || unsetenv("LD_LIBRARY_PATH")
414 || unsetenv("LD_LIBRARY_PATH_FDS")
415 || unsetenv("LD_ELF_HINTS_PATH")
416 || unsetenv("LD_LIBMAP")
417 || unsetenv("LD_LIBMAP_DISABLE")
418 || unsetenv("LD_LOADFLTR")
419 || unsetenv("LD_SHAREDLIB_BASE")
420 ) {
421 _rtld_error("environment corrupt; aborting");
422 die();
423 }
424 }
425 __ld_sharedlib_base = _getenv_ld("LD_SHAREDLIB_BASE");
426 ld_debug = _getenv_ld("LD_DEBUG");
427 libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
428 libmap_override = (char *)_getenv_ld("LD_LIBMAP");
429 ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
430 ld_library_dirs = _getenv_ld("LD_LIBRARY_PATH_FDS");
431 ld_preload = (char *)_getenv_ld("LD_PRELOAD");
432 ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
433 ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
434 dangerous_ld_env = (ld_library_path != NULL)
435 || (ld_preload != NULL)
436 || (ld_elf_hints_path != NULL)
437 || ld_loadfltr
438 || (libmap_override != NULL)
439 || libmap_disable
440 ;
441 ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
442 ld_utrace = _getenv_ld("LD_UTRACE");
443
444 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
445 ld_elf_hints_path = _PATH_ELF_HINTS;
446
447 if (ld_debug != NULL && *ld_debug != '\0')
448 debug = 1;
449 dbg("%s is initialized, base address = %p", __progname,
450 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
451 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
452 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
453
454 dbg("initializing thread locks");
455 lockdflt_init();
456
457 /*
458 * If we are resident we can skip work that we have already done.
459 * Note that the stack is reset and there is no Elf_Auxinfo
460 * when running from a resident image, and the static globals setup
461 * between here and resident_skip will have already been setup.
462 */
463 if (ld_resident)
464 goto resident_skip1;
465
466 /*
467 * Load the main program, or process its program header if it is
468 * already loaded.
469 */
470 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
471 int fd = aux_info[AT_EXECFD]->a_un.a_val;
472 dbg("loading main program");
473 obj_main = map_object(fd, argv0, NULL);
474 close(fd);
475 if (obj_main == NULL)
476 die();
477 #if 0
478 max_stack_flags = obj_main->stack_flags;
479 #endif
480 } else { /* Main program already loaded. */
481 const Elf_Phdr *phdr;
482 int phnum;
483 caddr_t entry;
484
485 dbg("processing main program's program header");
486 assert(aux_info[AT_PHDR] != NULL);
487 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
488 assert(aux_info[AT_PHNUM] != NULL);
489 phnum = aux_info[AT_PHNUM]->a_un.a_val;
490 assert(aux_info[AT_PHENT] != NULL);
491 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
492 assert(aux_info[AT_ENTRY] != NULL);
493 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
494 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
495 die();
496 }
497
498 char buf[MAXPATHLEN];
499 if (aux_info[AT_EXECPATH] != NULL) {
500 char *kexecpath;
501
502 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
503 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
504 if (kexecpath[0] == '/')
505 obj_main->path = kexecpath;
506 else if (getcwd(buf, sizeof(buf)) == NULL ||
507 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
508 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
509 obj_main->path = xstrdup(argv0);
510 else
511 obj_main->path = xstrdup(buf);
512 } else {
513 char resolved[MAXPATHLEN];
514 dbg("No AT_EXECPATH");
515 if (argv0[0] == '/') {
516 if (realpath(argv0, resolved) != NULL)
517 obj_main->path = xstrdup(resolved);
518 else
519 obj_main->path = xstrdup(argv0);
520 } else {
521 if (getcwd(buf, sizeof(buf)) != NULL
522 && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
523 && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
524 && access(buf, R_OK) == 0
525 && realpath(buf, resolved) != NULL)
526 obj_main->path = xstrdup(resolved);
527 else
528 obj_main->path = xstrdup(argv0);
529 }
530 }
531 dbg("obj_main path %s", obj_main->path);
532 obj_main->mainprog = true;
533
534 if (aux_info[AT_STACKPROT] != NULL &&
535 aux_info[AT_STACKPROT]->a_un.a_val != 0)
536 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
537
538 /*
539 * Get the actual dynamic linker pathname from the executable if
540 * possible. (It should always be possible.) That ensures that
541 * gdb will find the right dynamic linker even if a non-standard
542 * one is being used.
543 */
544 if (obj_main->interp != NULL &&
545 strcmp(obj_main->interp, obj_rtld.path) != 0) {
546 free(obj_rtld.path);
547 obj_rtld.path = xstrdup(obj_main->interp);
548 __progname = obj_rtld.path;
549 }
550
551 digest_dynamic(obj_main, 0);
552 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
553 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
554 obj_main->dynsymcount);
555
556 linkmap_add(obj_main);
557 linkmap_add(&obj_rtld);
558
559 /* Link the main program into the list of objects. */
560 *obj_tail = obj_main;
561 obj_tail = &obj_main->next;
562 obj_count++;
563 obj_loads++;
564
565 /* Initialize a fake symbol for resolving undefined weak references. */
566 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
567 sym_zero.st_shndx = SHN_UNDEF;
568 sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
569
570 if (!libmap_disable)
571 libmap_disable = (bool)lm_init(libmap_override);
572
573 dbg("loading LD_PRELOAD libraries");
574 if (load_preload_objects() == -1)
575 die();
576 preload_tail = obj_tail;
577
578 dbg("loading needed objects");
579 if (load_needed_objects(obj_main, 0) == -1)
580 die();
581
582 /* Make a list of all objects loaded at startup. */
583 last_interposer = obj_main;
584 for (obj = obj_list; obj != NULL; obj = obj->next) {
585 if (obj->z_interpose && obj != obj_main) {
586 objlist_put_after(&list_main, last_interposer, obj);
587 last_interposer = obj;
588 } else {
589 objlist_push_tail(&list_main, obj);
590 }
591 obj->refcount++;
592 }
593
594 dbg("checking for required versions");
595 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
596 die();
597
598 resident_skip1:
599
600 if (ld_tracing) { /* We're done */
601 trace_loaded_objects(obj_main);
602 exit(0);
603 }
604
605 if (ld_resident) /* XXX clean this up! */
606 goto resident_skip2;
607
608 if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
609 dump_relocations(obj_main);
610 exit (0);
611 }
612
613 /* setup TLS for main thread */
614 dbg("initializing initial thread local storage");
615 STAILQ_FOREACH(entry, &list_main, link) {
616 /*
617 * Allocate all the initial objects out of the static TLS
618 * block even if they didn't ask for it.
619 */
620 allocate_tls_offset(entry->obj);
621 }
622
623 /*
624 * Calculate the size of the TLS static segment. This is allocated
625 * for every thread. Generally make it page-aligned for efficiency,
626 * but take into account the fact that the actual allocation also
627 * includes room for the struct tls_tcb header.
628 */
629 {
630 ssize_t space;
631 ssize_t extra;
632
633 extra = __getstatictlsextra();
634 space = tls_last_offset + extra + sizeof(struct tls_tcb);
635 space = (space + PAGE_SIZE - 1) & ~((ssize_t)PAGE_SIZE - 1);
636
637 tls_static_space = (size_t)space - sizeof(struct tls_tcb);
638 }
639
640 /*
641 * Do not try to allocate the TLS here, let libc do it itself.
642 * (crt1 for the program will call _init_tls())
643 */
644
645 if (relocate_objects(obj_main,
646 ld_bind_now != NULL && *ld_bind_now != '\0',
647 &obj_rtld, SYMLOOK_EARLY, NULL) == -1)
648 die();
649
650 dbg("doing copy relocations");
651 if (do_copy_relocations(obj_main) == -1)
652 die();
653
654 resident_skip2:
655
656 if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
657 if (exec_sys_unregister(-1) < 0) {
658 dbg("exec_sys_unregister failed %d\n", errno);
659 exit(errno);
660 }
661 dbg("exec_sys_unregister success\n");
662 exit(0);
663 }
664
665 if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
666 dump_relocations(obj_main);
667 exit (0);
668 }
669
670 dbg("initializing key program variables");
671 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
672 set_program_var("environ", env);
673 set_program_var("__elf_aux_vector", aux);
674
675 if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
676 extern void resident_start(void);
677 ld_resident = 1;
678 if (exec_sys_register(resident_start) < 0) {
679 dbg("exec_sys_register failed %d\n", errno);
680 exit(errno);
681 }
682 dbg("exec_sys_register success\n");
683 exit(0);
684 }
685
686 /* Make a list of init functions to call. */
687 objlist_init(&initlist);
688 initlist_add_objects(obj_list, preload_tail, &initlist);
689
690 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
691
692 map_stacks_exec(NULL);
693
694 dbg("resolving ifuncs");
695 {
696 RtldLockState lockstate;
697
698 wlock_acquire(rtld_bind_lock, &lockstate);
699 if (resolve_objects_ifunc(
700 obj_main,
701 (ld_bind_now != NULL && *ld_bind_now != '\0'),
702 SYMLOOK_EARLY,
703 &lockstate) == -1) {
704 die();
705 }
706 lock_release(rtld_bind_lock, &lockstate);
707 }
708
709 /*
710 * Do NOT call the initlist here, give libc a chance to set up
711 * the initial TLS segment. crt1 will then call _rtld_call_init().
712 */
713
714 dbg("transferring control to program entry point = %p", obj_main->entry);
715
716 /* Return the exit procedure and the program entry point. */
717 *exit_proc = rtld_exit;
718 *objp = obj_main;
719 return (func_ptr_type) obj_main->entry;
720 }
721
722 /*
723 * Call the initialization list for dynamically loaded libraries.
724 * (called from crt1.c).
725 */
726 void
_rtld_call_init(void)727 _rtld_call_init(void)
728 {
729 RtldLockState lockstate;
730 Obj_Entry *obj;
731
732 if (!obj_main->note_present && obj_main->valid_hash_gnu) {
733 /*
734 * The use of a linker script with a PHDRS directive that does not include
735 * PT_NOTE will block the crt_no_init note. In this case we'll look for the
736 * recently added GNU hash dynamic tag which gets built by default. It is
737 * extremely unlikely to find a pre-3.1 binary without a PT_NOTE header and
738 * a gnu hash tag. If gnu hash found, consider binary to use new crt code.
739 */
740 obj_main->crt_no_init = true;
741 dbg("Setting crt_no_init without presence of PT_NOTE header");
742 }
743
744 wlock_acquire(rtld_bind_lock, &lockstate);
745 if (obj_main->crt_no_init)
746 preinit_main();
747 else {
748 /*
749 * Make sure we don't call the main program's init and fini functions
750 * for binaries linked with old crt1 which calls _init itself.
751 */
752 obj_main->init = obj_main->fini = (Elf_Addr)NULL;
753 obj_main->init_array = obj_main->fini_array = (Elf_Addr)NULL;
754 }
755 objlist_call_init(&initlist, &lockstate);
756 _r_debug_postinit(&obj_main->linkmap);
757 objlist_clear(&initlist);
758 dbg("loading filtees");
759 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
760 if (ld_loadfltr || obj->z_loadfltr)
761 load_filtees(obj, 0, &lockstate);
762 }
763 lock_release(rtld_bind_lock, &lockstate);
764 }
765
766 void *
rtld_resolve_ifunc(const Obj_Entry * obj,const Elf_Sym * def)767 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
768 {
769 void *ptr;
770 Elf_Addr target;
771
772 ptr = (void *)make_function_pointer(def, obj);
773 target = ((Elf_Addr (*)(void))ptr)();
774 return ((void *)target);
775 }
776
777 Elf_Addr
_rtld_bind(Obj_Entry * obj,Elf_Size reloff,void * stack)778 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
779 {
780 const Elf_Rel *rel;
781 const Elf_Sym *def;
782 const Obj_Entry *defobj;
783 Elf_Addr *where;
784 Elf_Addr target;
785 RtldLockState lockstate;
786
787 rlock_acquire(rtld_bind_lock, &lockstate);
788 if (sigsetjmp(lockstate.env, 0) != 0)
789 lock_upgrade(rtld_bind_lock, &lockstate);
790 if (obj->pltrel)
791 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
792 else
793 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
794
795 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
796 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
797 &lockstate);
798 if (def == NULL)
799 die();
800 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
801 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
802 else
803 target = (Elf_Addr)(defobj->relocbase + def->st_value);
804
805 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
806 defobj->strtab + def->st_name, basename(obj->path),
807 (void *)target, basename(defobj->path));
808
809 /*
810 * If we have a function call tracing hook, and the
811 * hook would like to keep tracing this one function,
812 * prevent the relocation so we will wind up here
813 * the next time again.
814 *
815 * We don't want to functrace calls from the functracer
816 * to avoid recursive loops.
817 */
818 if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
819 if (rtld_functrace(obj->path,
820 defobj->path,
821 defobj->strtab + def->st_name,
822 stack)) {
823 lock_release(rtld_bind_lock, &lockstate);
824 return target;
825 }
826 }
827
828 /*
829 * Write the new contents for the jmpslot. Note that depending on
830 * architecture, the value which we need to return back to the
831 * lazy binding trampoline may or may not be the target
832 * address. The value returned from reloc_jmpslot() is the value
833 * that the trampoline needs.
834 */
835 target = reloc_jmpslot(where, target, defobj, obj, rel);
836 lock_release(rtld_bind_lock, &lockstate);
837 return target;
838 }
839
840 /*
841 * Error reporting function. Use it like printf. If formats the message
842 * into a buffer, and sets things up so that the next call to dlerror()
843 * will return the message.
844 */
845 void
_rtld_error(const char * fmt,...)846 _rtld_error(const char *fmt, ...)
847 {
848 static char buf[512];
849 va_list ap;
850
851 va_start(ap, fmt);
852 rtld_vsnprintf(buf, sizeof buf, fmt, ap);
853 error_message = buf;
854 va_end(ap);
855 }
856
857 /*
858 * Return a dynamically-allocated copy of the current error message, if any.
859 */
860 static char *
errmsg_save(void)861 errmsg_save(void)
862 {
863 return error_message == NULL ? NULL : xstrdup(error_message);
864 }
865
866 /*
867 * Restore the current error message from a copy which was previously saved
868 * by errmsg_save(). The copy is freed.
869 */
870 static void
errmsg_restore(char * saved_msg)871 errmsg_restore(char *saved_msg)
872 {
873 if (saved_msg == NULL)
874 error_message = NULL;
875 else {
876 _rtld_error("%s", saved_msg);
877 free(saved_msg);
878 }
879 }
880
881 const char *
basename(const char * name)882 basename(const char *name)
883 {
884 const char *p = strrchr(name, '/');
885 return p != NULL ? p + 1 : name;
886 }
887
888 static struct utsname uts;
889
890 static char *
origin_subst_one(char * real,const char * kw,const char * subst,bool may_free)891 origin_subst_one(char *real, const char *kw, const char *subst,
892 bool may_free)
893 {
894 char *p, *p1, *res, *resp;
895 int subst_len, kw_len, subst_count, old_len, new_len;
896
897 kw_len = strlen(kw);
898
899 /*
900 * First, count the number of the keyword occurrences, to
901 * preallocate the final string.
902 */
903 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
904 p1 = strstr(p, kw);
905 if (p1 == NULL)
906 break;
907 }
908
909 /*
910 * If the keyword is not found, just return.
911 */
912 if (subst_count == 0)
913 return (may_free ? real : xstrdup(real));
914
915 /*
916 * There is indeed something to substitute. Calculate the
917 * length of the resulting string, and allocate it.
918 */
919 subst_len = strlen(subst);
920 old_len = strlen(real);
921 new_len = old_len + (subst_len - kw_len) * subst_count;
922 res = xmalloc(new_len + 1);
923
924 /*
925 * Now, execute the substitution loop.
926 */
927 for (p = real, resp = res, *resp = '\0';;) {
928 p1 = strstr(p, kw);
929 if (p1 != NULL) {
930 /* Copy the prefix before keyword. */
931 memcpy(resp, p, p1 - p);
932 resp += p1 - p;
933 /* Keyword replacement. */
934 memcpy(resp, subst, subst_len);
935 resp += subst_len;
936 *resp = '\0';
937 p = p1 + kw_len;
938 } else
939 break;
940 }
941
942 /* Copy to the end of string and finish. */
943 strcat(resp, p);
944 if (may_free)
945 free(real);
946 return (res);
947 }
948
949 static char *
origin_subst(char * real,const char * origin_path)950 origin_subst(char *real, const char *origin_path)
951 {
952 char *res1, *res2, *res3, *res4;
953
954 if (uts.sysname[0] == '\0') {
955 if (uname(&uts) != 0) {
956 _rtld_error("utsname failed: %d", errno);
957 return (NULL);
958 }
959 }
960 res1 = origin_subst_one(real, "$ORIGIN", origin_path, false);
961 res2 = origin_subst_one(res1, "$OSNAME", uts.sysname, true);
962 res3 = origin_subst_one(res2, "$OSREL", uts.release, true);
963 res4 = origin_subst_one(res3, "$PLATFORM", uts.machine, true);
964 return (res4);
965 }
966
967 static void
die(void)968 die(void)
969 {
970 const char *msg = dlerror();
971
972 if (msg == NULL)
973 msg = "Fatal error";
974 rtld_fdputstr(STDERR_FILENO, msg);
975 rtld_fdputchar(STDERR_FILENO, '\n');
976 _exit(1);
977 }
978
979 /*
980 * Process a shared object's DYNAMIC section, and save the important
981 * information in its Obj_Entry structure.
982 */
983 static void
digest_dynamic1(Obj_Entry * obj,int early,const Elf_Dyn ** dyn_rpath,const Elf_Dyn ** dyn_soname,const Elf_Dyn ** dyn_runpath)984 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
985 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
986 {
987 const Elf_Dyn *dynp;
988 Needed_Entry **needed_tail = &obj->needed;
989 Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
990 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
991 const Elf_Hashelt *hashtab;
992 const Elf32_Word *hashval;
993 Elf32_Word bkt, nmaskwords;
994 int bloom_size32;
995 bool nmw_power2;
996 int plttype = DT_REL;
997
998 *dyn_rpath = NULL;
999 *dyn_soname = NULL;
1000 *dyn_runpath = NULL;
1001
1002 obj->bind_now = false;
1003 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
1004 switch (dynp->d_tag) {
1005
1006 case DT_REL:
1007 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
1008 break;
1009
1010 case DT_RELSZ:
1011 obj->relsize = dynp->d_un.d_val;
1012 break;
1013
1014 case DT_RELENT:
1015 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
1016 break;
1017
1018 case DT_JMPREL:
1019 obj->pltrel = (const Elf_Rel *)
1020 (obj->relocbase + dynp->d_un.d_ptr);
1021 break;
1022
1023 case DT_PLTRELSZ:
1024 obj->pltrelsize = dynp->d_un.d_val;
1025 break;
1026
1027 case DT_RELA:
1028 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
1029 break;
1030
1031 case DT_RELASZ:
1032 obj->relasize = dynp->d_un.d_val;
1033 break;
1034
1035 case DT_RELAENT:
1036 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
1037 break;
1038
1039 case DT_PLTREL:
1040 plttype = dynp->d_un.d_val;
1041 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
1042 break;
1043
1044 case DT_SYMTAB:
1045 obj->symtab = (const Elf_Sym *)
1046 (obj->relocbase + dynp->d_un.d_ptr);
1047 break;
1048
1049 case DT_SYMENT:
1050 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
1051 break;
1052
1053 case DT_STRTAB:
1054 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
1055 break;
1056
1057 case DT_STRSZ:
1058 obj->strsize = dynp->d_un.d_val;
1059 break;
1060
1061 case DT_VERNEED:
1062 obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1063 dynp->d_un.d_val);
1064 break;
1065
1066 case DT_VERNEEDNUM:
1067 obj->verneednum = dynp->d_un.d_val;
1068 break;
1069
1070 case DT_VERDEF:
1071 obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1072 dynp->d_un.d_val);
1073 break;
1074
1075 case DT_VERDEFNUM:
1076 obj->verdefnum = dynp->d_un.d_val;
1077 break;
1078
1079 case DT_VERSYM:
1080 obj->versyms = (const Elf_Versym *)(obj->relocbase +
1081 dynp->d_un.d_val);
1082 break;
1083
1084 case DT_HASH:
1085 {
1086 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1087 dynp->d_un.d_ptr);
1088 obj->nbuckets = hashtab[0];
1089 obj->nchains = hashtab[1];
1090 obj->buckets = hashtab + 2;
1091 obj->chains = obj->buckets + obj->nbuckets;
1092 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 &&
1093 obj->buckets != NULL;
1094 }
1095 break;
1096
1097 case DT_GNU_HASH:
1098 {
1099 hashtab = (const Elf_Hashelt *)(obj->relocbase +
1100 dynp->d_un.d_ptr);
1101 obj->nbuckets_gnu = hashtab[0];
1102 obj->symndx_gnu = hashtab[1];
1103 nmaskwords = hashtab[2];
1104 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords;
1105 /* Number of bitmask words is required to be power of 2 */
1106 nmw_power2 = powerof2(nmaskwords);
1107 obj->maskwords_bm_gnu = nmaskwords - 1;
1108 obj->shift2_gnu = hashtab[3];
1109 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4);
1110 obj->buckets_gnu = hashtab + 4 + bloom_size32;
1111 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu -
1112 obj->symndx_gnu;
1113 obj->valid_hash_gnu = nmw_power2 && obj->nbuckets_gnu > 0 &&
1114 obj->buckets_gnu != NULL;
1115 }
1116 break;
1117
1118 case DT_NEEDED:
1119 if (!obj->rtld) {
1120 Needed_Entry *nep = NEW(Needed_Entry);
1121 nep->name = dynp->d_un.d_val;
1122 nep->obj = NULL;
1123 nep->next = NULL;
1124
1125 *needed_tail = nep;
1126 needed_tail = &nep->next;
1127 }
1128 break;
1129
1130 case DT_FILTER:
1131 if (!obj->rtld) {
1132 Needed_Entry *nep = NEW(Needed_Entry);
1133 nep->name = dynp->d_un.d_val;
1134 nep->obj = NULL;
1135 nep->next = NULL;
1136
1137 *needed_filtees_tail = nep;
1138 needed_filtees_tail = &nep->next;
1139 }
1140 break;
1141
1142 case DT_AUXILIARY:
1143 if (!obj->rtld) {
1144 Needed_Entry *nep = NEW(Needed_Entry);
1145 nep->name = dynp->d_un.d_val;
1146 nep->obj = NULL;
1147 nep->next = NULL;
1148
1149 *needed_aux_filtees_tail = nep;
1150 needed_aux_filtees_tail = &nep->next;
1151 }
1152 break;
1153
1154 case DT_PLTGOT:
1155 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1156 break;
1157
1158 case DT_TEXTREL:
1159 obj->textrel = true;
1160 break;
1161
1162 case DT_SYMBOLIC:
1163 obj->symbolic = true;
1164 break;
1165
1166 case DT_RPATH:
1167 /*
1168 * We have to wait until later to process this, because we
1169 * might not have gotten the address of the string table yet.
1170 */
1171 *dyn_rpath = dynp;
1172 break;
1173
1174 case DT_SONAME:
1175 *dyn_soname = dynp;
1176 break;
1177
1178 case DT_RUNPATH:
1179 *dyn_runpath = dynp;
1180 break;
1181
1182 case DT_INIT:
1183 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1184 break;
1185
1186 case DT_PREINIT_ARRAY:
1187 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1188 break;
1189
1190 case DT_PREINIT_ARRAYSZ:
1191 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1192 break;
1193
1194 case DT_INIT_ARRAY:
1195 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1196 break;
1197
1198 case DT_INIT_ARRAYSZ:
1199 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1200 break;
1201
1202 case DT_FINI:
1203 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1204 break;
1205
1206 case DT_FINI_ARRAY:
1207 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1208 break;
1209
1210 case DT_FINI_ARRAYSZ:
1211 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1212 break;
1213
1214 case DT_DEBUG:
1215 /* XXX - not implemented yet */
1216 if (!early)
1217 dbg("Filling in DT_DEBUG entry");
1218 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1219 break;
1220
1221 case DT_FLAGS:
1222 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1223 obj->z_origin = true;
1224 if (dynp->d_un.d_val & DF_SYMBOLIC)
1225 obj->symbolic = true;
1226 if (dynp->d_un.d_val & DF_TEXTREL)
1227 obj->textrel = true;
1228 if (dynp->d_un.d_val & DF_BIND_NOW)
1229 obj->bind_now = true;
1230 if (dynp->d_un.d_val & DF_STATIC_TLS)
1231 obj->static_tls = true;
1232 break;
1233
1234 case DT_FLAGS_1:
1235 if (dynp->d_un.d_val & DF_1_NOOPEN)
1236 obj->z_noopen = true;
1237 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1238 obj->z_origin = true;
1239 /*if (dynp->d_un.d_val & DF_1_GLOBAL)
1240 XXX ;*/
1241 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1242 obj->bind_now = true;
1243 if (dynp->d_un.d_val & DF_1_NODELETE)
1244 obj->z_nodelete = true;
1245 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1246 obj->z_loadfltr = true;
1247 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1248 obj->z_interpose = true;
1249 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1250 obj->z_nodeflib = true;
1251 break;
1252
1253 default:
1254 if (!early) {
1255 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1256 (long)dynp->d_tag);
1257 }
1258 break;
1259 }
1260 }
1261
1262 obj->traced = false;
1263
1264 if (plttype == DT_RELA) {
1265 obj->pltrela = (const Elf_Rela *) obj->pltrel;
1266 obj->pltrel = NULL;
1267 obj->pltrelasize = obj->pltrelsize;
1268 obj->pltrelsize = 0;
1269 }
1270
1271 /* Determine size of dynsym table (equal to nchains of sysv hash) */
1272 if (obj->valid_hash_sysv)
1273 obj->dynsymcount = obj->nchains;
1274 else if (obj->valid_hash_gnu) {
1275 obj->dynsymcount = 0;
1276 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1277 if (obj->buckets_gnu[bkt] == 0)
1278 continue;
1279 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1280 do
1281 obj->dynsymcount++;
1282 while ((*hashval++ & 1u) == 0);
1283 }
1284 obj->dynsymcount += obj->symndx_gnu;
1285 }
1286 }
1287
1288 static void
digest_dynamic2(Obj_Entry * obj,const Elf_Dyn * dyn_rpath,const Elf_Dyn * dyn_soname,const Elf_Dyn * dyn_runpath)1289 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1290 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1291 {
1292
1293 if (obj->z_origin && obj->origin_path == NULL) {
1294 obj->origin_path = xmalloc(PATH_MAX);
1295 if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1296 die();
1297 }
1298
1299 if (dyn_runpath != NULL) {
1300 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val;
1301 if (obj->z_origin)
1302 obj->runpath = origin_subst(obj->runpath, obj->origin_path);
1303 }
1304 else if (dyn_rpath != NULL) {
1305 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1306 if (obj->z_origin)
1307 obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1308 }
1309
1310 if (dyn_soname != NULL)
1311 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1312 }
1313
1314 static void
digest_dynamic(Obj_Entry * obj,int early)1315 digest_dynamic(Obj_Entry *obj, int early)
1316 {
1317 const Elf_Dyn *dyn_rpath;
1318 const Elf_Dyn *dyn_soname;
1319 const Elf_Dyn *dyn_runpath;
1320
1321 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1322 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1323 }
1324
1325 /*
1326 * Process a shared object's program header. This is used only for the
1327 * main program, when the kernel has already loaded the main program
1328 * into memory before calling the dynamic linker. It creates and
1329 * returns an Obj_Entry structure.
1330 */
1331 static Obj_Entry *
digest_phdr(const Elf_Phdr * phdr,int phnum,caddr_t entry,const char * path)1332 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1333 {
1334 Obj_Entry *obj;
1335 const Elf_Phdr *phlimit = phdr + phnum;
1336 const Elf_Phdr *ph;
1337 Elf_Addr note_start, note_end;
1338 int nsegs = 0;
1339
1340 obj = obj_new();
1341 for (ph = phdr; ph < phlimit; ph++) {
1342 if (ph->p_type != PT_PHDR)
1343 continue;
1344
1345 obj->phdr = phdr;
1346 obj->phsize = ph->p_memsz;
1347 obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1348 break;
1349 }
1350
1351 obj->stack_flags = PF_X | PF_R | PF_W;
1352
1353 for (ph = phdr; ph < phlimit; ph++) {
1354 switch (ph->p_type) {
1355
1356 case PT_INTERP:
1357 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1358 break;
1359
1360 case PT_LOAD:
1361 if (nsegs == 0) { /* First load segment */
1362 obj->vaddrbase = trunc_page(ph->p_vaddr);
1363 obj->mapbase = obj->vaddrbase + obj->relocbase;
1364 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1365 obj->vaddrbase;
1366 } else { /* Last load segment */
1367 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1368 obj->vaddrbase;
1369 }
1370 nsegs++;
1371 break;
1372
1373 case PT_DYNAMIC:
1374 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1375 break;
1376
1377 case PT_TLS:
1378 obj->tlsindex = 1;
1379 obj->tlssize = ph->p_memsz;
1380 obj->tlsalign = ph->p_align;
1381 obj->tlsinitsize = ph->p_filesz;
1382 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1383 break;
1384
1385 case PT_GNU_STACK:
1386 obj->stack_flags = ph->p_flags;
1387 break;
1388
1389 case PT_GNU_RELRO:
1390 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1391 obj->relro_size = round_page(ph->p_memsz);
1392 break;
1393
1394 case PT_NOTE:
1395 obj->note_present = true;
1396 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1397 note_end = note_start + ph->p_filesz;
1398 digest_notes(obj, note_start, note_end);
1399 break;
1400 }
1401 }
1402 if (nsegs < 1) {
1403 _rtld_error("%s: too few PT_LOAD segments", path);
1404 return NULL;
1405 }
1406
1407 obj->entry = entry;
1408 return obj;
1409 }
1410
1411 void
digest_notes(Obj_Entry * obj,Elf_Addr note_start,Elf_Addr note_end)1412 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1413 {
1414 const Elf_Note *note;
1415 const char *note_name;
1416 uintptr_t p;
1417
1418 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1419 note = (const Elf_Note *)((const char *)(note + 1) +
1420 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1421 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1422 if (note->n_namesz != sizeof(NOTE_VENDOR) ||
1423 note->n_descsz != sizeof(int32_t))
1424 continue;
1425 if (note->n_type != ABI_NOTETYPE &&
1426 note->n_type != CRT_NOINIT_NOTETYPE)
1427 continue;
1428 note_name = (const char *)(note + 1);
1429 if (strncmp(NOTE_VENDOR, note_name, sizeof(NOTE_VENDOR)) != 0)
1430 continue;
1431 switch (note->n_type) {
1432 case ABI_NOTETYPE:
1433 /* DragonFly osrel note */
1434 p = (uintptr_t)(note + 1);
1435 p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1436 obj->osrel = *(const int32_t *)(p);
1437 dbg("note osrel %d", obj->osrel);
1438 break;
1439 case CRT_NOINIT_NOTETYPE:
1440 /* DragonFly 'crt does not call init' note */
1441 obj->crt_no_init = true;
1442 dbg("note crt_no_init");
1443 break;
1444 }
1445 }
1446 }
1447
1448 static Obj_Entry *
dlcheck(void * handle)1449 dlcheck(void *handle)
1450 {
1451 Obj_Entry *obj;
1452
1453 for (obj = obj_list; obj != NULL; obj = obj->next)
1454 if (obj == (Obj_Entry *) handle)
1455 break;
1456
1457 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1458 _rtld_error("Invalid shared object handle %p", handle);
1459 return NULL;
1460 }
1461 return obj;
1462 }
1463
1464 /*
1465 * If the given object is already in the donelist, return true. Otherwise
1466 * add the object to the list and return false.
1467 */
1468 static bool
donelist_check(DoneList * dlp,const Obj_Entry * obj)1469 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1470 {
1471 unsigned int i;
1472
1473 for (i = 0; i < dlp->num_used; i++)
1474 if (dlp->objs[i] == obj)
1475 return true;
1476 /*
1477 * Our donelist allocation should always be sufficient. But if
1478 * our threads locking isn't working properly, more shared objects
1479 * could have been loaded since we allocated the list. That should
1480 * never happen, but we'll handle it properly just in case it does.
1481 */
1482 if (dlp->num_used < dlp->num_alloc)
1483 dlp->objs[dlp->num_used++] = obj;
1484 return false;
1485 }
1486
1487 /*
1488 * Hash function for symbol table lookup. Don't even think about changing
1489 * this. It is specified by the System V ABI.
1490 */
1491 unsigned long
elf_hash(const char * name)1492 elf_hash(const char *name)
1493 {
1494 const unsigned char *p = (const unsigned char *) name;
1495 unsigned long h = 0;
1496 unsigned long g;
1497
1498 while (*p != '\0') {
1499 h = (h << 4) + *p++;
1500 if ((g = h & 0xf0000000) != 0)
1501 h ^= g >> 24;
1502 h &= ~g;
1503 }
1504 return h;
1505 }
1506
1507 /*
1508 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1509 * unsigned in case it's implemented with a wider type.
1510 */
1511 static uint_fast32_t
gnu_hash(const char * s)1512 gnu_hash(const char *s)
1513 {
1514 uint_fast32_t h;
1515 unsigned char c;
1516
1517 h = 5381;
1518 for (c = *s; c != '\0'; c = *++s)
1519 h = h * 33 + c;
1520 return (h & 0xffffffff);
1521 }
1522
1523
1524 /*
1525 * Find the library with the given name, and return its full pathname.
1526 * The returned string is dynamically allocated. Generates an error
1527 * message and returns NULL if the library cannot be found.
1528 *
1529 * If the second argument is non-NULL, then it refers to an already-
1530 * loaded shared object, whose library search path will be searched.
1531 *
1532 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1533 * descriptor (which is close-on-exec) will be passed out via the third
1534 * argument.
1535 *
1536 * The search order is:
1537 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1538 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1539 * LD_LIBRARY_PATH
1540 * DT_RUNPATH in the referencing file
1541 * ldconfig hints (if -z nodefaultlib, filter out default library directories
1542 * from list)
1543 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1544 *
1545 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1546 */
1547 static char *
find_library(const char * xname,const Obj_Entry * refobj,int * fdp)1548 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1549 {
1550 char *pathname;
1551 char *name;
1552 bool nodeflib, objgiven;
1553
1554 objgiven = refobj != NULL;
1555 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */
1556 if (xname[0] != '/' && !trust) {
1557 _rtld_error("Absolute pathname required for shared object \"%s\"",
1558 xname);
1559 return NULL;
1560 }
1561 if (objgiven && refobj->z_origin) {
1562 return (origin_subst(__DECONST(char *, xname),
1563 refobj->origin_path));
1564 } else {
1565 return (xstrdup(xname));
1566 }
1567 }
1568
1569 if (libmap_disable || !objgiven ||
1570 (name = lm_find(refobj->path, xname)) == NULL)
1571 name = (char *)xname;
1572
1573 dbg(" Searching for \"%s\"", name);
1574
1575 nodeflib = objgiven ? refobj->z_nodeflib : false;
1576 if ((objgiven &&
1577 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1578 (objgiven && refobj->runpath == NULL && refobj != obj_main &&
1579 (pathname = search_library_path(name, obj_main->rpath)) != NULL) ||
1580 (pathname = search_library_path(name, ld_library_path)) != NULL ||
1581 (objgiven &&
1582 (pathname = search_library_path(name, refobj->runpath)) != NULL) ||
1583 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL ||
1584 (pathname = search_library_path(name, gethints(nodeflib))) != NULL ||
1585 (objgiven && !nodeflib &&
1586 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL))
1587 return (pathname);
1588
1589 if (objgiven && refobj->path != NULL) {
1590 _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1591 name, basename(refobj->path));
1592 } else {
1593 _rtld_error("Shared object \"%s\" not found", name);
1594 }
1595 return NULL;
1596 }
1597
1598 /*
1599 * Given a symbol number in a referencing object, find the corresponding
1600 * definition of the symbol. Returns a pointer to the symbol, or NULL if
1601 * no definition was found. Returns a pointer to the Obj_Entry of the
1602 * defining object via the reference parameter DEFOBJ_OUT.
1603 */
1604 const Elf_Sym *
find_symdef(unsigned long symnum,const Obj_Entry * refobj,const Obj_Entry ** defobj_out,int flags,SymCache * cache,RtldLockState * lockstate)1605 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1606 const Obj_Entry **defobj_out, int flags, SymCache *cache,
1607 RtldLockState *lockstate)
1608 {
1609 const Elf_Sym *ref;
1610 const Elf_Sym *def;
1611 const Obj_Entry *defobj;
1612 SymLook req;
1613 const char *name;
1614 int res;
1615
1616 /*
1617 * If we have already found this symbol, get the information from
1618 * the cache.
1619 */
1620 if (symnum >= refobj->dynsymcount)
1621 return NULL; /* Bad object */
1622 if (cache != NULL && cache[symnum].sym != NULL) {
1623 *defobj_out = cache[symnum].obj;
1624 return cache[symnum].sym;
1625 }
1626
1627 ref = refobj->symtab + symnum;
1628 name = refobj->strtab + ref->st_name;
1629 def = NULL;
1630 defobj = NULL;
1631
1632 /*
1633 * We don't have to do a full scale lookup if the symbol is local.
1634 * We know it will bind to the instance in this load module; to
1635 * which we already have a pointer (ie ref). By not doing a lookup,
1636 * we not only improve performance, but it also avoids unresolvable
1637 * symbols when local symbols are not in the hash table.
1638 *
1639 * This might occur for TLS module relocations, which simply use
1640 * symbol 0.
1641 */
1642 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1643 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1644 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1645 symnum);
1646 }
1647 symlook_init(&req, name);
1648 req.flags = flags;
1649 req.ventry = fetch_ventry(refobj, symnum);
1650 req.lockstate = lockstate;
1651 res = symlook_default(&req, refobj);
1652 if (res == 0) {
1653 def = req.sym_out;
1654 defobj = req.defobj_out;
1655 }
1656 } else {
1657 def = ref;
1658 defobj = refobj;
1659 }
1660
1661 /*
1662 * If we found no definition and the reference is weak, treat the
1663 * symbol as having the value zero.
1664 */
1665 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1666 def = &sym_zero;
1667 defobj = obj_main;
1668 }
1669
1670 if (def != NULL) {
1671 *defobj_out = defobj;
1672 /* Record the information in the cache to avoid subsequent lookups. */
1673 if (cache != NULL) {
1674 cache[symnum].sym = def;
1675 cache[symnum].obj = defobj;
1676 }
1677 } else {
1678 if (refobj != &obj_rtld)
1679 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1680 }
1681 return def;
1682 }
1683
1684 /*
1685 * Return the search path from the ldconfig hints file, reading it if
1686 * necessary. If nostdlib is true, then the default search paths are
1687 * not added to result.
1688 *
1689 * Returns NULL if there are problems with the hints file,
1690 * or if the search path there is empty.
1691 */
1692 static const char *
gethints(bool nostdlib)1693 gethints(bool nostdlib)
1694 {
1695 static char *hints, *filtered_path;
1696 struct elfhints_hdr hdr;
1697 struct fill_search_info_args sargs, hargs;
1698 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1699 struct dl_serpath *SLPpath, *hintpath;
1700 char *p;
1701 unsigned int SLPndx, hintndx, fndx, fcount;
1702 int fd;
1703 size_t flen;
1704 bool skip;
1705
1706 /* First call, read the hints file */
1707 if (hints == NULL) {
1708 /* Keep from trying again in case the hints file is bad. */
1709 hints = "";
1710
1711 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1712 return (NULL);
1713 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1714 hdr.magic != ELFHINTS_MAGIC ||
1715 hdr.version != 1) {
1716 close(fd);
1717 return (NULL);
1718 }
1719 p = xmalloc(hdr.dirlistlen + 1);
1720 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1721 read(fd, p, hdr.dirlistlen + 1) !=
1722 (ssize_t)hdr.dirlistlen + 1) {
1723 free(p);
1724 close(fd);
1725 return (NULL);
1726 }
1727 hints = p;
1728 close(fd);
1729 }
1730
1731 /*
1732 * If caller agreed to receive list which includes the default
1733 * paths, we are done. Otherwise, if we still have not
1734 * calculated filtered result, do it now.
1735 */
1736 if (!nostdlib)
1737 return (hints[0] != '\0' ? hints : NULL);
1738 if (filtered_path != NULL)
1739 goto filt_ret;
1740
1741 /*
1742 * Obtain the list of all configured search paths, and the
1743 * list of the default paths.
1744 *
1745 * First estimate the size of the results.
1746 */
1747 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1748 smeta.dls_cnt = 0;
1749 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1750 hmeta.dls_cnt = 0;
1751
1752 sargs.request = RTLD_DI_SERINFOSIZE;
1753 sargs.serinfo = &smeta;
1754 hargs.request = RTLD_DI_SERINFOSIZE;
1755 hargs.serinfo = &hmeta;
1756
1757 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1758 path_enumerate(p, fill_search_info, &hargs);
1759
1760 SLPinfo = xmalloc(smeta.dls_size);
1761 hintinfo = xmalloc(hmeta.dls_size);
1762
1763 /*
1764 * Next fetch both sets of paths.
1765 */
1766 sargs.request = RTLD_DI_SERINFO;
1767 sargs.serinfo = SLPinfo;
1768 sargs.serpath = &SLPinfo->dls_serpath[0];
1769 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1770
1771 hargs.request = RTLD_DI_SERINFO;
1772 hargs.serinfo = hintinfo;
1773 hargs.serpath = &hintinfo->dls_serpath[0];
1774 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1775
1776 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &sargs);
1777 path_enumerate(p, fill_search_info, &hargs);
1778
1779 /*
1780 * Now calculate the difference between two sets, by excluding
1781 * standard paths from the full set.
1782 */
1783 fndx = 0;
1784 fcount = 0;
1785 filtered_path = xmalloc(hdr.dirlistlen + 1);
1786 hintpath = &hintinfo->dls_serpath[0];
1787 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1788 skip = false;
1789 SLPpath = &SLPinfo->dls_serpath[0];
1790 /*
1791 * Check each standard path against current.
1792 */
1793 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1794 /* matched, skip the path */
1795 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1796 skip = true;
1797 break;
1798 }
1799 }
1800 if (skip)
1801 continue;
1802 /*
1803 * Not matched against any standard path, add the path
1804 * to result. Separate consecutive paths with ':'.
1805 */
1806 if (fcount > 0) {
1807 filtered_path[fndx] = ':';
1808 fndx++;
1809 }
1810 fcount++;
1811 flen = strlen(hintpath->dls_name);
1812 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1813 fndx += flen;
1814 }
1815 filtered_path[fndx] = '\0';
1816
1817 free(SLPinfo);
1818 free(hintinfo);
1819
1820 filt_ret:
1821 return (filtered_path[0] != '\0' ? filtered_path : NULL);
1822 }
1823
1824 static void
init_dag(Obj_Entry * root)1825 init_dag(Obj_Entry *root)
1826 {
1827 const Needed_Entry *needed;
1828 const Objlist_Entry *elm;
1829 DoneList donelist;
1830
1831 if (root->dag_inited)
1832 return;
1833 donelist_init(&donelist);
1834
1835 /* Root object belongs to own DAG. */
1836 objlist_push_tail(&root->dldags, root);
1837 objlist_push_tail(&root->dagmembers, root);
1838 donelist_check(&donelist, root);
1839
1840 /*
1841 * Add dependencies of root object to DAG in breadth order
1842 * by exploiting the fact that each new object get added
1843 * to the tail of the dagmembers list.
1844 */
1845 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1846 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1847 if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1848 continue;
1849 objlist_push_tail(&needed->obj->dldags, root);
1850 objlist_push_tail(&root->dagmembers, needed->obj);
1851 }
1852 }
1853 root->dag_inited = true;
1854 }
1855
1856 static void
process_nodelete(Obj_Entry * root)1857 process_nodelete(Obj_Entry *root)
1858 {
1859 const Objlist_Entry *elm;
1860
1861 /*
1862 * Walk over object DAG and process every dependent object that
1863 * is marked as DF_1_NODELETE. They need to grow their own DAG,
1864 * which then should have its reference upped separately.
1865 */
1866 STAILQ_FOREACH(elm, &root->dagmembers, link) {
1867 if (elm->obj != NULL && elm->obj->z_nodelete &&
1868 !elm->obj->ref_nodel) {
1869 dbg("obj %s nodelete", elm->obj->path);
1870 init_dag(elm->obj);
1871 ref_dag(elm->obj);
1872 elm->obj->ref_nodel = true;
1873 }
1874 }
1875 }
1876
1877 /*
1878 * Initialize the dynamic linker. The argument is the address at which
1879 * the dynamic linker has been mapped into memory. The primary task of
1880 * this function is to relocate the dynamic linker.
1881 */
1882 static void
init_rtld(caddr_t mapbase,Elf_Auxinfo ** aux_info)1883 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1884 {
1885 Obj_Entry objtmp; /* Temporary rtld object */
1886 const Elf_Ehdr *ehdr;
1887 const Elf_Dyn *dyn_rpath;
1888 const Elf_Dyn *dyn_soname;
1889 const Elf_Dyn *dyn_runpath;
1890
1891 /*
1892 * Conjure up an Obj_Entry structure for the dynamic linker.
1893 *
1894 * The "path" member can't be initialized yet because string constants
1895 * cannot yet be accessed. Below we will set it correctly.
1896 */
1897 memset(&objtmp, 0, sizeof(objtmp));
1898 objtmp.path = NULL;
1899 objtmp.rtld = true;
1900 objtmp.mapbase = mapbase;
1901 #ifdef PIC
1902 objtmp.relocbase = mapbase;
1903 #endif
1904 if (RTLD_IS_DYNAMIC()) {
1905 objtmp.dynamic = rtld_dynamic(&objtmp);
1906 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
1907 assert(objtmp.needed == NULL);
1908 assert(!objtmp.textrel);
1909
1910 /*
1911 * Temporarily put the dynamic linker entry into the object list, so
1912 * that symbols can be found.
1913 */
1914
1915 relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1916 }
1917 ehdr = (Elf_Ehdr *)mapbase;
1918 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
1919 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
1920
1921 /* Initialize the object list. */
1922 obj_tail = &obj_list;
1923
1924 /* Now that non-local variables can be accesses, copy out obj_rtld. */
1925 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1926
1927 #ifdef ENABLE_OSRELDATE
1928 if (aux_info[AT_OSRELDATE] != NULL)
1929 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1930 #endif
1931
1932 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
1933
1934 /* Replace the path with a dynamically allocated copy. */
1935 obj_rtld.path = xstrdup(PATH_RTLD);
1936
1937 r_debug.r_brk = r_debug_state;
1938 r_debug.r_state = RT_CONSISTENT;
1939 }
1940
1941 /*
1942 * Add the init functions from a needed object list (and its recursive
1943 * needed objects) to "list". This is not used directly; it is a helper
1944 * function for initlist_add_objects(). The write lock must be held
1945 * when this function is called.
1946 */
1947 static void
initlist_add_neededs(Needed_Entry * needed,Objlist * list)1948 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1949 {
1950 /* Recursively process the successor needed objects. */
1951 if (needed->next != NULL)
1952 initlist_add_neededs(needed->next, list);
1953
1954 /* Process the current needed object. */
1955 if (needed->obj != NULL)
1956 initlist_add_objects(needed->obj, &needed->obj->next, list);
1957 }
1958
1959 /*
1960 * Scan all of the DAGs rooted in the range of objects from "obj" to
1961 * "tail" and add their init functions to "list". This recurses over
1962 * the DAGs and ensure the proper init ordering such that each object's
1963 * needed libraries are initialized before the object itself. At the
1964 * same time, this function adds the objects to the global finalization
1965 * list "list_fini" in the opposite order. The write lock must be
1966 * held when this function is called.
1967 */
1968 static void
initlist_add_objects(Obj_Entry * obj,Obj_Entry ** tail,Objlist * list)1969 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1970 {
1971
1972 if (obj->init_scanned || obj->init_done)
1973 return;
1974 obj->init_scanned = true;
1975
1976 /* Recursively process the successor objects. */
1977 if (&obj->next != tail)
1978 initlist_add_objects(obj->next, tail, list);
1979
1980 /* Recursively process the needed objects. */
1981 if (obj->needed != NULL)
1982 initlist_add_neededs(obj->needed, list);
1983 if (obj->needed_filtees != NULL)
1984 initlist_add_neededs(obj->needed_filtees, list);
1985 if (obj->needed_aux_filtees != NULL)
1986 initlist_add_neededs(obj->needed_aux_filtees, list);
1987
1988 /* Add the object to the init list. */
1989 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1990 obj->init_array != (Elf_Addr)NULL)
1991 objlist_push_tail(list, obj);
1992
1993 /* Add the object to the global fini list in the reverse order. */
1994 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1995 && !obj->on_fini_list) {
1996 objlist_push_head(&list_fini, obj);
1997 obj->on_fini_list = true;
1998 }
1999 }
2000
2001 #ifndef FPTR_TARGET
2002 #define FPTR_TARGET(f) ((Elf_Addr) (f))
2003 #endif
2004
2005 static void
free_needed_filtees(Needed_Entry * n)2006 free_needed_filtees(Needed_Entry *n)
2007 {
2008 Needed_Entry *needed, *needed1;
2009
2010 for (needed = n; needed != NULL; needed = needed->next) {
2011 if (needed->obj != NULL) {
2012 dlclose(needed->obj);
2013 needed->obj = NULL;
2014 }
2015 }
2016 for (needed = n; needed != NULL; needed = needed1) {
2017 needed1 = needed->next;
2018 free(needed);
2019 }
2020 }
2021
2022 static void
unload_filtees(Obj_Entry * obj)2023 unload_filtees(Obj_Entry *obj)
2024 {
2025
2026 free_needed_filtees(obj->needed_filtees);
2027 obj->needed_filtees = NULL;
2028 free_needed_filtees(obj->needed_aux_filtees);
2029 obj->needed_aux_filtees = NULL;
2030 obj->filtees_loaded = false;
2031 }
2032
2033 static void
load_filtee1(Obj_Entry * obj,Needed_Entry * needed,int flags,RtldLockState * lockstate)2034 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2035 RtldLockState *lockstate)
2036 {
2037
2038 for (; needed != NULL; needed = needed->next) {
2039 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2040 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2041 RTLD_LOCAL, lockstate);
2042 }
2043 }
2044
2045 static void
load_filtees(Obj_Entry * obj,int flags,RtldLockState * lockstate)2046 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2047 {
2048
2049 lock_restart_for_upgrade(lockstate);
2050 if (!obj->filtees_loaded) {
2051 load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2052 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2053 obj->filtees_loaded = true;
2054 }
2055 }
2056
2057 static int
process_needed(Obj_Entry * obj,Needed_Entry * needed,int flags)2058 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2059 {
2060 Obj_Entry *obj1;
2061
2062 for (; needed != NULL; needed = needed->next) {
2063 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2064 flags & ~RTLD_LO_NOLOAD);
2065 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2066 return (-1);
2067 }
2068 return (0);
2069 }
2070
2071 /*
2072 * Given a shared object, traverse its list of needed objects, and load
2073 * each of them. Returns 0 on success. Generates an error message and
2074 * returns -1 on failure.
2075 */
2076 static int
load_needed_objects(Obj_Entry * first,int flags)2077 load_needed_objects(Obj_Entry *first, int flags)
2078 {
2079 Obj_Entry *obj;
2080
2081 for (obj = first; obj != NULL; obj = obj->next) {
2082 if (process_needed(obj, obj->needed, flags) == -1)
2083 return (-1);
2084 }
2085 return (0);
2086 }
2087
2088 static int
load_preload_objects(void)2089 load_preload_objects(void)
2090 {
2091 char *p = ld_preload;
2092 Obj_Entry *obj;
2093 static const char delim[] = " \t:;";
2094
2095 if (p == NULL)
2096 return 0;
2097
2098 p += strspn(p, delim);
2099 while (*p != '\0') {
2100 size_t len = strcspn(p, delim);
2101 char savech;
2102 SymLook req;
2103 int res;
2104
2105 savech = p[len];
2106 p[len] = '\0';
2107 obj = load_object(p, -1, NULL, 0);
2108 if (obj == NULL)
2109 return -1; /* XXX - cleanup */
2110 obj->z_interpose = true;
2111 p[len] = savech;
2112 p += len;
2113 p += strspn(p, delim);
2114
2115 /* Check for the magic tracing function */
2116 symlook_init(&req, RTLD_FUNCTRACE);
2117 res = symlook_obj(&req, obj);
2118 if (res == 0) {
2119 rtld_functrace = (void *)(req.defobj_out->relocbase +
2120 req.sym_out->st_value);
2121 rtld_functrace_obj = req.defobj_out;
2122 }
2123 }
2124 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2125 return 0;
2126 }
2127
2128 static const char *
printable_path(const char * path)2129 printable_path(const char *path)
2130 {
2131
2132 return (path == NULL ? "<unknown>" : path);
2133 }
2134
2135 /*
2136 * Load a shared object into memory, if it is not already loaded. The
2137 * object may be specified by name or by user-supplied file descriptor
2138 * fd_u. In the later case, the fd_u descriptor is not closed, but its
2139 * duplicate is.
2140 *
2141 * Returns a pointer to the Obj_Entry for the object. Returns NULL
2142 * on failure.
2143 */
2144 static Obj_Entry *
load_object(const char * name,int fd_u,const Obj_Entry * refobj,int flags)2145 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2146 {
2147 Obj_Entry *obj;
2148 int fd;
2149 struct stat sb;
2150 char *path;
2151
2152 fd = -1;
2153 if (name != NULL) {
2154 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
2155 if (object_match_name(obj, name))
2156 return (obj);
2157 }
2158
2159 path = find_library(name, refobj, &fd);
2160 if (path == NULL)
2161 return (NULL);
2162 } else
2163 path = NULL;
2164
2165 if (fd >= 0) {
2166 /*
2167 * search_library_pathfds() opens a fresh file descriptor for the
2168 * library, so there is no need to dup().
2169 */
2170 } else if (fd_u == -1) {
2171 /*
2172 * If we didn't find a match by pathname, or the name is not
2173 * supplied, open the file and check again by device and inode.
2174 * This avoids false mismatches caused by multiple links or ".."
2175 * in pathnames.
2176 *
2177 * To avoid a race, we open the file and use fstat() rather than
2178 * using stat().
2179 */
2180 if ((fd = open(path, O_RDONLY | O_CLOEXEC)) == -1) {
2181 _rtld_error("Cannot open \"%s\"", path);
2182 free(path);
2183 return (NULL);
2184 }
2185 } else {
2186 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2187 if (fd == -1) {
2188 _rtld_error("Cannot dup fd");
2189 free(path);
2190 return (NULL);
2191 }
2192 }
2193 if (fstat(fd, &sb) == -1) {
2194 _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2195 close(fd);
2196 free(path);
2197 return NULL;
2198 }
2199 for (obj = obj_list->next; obj != NULL; obj = obj->next)
2200 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2201 break;
2202 if (obj != NULL && name != NULL) {
2203 object_add_name(obj, name);
2204 free(path);
2205 close(fd);
2206 return obj;
2207 }
2208 if (flags & RTLD_LO_NOLOAD) {
2209 free(path);
2210 close(fd);
2211 return (NULL);
2212 }
2213
2214 /* First use of this object, so we must map it in */
2215 obj = do_load_object(fd, name, path, &sb, flags);
2216 if (obj == NULL)
2217 free(path);
2218 close(fd);
2219
2220 return obj;
2221 }
2222
2223 static Obj_Entry *
do_load_object(int fd,const char * name,char * path,struct stat * sbp,int flags)2224 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2225 int flags)
2226 {
2227 Obj_Entry *obj;
2228 struct statfs fs;
2229
2230 /*
2231 * but first, make sure that environment variables haven't been
2232 * used to circumvent the noexec flag on a filesystem.
2233 */
2234 if (dangerous_ld_env) {
2235 if (fstatfs(fd, &fs) != 0) {
2236 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2237 return NULL;
2238 }
2239 if (fs.f_flags & MNT_NOEXEC) {
2240 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
2241 return NULL;
2242 }
2243 }
2244 dbg("loading \"%s\"", printable_path(path));
2245 obj = map_object(fd, printable_path(path), sbp);
2246 if (obj == NULL)
2247 return NULL;
2248
2249 /*
2250 * If DT_SONAME is present in the object, digest_dynamic2 already
2251 * added it to the object names.
2252 */
2253 if (name != NULL)
2254 object_add_name(obj, name);
2255 obj->path = path;
2256 digest_dynamic(obj, 0);
2257 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2258 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2259 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2260 RTLD_LO_DLOPEN) {
2261 dbg("refusing to load non-loadable \"%s\"", obj->path);
2262 _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2263 munmap(obj->mapbase, obj->mapsize);
2264 obj_free(obj);
2265 return (NULL);
2266 }
2267
2268 *obj_tail = obj;
2269 obj_tail = &obj->next;
2270 obj_count++;
2271 obj_loads++;
2272 linkmap_add(obj); /* for GDB & dlinfo() */
2273 #if 0
2274 max_stack_flags |= obj->stack_flags;
2275 #endif
2276
2277 dbg(" %p .. %p: %s", obj->mapbase,
2278 obj->mapbase + obj->mapsize - 1, obj->path);
2279 if (obj->textrel)
2280 dbg(" WARNING: %s has impure text", obj->path);
2281 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2282 obj->path);
2283
2284 return obj;
2285 }
2286
2287 static Obj_Entry *
obj_from_addr(const void * addr)2288 obj_from_addr(const void *addr)
2289 {
2290 Obj_Entry *obj;
2291
2292 for (obj = obj_list; obj != NULL; obj = obj->next) {
2293 if (addr < (void *) obj->mapbase)
2294 continue;
2295 if (addr < (void *) (obj->mapbase + obj->mapsize))
2296 return obj;
2297 }
2298 return NULL;
2299 }
2300
2301 /*
2302 * If the main program is defined with a .preinit_array section, call
2303 * each function in order. This must occur before the initialization
2304 * of any shared object or the main program.
2305 */
2306 static void
preinit_main(void)2307 preinit_main(void)
2308 {
2309 Elf_Addr *preinit_addr;
2310 int index;
2311
2312 preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2313 if (preinit_addr == NULL)
2314 return;
2315
2316 for (index = 0; index < obj_main->preinit_array_num; index++) {
2317 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2318 dbg("calling preinit function for %s at %p", obj_main->path,
2319 (void *)preinit_addr[index]);
2320 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2321 0, 0, obj_main->path);
2322 call_init_pointer(obj_main, preinit_addr[index]);
2323 }
2324 }
2325 }
2326
2327 /*
2328 * Call the finalization functions for each of the objects in "list"
2329 * belonging to the DAG of "root" and referenced once. If NULL "root"
2330 * is specified, every finalization function will be called regardless
2331 * of the reference count and the list elements won't be freed. All of
2332 * the objects are expected to have non-NULL fini functions.
2333 */
2334 static void
objlist_call_fini(Objlist * list,Obj_Entry * root,RtldLockState * lockstate)2335 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2336 {
2337 Objlist_Entry *elm;
2338 char *saved_msg;
2339 Elf_Addr *fini_addr;
2340 int index;
2341
2342 assert(root == NULL || root->refcount == 1);
2343
2344 /*
2345 * Preserve the current error message since a fini function might
2346 * call into the dynamic linker and overwrite it.
2347 */
2348 saved_msg = errmsg_save();
2349 do {
2350 STAILQ_FOREACH(elm, list, link) {
2351 if (root != NULL && (elm->obj->refcount != 1 ||
2352 objlist_find(&root->dagmembers, elm->obj) == NULL))
2353 continue;
2354
2355 /* Remove object from fini list to prevent recursive invocation. */
2356 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2357 /*
2358 * XXX: If a dlopen() call references an object while the
2359 * fini function is in progress, we might end up trying to
2360 * unload the referenced object in dlclose() or the object
2361 * won't be unloaded although its fini function has been
2362 * called.
2363 */
2364 lock_release(rtld_bind_lock, lockstate);
2365
2366 /*
2367 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2368 * When this happens, DT_FINI_ARRAY is processed first.
2369 * It is also processed backwards. It is possible to encounter
2370 * DT_FINI_ARRAY elements with values of 0 or 1, but they need
2371 * to be ignored.
2372 */
2373 fini_addr = (Elf_Addr *)elm->obj->fini_array;
2374 if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2375 for (index = elm->obj->fini_array_num - 1; index >= 0; index--) {
2376 if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2377 dbg("calling fini array function for %s at %p",
2378 elm->obj->path, (void *)fini_addr[index]);
2379 LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2380 (void *)fini_addr[index], 0, 0, elm->obj->path);
2381 call_initfini_pointer(elm->obj, fini_addr[index]);
2382 }
2383 }
2384 }
2385 if (elm->obj->fini != (Elf_Addr)NULL) {
2386 dbg("calling fini function for %s at %p", elm->obj->path,
2387 (void *)elm->obj->fini);
2388 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2389 0, 0, elm->obj->path);
2390 call_initfini_pointer(elm->obj, elm->obj->fini);
2391 }
2392 wlock_acquire(rtld_bind_lock, lockstate);
2393 /* No need to free anything if process is going down. */
2394 if (root != NULL)
2395 free(elm);
2396 /*
2397 * We must restart the list traversal after every fini call
2398 * because a dlclose() call from the fini function or from
2399 * another thread might have modified the reference counts.
2400 */
2401 break;
2402 }
2403 } while (elm != NULL);
2404 errmsg_restore(saved_msg);
2405 }
2406
2407 /*
2408 * Call the initialization functions for each of the objects in
2409 * "list". All of the objects are expected to have non-NULL init
2410 * functions.
2411 */
2412 static void
objlist_call_init(Objlist * list,RtldLockState * lockstate)2413 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2414 {
2415 Objlist_Entry *elm;
2416 Obj_Entry *obj;
2417 char *saved_msg;
2418 Elf_Addr *init_addr;
2419 int index;
2420
2421 /*
2422 * Clean init_scanned flag so that objects can be rechecked and
2423 * possibly initialized earlier if any of vectors called below
2424 * cause the change by using dlopen.
2425 */
2426 for (obj = obj_list; obj != NULL; obj = obj->next)
2427 obj->init_scanned = false;
2428
2429 /*
2430 * Preserve the current error message since an init function might
2431 * call into the dynamic linker and overwrite it.
2432 */
2433 saved_msg = errmsg_save();
2434 STAILQ_FOREACH(elm, list, link) {
2435 if (elm->obj->init_done) /* Initialized early. */
2436 continue;
2437
2438 /*
2439 * Race: other thread might try to use this object before current
2440 * one completes the initilization. Not much can be done here
2441 * without better locking.
2442 */
2443 elm->obj->init_done = true;
2444 lock_release(rtld_bind_lock, lockstate);
2445
2446 /*
2447 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2448 * When this happens, DT_INIT is processed first.
2449 * It is possible to encounter DT_INIT_ARRAY elements with values
2450 * of 0 or 1, but they need to be ignored.
2451 */
2452 if (elm->obj->init != (Elf_Addr)NULL) {
2453 dbg("calling init function for %s at %p", elm->obj->path,
2454 (void *)elm->obj->init);
2455 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2456 0, 0, elm->obj->path);
2457 call_initfini_pointer(elm->obj, elm->obj->init);
2458 }
2459 init_addr = (Elf_Addr *)elm->obj->init_array;
2460 if (init_addr != NULL) {
2461 for (index = 0; index < elm->obj->init_array_num; index++) {
2462 if (init_addr[index] != 0 && init_addr[index] != 1) {
2463 dbg("calling init array function for %s at %p", elm->obj->path,
2464 (void *)init_addr[index]);
2465 LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2466 (void *)init_addr[index], 0, 0, elm->obj->path);
2467 call_init_pointer(elm->obj, init_addr[index]);
2468 }
2469 }
2470 }
2471 wlock_acquire(rtld_bind_lock, lockstate);
2472 }
2473 errmsg_restore(saved_msg);
2474 }
2475
2476 static void
objlist_clear(Objlist * list)2477 objlist_clear(Objlist *list)
2478 {
2479 Objlist_Entry *elm;
2480
2481 while (!STAILQ_EMPTY(list)) {
2482 elm = STAILQ_FIRST(list);
2483 STAILQ_REMOVE_HEAD(list, link);
2484 free(elm);
2485 }
2486 }
2487
2488 static Objlist_Entry *
objlist_find(Objlist * list,const Obj_Entry * obj)2489 objlist_find(Objlist *list, const Obj_Entry *obj)
2490 {
2491 Objlist_Entry *elm;
2492
2493 STAILQ_FOREACH(elm, list, link)
2494 if (elm->obj == obj)
2495 return elm;
2496 return NULL;
2497 }
2498
2499 static void
objlist_init(Objlist * list)2500 objlist_init(Objlist *list)
2501 {
2502 STAILQ_INIT(list);
2503 }
2504
2505 static void
objlist_push_head(Objlist * list,Obj_Entry * obj)2506 objlist_push_head(Objlist *list, Obj_Entry *obj)
2507 {
2508 Objlist_Entry *elm;
2509
2510 elm = NEW(Objlist_Entry);
2511 elm->obj = obj;
2512 STAILQ_INSERT_HEAD(list, elm, link);
2513 }
2514
2515 static void
objlist_push_tail(Objlist * list,Obj_Entry * obj)2516 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2517 {
2518 Objlist_Entry *elm;
2519
2520 elm = NEW(Objlist_Entry);
2521 elm->obj = obj;
2522 STAILQ_INSERT_TAIL(list, elm, link);
2523 }
2524
2525 static void
objlist_put_after(Objlist * list,Obj_Entry * listobj,Obj_Entry * obj)2526 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2527 {
2528 Objlist_Entry *elm, *listelm;
2529
2530 STAILQ_FOREACH(listelm, list, link) {
2531 if (listelm->obj == listobj)
2532 break;
2533 }
2534 elm = NEW(Objlist_Entry);
2535 elm->obj = obj;
2536 if (listelm != NULL)
2537 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2538 else
2539 STAILQ_INSERT_TAIL(list, elm, link);
2540 }
2541
2542 static void
objlist_remove(Objlist * list,Obj_Entry * obj)2543 objlist_remove(Objlist *list, Obj_Entry *obj)
2544 {
2545 Objlist_Entry *elm;
2546
2547 if ((elm = objlist_find(list, obj)) != NULL) {
2548 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2549 free(elm);
2550 }
2551 }
2552
2553 /*
2554 * Relocate dag rooted in the specified object.
2555 * Returns 0 on success, or -1 on failure.
2556 */
2557
2558 static int
relocate_object_dag(Obj_Entry * root,bool bind_now,Obj_Entry * rtldobj,int flags,RtldLockState * lockstate)2559 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2560 int flags, RtldLockState *lockstate)
2561 {
2562 Objlist_Entry *elm;
2563 int error;
2564
2565 error = 0;
2566 STAILQ_FOREACH(elm, &root->dagmembers, link) {
2567 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2568 lockstate);
2569 if (error == -1)
2570 break;
2571 }
2572 return (error);
2573 }
2574
2575 /*
2576 * Prepare for, or clean after, relocating an object marked with
2577 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only
2578 * segments are remapped read-write. After relocations are done, the
2579 * segment's permissions are returned back to the modes specified in
2580 * the phdrs. If any relocation happened, or always for wired
2581 * program, COW is triggered.
2582 */
2583 static int
reloc_textrel_prot(Obj_Entry * obj,bool before)2584 reloc_textrel_prot(Obj_Entry *obj, bool before)
2585 {
2586 const Elf_Phdr *ph;
2587 void *base;
2588 size_t l, sz;
2589 int prot;
2590
2591 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2592 l--, ph++) {
2593 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2594 continue;
2595 base = obj->relocbase + trunc_page(ph->p_vaddr);
2596 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2597 trunc_page(ph->p_vaddr);
2598 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2599 /*
2600 * Make sure modified text segments are included in the
2601 * core dump since we modified it. This unfortunately causes the
2602 * entire text segment to core-out but we don't have much of a
2603 * choice. We could try to only reenable core dumps on pages
2604 * in which relocations occured but that is likely most of the text
2605 * pages anyway, and even that would not work because the rest of
2606 * the text pages would wind up as a read-only OBJT_DEFAULT object
2607 * (created due to our modifications) backed by the original OBJT_VNODE
2608 * object, and the ELF coredump code is currently only able to dump
2609 * vnode records for pure vnode-backed mappings, not vnode backings
2610 * to memory objects.
2611 */
2612 if (before == false)
2613 madvise(base, sz, MADV_CORE);
2614 if (mprotect(base, sz, prot) == -1) {
2615 _rtld_error("%s: Cannot write-%sable text segment: %s",
2616 obj->path, before ? "en" : "dis",
2617 rtld_strerror(errno));
2618 return (-1);
2619 }
2620 }
2621 return (0);
2622 }
2623
2624 /*
2625 * Relocate single object.
2626 * Returns 0 on success, or -1 on failure.
2627 */
2628 static int
relocate_object(Obj_Entry * obj,bool bind_now,Obj_Entry * rtldobj,int flags,RtldLockState * lockstate)2629 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2630 int flags, RtldLockState *lockstate)
2631 {
2632
2633 if (obj->relocated)
2634 return (0);
2635 obj->relocated = true;
2636 if (obj != rtldobj)
2637 dbg("relocating \"%s\"", obj->path);
2638
2639 if (obj->symtab == NULL || obj->strtab == NULL ||
2640 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2641 _rtld_error("%s: Shared object has no run-time symbol table",
2642 obj->path);
2643 return (-1);
2644 }
2645
2646 /* There are relocations to the write-protected text segment. */
2647 if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2648 return (-1);
2649
2650 /* Process the non-PLT non-IFUNC relocations. */
2651 if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2652 return (-1);
2653
2654 /* Re-protected the text segment. */
2655 if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2656 return (-1);
2657
2658 /* Set the special PLT or GOT entries. */
2659 init_pltgot(obj);
2660
2661 /* Process the PLT relocations. */
2662 if (reloc_plt(obj) == -1)
2663 return (-1);
2664 /* Relocate the jump slots if we are doing immediate binding. */
2665 if (obj->bind_now || bind_now)
2666 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2667 return (-1);
2668
2669 /*
2670 * Process the non-PLT IFUNC relocations. The relocations are
2671 * processed in two phases, because IFUNC resolvers may
2672 * reference other symbols, which must be readily processed
2673 * before resolvers are called.
2674 */
2675 if (obj->non_plt_gnu_ifunc &&
2676 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate))
2677 return (-1);
2678
2679 /*
2680 * Set up the magic number and version in the Obj_Entry. These
2681 * were checked in the crt1.o from the original ElfKit, so we
2682 * set them for backward compatibility.
2683 */
2684 obj->magic = RTLD_MAGIC;
2685 obj->version = RTLD_VERSION;
2686
2687 /*
2688 * Set relocated data to read-only status if protection specified
2689 */
2690
2691 if (obj->relro_size) {
2692 if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2693 _rtld_error("%s: Cannot enforce relro relocation: %s",
2694 obj->path, rtld_strerror(errno));
2695 return (-1);
2696 }
2697 obj->relro_protected = true;
2698 }
2699 return (0);
2700 }
2701
2702 /*
2703 * Relocate newly-loaded shared objects. The argument is a pointer to
2704 * the Obj_Entry for the first such object. All objects from the first
2705 * to the end of the list of objects are relocated. Returns 0 on success,
2706 * or -1 on failure.
2707 */
2708 static int
relocate_objects(Obj_Entry * first,bool bind_now,Obj_Entry * rtldobj,int flags,RtldLockState * lockstate)2709 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2710 int flags, RtldLockState *lockstate)
2711 {
2712 Obj_Entry *obj;
2713 int error;
2714
2715 for (error = 0, obj = first; obj != NULL; obj = obj->next) {
2716 error = relocate_object(obj, bind_now, rtldobj, flags,
2717 lockstate);
2718 if (error == -1)
2719 break;
2720 }
2721 return (error);
2722 }
2723
2724 /*
2725 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2726 * referencing STT_GNU_IFUNC symbols is postponed till the other
2727 * relocations are done. The indirect functions specified as
2728 * ifunc are allowed to call other symbols, so we need to have
2729 * objects relocated before asking for resolution from indirects.
2730 *
2731 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2732 * instead of the usual lazy handling of PLT slots. It is
2733 * consistent with how GNU does it.
2734 */
2735 static int
resolve_object_ifunc(Obj_Entry * obj,bool bind_now,int flags,RtldLockState * lockstate)2736 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2737 RtldLockState *lockstate)
2738 {
2739 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2740 return (-1);
2741 if (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
2742 lockstate) == -1)
2743 return (-1);
2744 if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2745 reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2746 return (-1);
2747 return (0);
2748 }
2749
2750 static int
resolve_objects_ifunc(Obj_Entry * first,bool bind_now,int flags,RtldLockState * lockstate)2751 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2752 RtldLockState *lockstate)
2753 {
2754 Obj_Entry *obj;
2755
2756 for (obj = first; obj != NULL; obj = obj->next) {
2757 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2758 return (-1);
2759 }
2760 return (0);
2761 }
2762
2763 static int
initlist_objects_ifunc(Objlist * list,bool bind_now,int flags,RtldLockState * lockstate)2764 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2765 RtldLockState *lockstate)
2766 {
2767 Objlist_Entry *elm;
2768
2769 STAILQ_FOREACH(elm, list, link) {
2770 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2771 lockstate) == -1)
2772 return (-1);
2773 }
2774 return (0);
2775 }
2776
2777 /*
2778 * Cleanup procedure. It will be called (by the atexit mechanism) just
2779 * before the process exits.
2780 */
2781 static void
rtld_exit(void)2782 rtld_exit(void)
2783 {
2784 RtldLockState lockstate;
2785
2786 wlock_acquire(rtld_bind_lock, &lockstate);
2787 dbg("rtld_exit()");
2788 objlist_call_fini(&list_fini, NULL, &lockstate);
2789 /* No need to remove the items from the list, since we are exiting. */
2790 if (!libmap_disable)
2791 lm_fini();
2792 lock_release(rtld_bind_lock, &lockstate);
2793 }
2794
2795 /*
2796 * Iterate over a search path, translate each element, and invoke the
2797 * callback on the result.
2798 */
2799 static void *
path_enumerate(const char * path,path_enum_proc callback,void * arg)2800 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2801 {
2802 const char *trans;
2803 if (path == NULL)
2804 return (NULL);
2805
2806 path += strspn(path, ":;");
2807 while (*path != '\0') {
2808 size_t len;
2809 char *res;
2810
2811 len = strcspn(path, ":;");
2812 trans = lm_findn(NULL, path, len);
2813 if (trans)
2814 res = callback(trans, strlen(trans), arg);
2815 else
2816 res = callback(path, len, arg);
2817
2818 if (res != NULL)
2819 return (res);
2820
2821 path += len;
2822 path += strspn(path, ":;");
2823 }
2824
2825 return (NULL);
2826 }
2827
2828 struct try_library_args {
2829 const char *name;
2830 size_t namelen;
2831 char *buffer;
2832 size_t buflen;
2833 };
2834
2835 static void *
try_library_path(const char * dir,size_t dirlen,void * param)2836 try_library_path(const char *dir, size_t dirlen, void *param)
2837 {
2838 struct try_library_args *arg;
2839
2840 arg = param;
2841 if (*dir == '/' || trust) {
2842 char *pathname;
2843
2844 if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2845 return (NULL);
2846
2847 pathname = arg->buffer;
2848 strncpy(pathname, dir, dirlen);
2849 pathname[dirlen] = '/';
2850 strcpy(pathname + dirlen + 1, arg->name);
2851
2852 dbg(" Trying \"%s\"", pathname);
2853 if (access(pathname, F_OK) == 0) { /* We found it */
2854 pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2855 strcpy(pathname, arg->buffer);
2856 return (pathname);
2857 }
2858 }
2859 return (NULL);
2860 }
2861
2862 static char *
search_library_path(const char * name,const char * path)2863 search_library_path(const char *name, const char *path)
2864 {
2865 char *p;
2866 struct try_library_args arg;
2867
2868 if (path == NULL)
2869 return NULL;
2870
2871 arg.name = name;
2872 arg.namelen = strlen(name);
2873 arg.buffer = xmalloc(PATH_MAX);
2874 arg.buflen = PATH_MAX;
2875
2876 p = path_enumerate(path, try_library_path, &arg);
2877
2878 free(arg.buffer);
2879
2880 return (p);
2881 }
2882
2883
2884 /*
2885 * Finds the library with the given name using the directory descriptors
2886 * listed in the LD_LIBRARY_PATH_FDS environment variable.
2887 *
2888 * Returns a freshly-opened close-on-exec file descriptor for the library,
2889 * or -1 if the library cannot be found.
2890 */
2891 static char *
search_library_pathfds(const char * name,const char * path,int * fdp)2892 search_library_pathfds(const char *name, const char *path, int *fdp)
2893 {
2894 char *envcopy, *fdstr, *found, *last_token;
2895 size_t len;
2896 int dirfd, fd;
2897
2898 dbg("%s('%s', '%s', fdp)", __func__, name, path);
2899
2900 /* Don't load from user-specified libdirs into setuid binaries. */
2901 if (!trust)
2902 return (NULL);
2903
2904 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
2905 if (path == NULL)
2906 return (NULL);
2907
2908 /* LD_LIBRARY_PATH_FDS only works with relative paths. */
2909 if (name[0] == '/') {
2910 dbg("Absolute path (%s) passed to %s", name, __func__);
2911 return (NULL);
2912 }
2913
2914 /*
2915 * Use strtok_r() to walk the FD:FD:FD list. This requires a local
2916 * copy of the path, as strtok_r rewrites separator tokens
2917 * with '\0'.
2918 *
2919 * NOTE: strtok() uses a __thread static and cannot be used by rtld.
2920 */
2921 found = NULL;
2922 envcopy = xstrdup(path);
2923 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
2924 fdstr = strtok_r(NULL, ":", &last_token)) {
2925 dirfd = parse_libdir(fdstr);
2926 if (dirfd < 0)
2927 break;
2928 fd = openat(dirfd, name, O_RDONLY | O_CLOEXEC);
2929 if (fd >= 0) {
2930 *fdp = fd;
2931 len = strlen(fdstr) + strlen(name) + 3;
2932 found = xmalloc(len);
2933 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
2934 _rtld_error("error generating '%d/%s'",
2935 dirfd, name);
2936 die();
2937 }
2938 dbg("open('%s') => %d", found, fd);
2939 break;
2940 }
2941 }
2942 free(envcopy);
2943
2944 return (found);
2945 }
2946
2947
2948 int
dlclose(void * handle)2949 dlclose(void *handle)
2950 {
2951 Obj_Entry *root;
2952 RtldLockState lockstate;
2953
2954 wlock_acquire(rtld_bind_lock, &lockstate);
2955 root = dlcheck(handle);
2956 if (root == NULL) {
2957 lock_release(rtld_bind_lock, &lockstate);
2958 return -1;
2959 }
2960 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2961 root->path);
2962
2963 /* Unreference the object and its dependencies. */
2964 root->dl_refcount--;
2965
2966 if (root->refcount == 1) {
2967 /*
2968 * The object will be no longer referenced, so we must unload it.
2969 * First, call the fini functions.
2970 */
2971 objlist_call_fini(&list_fini, root, &lockstate);
2972
2973 unref_dag(root);
2974
2975 /* Finish cleaning up the newly-unreferenced objects. */
2976 GDB_STATE(RT_DELETE,&root->linkmap);
2977 unload_object(root);
2978 GDB_STATE(RT_CONSISTENT,NULL);
2979 } else
2980 unref_dag(root);
2981
2982 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2983 lock_release(rtld_bind_lock, &lockstate);
2984 return 0;
2985 }
2986
2987 char *
dlerror(void)2988 dlerror(void)
2989 {
2990 char *msg = error_message;
2991 error_message = NULL;
2992 return msg;
2993 }
2994
2995 void *
dlopen(const char * name,int mode)2996 dlopen(const char *name, int mode)
2997 {
2998
2999 return (rtld_dlopen(name, -1, mode));
3000 }
3001
3002 void *
fdlopen(int fd,int mode)3003 fdlopen(int fd, int mode)
3004 {
3005
3006 return (rtld_dlopen(NULL, fd, mode));
3007 }
3008
3009 static void *
rtld_dlopen(const char * name,int fd,int mode)3010 rtld_dlopen(const char *name, int fd, int mode)
3011 {
3012 RtldLockState lockstate;
3013 int lo_flags;
3014
3015 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3016 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3017 if (ld_tracing != NULL) {
3018 rlock_acquire(rtld_bind_lock, &lockstate);
3019 if (sigsetjmp(lockstate.env, 0) != 0)
3020 lock_upgrade(rtld_bind_lock, &lockstate);
3021 environ = (char **)*get_program_var_addr("environ", &lockstate);
3022 lock_release(rtld_bind_lock, &lockstate);
3023 }
3024 lo_flags = RTLD_LO_DLOPEN;
3025 if (mode & RTLD_NODELETE)
3026 lo_flags |= RTLD_LO_NODELETE;
3027 if (mode & RTLD_NOLOAD)
3028 lo_flags |= RTLD_LO_NOLOAD;
3029 if (ld_tracing != NULL)
3030 lo_flags |= RTLD_LO_TRACE;
3031
3032 return (dlopen_object(name, fd, obj_main, lo_flags,
3033 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3034 }
3035
3036 static void
dlopen_cleanup(Obj_Entry * obj)3037 dlopen_cleanup(Obj_Entry *obj)
3038 {
3039
3040 obj->dl_refcount--;
3041 unref_dag(obj);
3042 if (obj->refcount == 0)
3043 unload_object(obj);
3044 }
3045
3046 static Obj_Entry *
dlopen_object(const char * name,int fd,Obj_Entry * refobj,int lo_flags,int mode,RtldLockState * lockstate)3047 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3048 int mode, RtldLockState *lockstate)
3049 {
3050 Obj_Entry **old_obj_tail;
3051 Obj_Entry *obj;
3052 Objlist initlist;
3053 RtldLockState mlockstate;
3054 int result;
3055
3056 objlist_init(&initlist);
3057
3058 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3059 wlock_acquire(rtld_bind_lock, &mlockstate);
3060 lockstate = &mlockstate;
3061 }
3062 GDB_STATE(RT_ADD,NULL);
3063
3064 old_obj_tail = obj_tail;
3065 obj = NULL;
3066 if (name == NULL && fd == -1) {
3067 obj = obj_main;
3068 obj->refcount++;
3069 } else {
3070 obj = load_object(name, fd, refobj, lo_flags);
3071 }
3072
3073 if (obj) {
3074 obj->dl_refcount++;
3075 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3076 objlist_push_tail(&list_global, obj);
3077 if (*old_obj_tail != NULL) { /* We loaded something new. */
3078 assert(*old_obj_tail == obj);
3079 if ((lo_flags & RTLD_LO_EARLY) == 0 && obj->static_tls &&
3080 !allocate_tls_offset(obj)) {
3081 _rtld_error("%s: No space available "
3082 "for static TLS",
3083 obj->path);
3084 result = -1;
3085 } else {
3086 result = 0;
3087 }
3088 if (result == 0) {
3089 result = load_needed_objects(
3090 obj,
3091 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
3092 }
3093 init_dag(obj);
3094 ref_dag(obj);
3095 if (result != -1)
3096 result = rtld_verify_versions(&obj->dagmembers);
3097 if (result != -1 && ld_tracing)
3098 goto trace;
3099 if (result == -1 || relocate_object_dag(obj,
3100 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3101 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3102 lockstate) == -1) {
3103 dlopen_cleanup(obj);
3104 obj = NULL;
3105 } else if (lo_flags & RTLD_LO_EARLY) {
3106 /*
3107 * Do not call the init functions for early loaded
3108 * filtees. The image is still not initialized enough
3109 * for them to work.
3110 *
3111 * Our object is found by the global object list and
3112 * will be ordered among all init calls done right
3113 * before transferring control to main.
3114 */
3115 } else {
3116 /* Make list of init functions to call. */
3117 initlist_add_objects(obj, &obj->next, &initlist);
3118 }
3119 /*
3120 * Process all no_delete objects here, given them own
3121 * DAGs to prevent their dependencies from being unloaded.
3122 * This has to be done after we have loaded all of the
3123 * dependencies, so that we do not miss any.
3124 */
3125 if (obj != NULL)
3126 process_nodelete(obj);
3127 } else {
3128 /*
3129 * Bump the reference counts for objects on this DAG. If
3130 * this is the first dlopen() call for the object that was
3131 * already loaded as a dependency, initialize the dag
3132 * starting at it.
3133 */
3134 init_dag(obj);
3135 ref_dag(obj);
3136
3137 if ((lo_flags & RTLD_LO_TRACE) != 0)
3138 goto trace;
3139 }
3140 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3141 obj->z_nodelete) && !obj->ref_nodel) {
3142 dbg("obj %s nodelete", obj->path);
3143 ref_dag(obj);
3144 obj->z_nodelete = obj->ref_nodel = true;
3145 }
3146 }
3147
3148 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3149 name);
3150 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3151
3152 if ((lo_flags & RTLD_LO_EARLY) == 0) {
3153 map_stacks_exec(lockstate);
3154 if (obj)
3155 distribute_static_tls(&initlist, lockstate);
3156 }
3157
3158 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3159 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3160 lockstate) == -1) {
3161 objlist_clear(&initlist);
3162 dlopen_cleanup(obj);
3163 if (lockstate == &mlockstate)
3164 lock_release(rtld_bind_lock, lockstate);
3165 return (NULL);
3166 }
3167
3168 if (!(lo_flags & RTLD_LO_EARLY)) {
3169 /* Call the init functions. */
3170 objlist_call_init(&initlist, lockstate);
3171 }
3172 objlist_clear(&initlist);
3173 if (lockstate == &mlockstate)
3174 lock_release(rtld_bind_lock, lockstate);
3175 return obj;
3176 trace:
3177 trace_loaded_objects(obj);
3178 if (lockstate == &mlockstate)
3179 lock_release(rtld_bind_lock, lockstate);
3180 exit(0);
3181 }
3182
3183 static void *
do_dlsym(void * handle,const char * name,void * retaddr,const Ver_Entry * ve,int flags)3184 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3185 int flags)
3186 {
3187 DoneList donelist;
3188 const Obj_Entry *obj, *defobj;
3189 const Elf_Sym *def;
3190 SymLook req;
3191 RtldLockState lockstate;
3192 tls_index ti;
3193 int res;
3194
3195 def = NULL;
3196 defobj = NULL;
3197 symlook_init(&req, name);
3198 req.ventry = ve;
3199 req.flags = flags | SYMLOOK_IN_PLT;
3200 req.lockstate = &lockstate;
3201
3202 rlock_acquire(rtld_bind_lock, &lockstate);
3203 if (sigsetjmp(lockstate.env, 0) != 0)
3204 lock_upgrade(rtld_bind_lock, &lockstate);
3205 if (handle == NULL || handle == RTLD_NEXT ||
3206 handle == RTLD_DEFAULT || handle == RTLD_SELF ||
3207 handle == RTLD_ALL) {
3208
3209 if (handle != RTLD_ALL) {
3210 if ((obj = obj_from_addr(retaddr)) == NULL) {
3211 _rtld_error("Cannot determine caller's shared object");
3212 lock_release(rtld_bind_lock, &lockstate);
3213 return NULL;
3214 }
3215 } else {
3216 obj = obj_list;
3217 }
3218 if (handle == NULL) { /* Just the caller's shared object. */
3219 res = symlook_obj(&req, obj);
3220 if (res == 0) {
3221 def = req.sym_out;
3222 defobj = req.defobj_out;
3223 }
3224 } else if (handle == RTLD_NEXT || /* Objects after caller's */
3225 handle == RTLD_SELF || /* ... caller included */
3226 handle == RTLD_ALL) { /* All Objects */
3227 if (handle == RTLD_NEXT)
3228 obj = obj->next;
3229 for (; obj != NULL; obj = obj->next) {
3230 res = symlook_obj(&req, obj);
3231 if (res == 0) {
3232 if (def == NULL ||
3233 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3234 def = req.sym_out;
3235 defobj = req.defobj_out;
3236 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3237 break;
3238 }
3239 }
3240 }
3241 /*
3242 * Search the dynamic linker itself, and possibly resolve the
3243 * symbol from there. This is how the application links to
3244 * dynamic linker services such as dlopen.
3245 */
3246 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3247 res = symlook_obj(&req, &obj_rtld);
3248 if (res == 0) {
3249 def = req.sym_out;
3250 defobj = req.defobj_out;
3251 }
3252 }
3253 } else {
3254 assert(handle == RTLD_DEFAULT);
3255 res = symlook_default(&req, obj);
3256 if (res == 0) {
3257 defobj = req.defobj_out;
3258 def = req.sym_out;
3259 }
3260 }
3261 } else {
3262 if ((obj = dlcheck(handle)) == NULL) {
3263 lock_release(rtld_bind_lock, &lockstate);
3264 return NULL;
3265 }
3266
3267 donelist_init(&donelist);
3268 if (obj->mainprog) {
3269 /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3270 res = symlook_global(&req, &donelist);
3271 if (res == 0) {
3272 def = req.sym_out;
3273 defobj = req.defobj_out;
3274 }
3275 /*
3276 * Search the dynamic linker itself, and possibly resolve the
3277 * symbol from there. This is how the application links to
3278 * dynamic linker services such as dlopen.
3279 */
3280 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3281 res = symlook_obj(&req, &obj_rtld);
3282 if (res == 0) {
3283 def = req.sym_out;
3284 defobj = req.defobj_out;
3285 }
3286 }
3287 }
3288 else {
3289 /* Search the whole DAG rooted at the given object. */
3290 res = symlook_list(&req, &obj->dagmembers, &donelist);
3291 if (res == 0) {
3292 def = req.sym_out;
3293 defobj = req.defobj_out;
3294 }
3295 }
3296 }
3297
3298 if (def != NULL) {
3299 lock_release(rtld_bind_lock, &lockstate);
3300
3301 /*
3302 * The value required by the caller is derived from the value
3303 * of the symbol. this is simply the relocated value of the
3304 * symbol.
3305 */
3306 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3307 return (make_function_pointer(def, defobj));
3308 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3309 return (rtld_resolve_ifunc(defobj, def));
3310 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3311 ti.ti_module = defobj->tlsindex;
3312 ti.ti_offset = def->st_value;
3313 return (__tls_get_addr(&ti));
3314 } else
3315 return (defobj->relocbase + def->st_value);
3316 }
3317
3318 _rtld_error("Undefined symbol \"%s\"", name);
3319 lock_release(rtld_bind_lock, &lockstate);
3320 return NULL;
3321 }
3322
3323 void *
dlsym(void * handle,const char * name)3324 dlsym(void *handle, const char *name)
3325 {
3326 return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3327 SYMLOOK_DLSYM);
3328 }
3329
3330 dlfunc_t
dlfunc(void * handle,const char * name)3331 dlfunc(void *handle, const char *name)
3332 {
3333 union {
3334 void *d;
3335 dlfunc_t f;
3336 } rv;
3337
3338 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3339 SYMLOOK_DLSYM);
3340 return (rv.f);
3341 }
3342
3343 void *
dlvsym(void * handle,const char * name,const char * version)3344 dlvsym(void *handle, const char *name, const char *version)
3345 {
3346 Ver_Entry ventry;
3347
3348 ventry.name = version;
3349 ventry.file = NULL;
3350 ventry.hash = elf_hash(version);
3351 ventry.flags= 0;
3352 return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3353 SYMLOOK_DLSYM);
3354 }
3355
3356 int
_rtld_addr_phdr(const void * addr,struct dl_phdr_info * phdr_info)3357 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3358 {
3359 const Obj_Entry *obj;
3360 RtldLockState lockstate;
3361
3362 rlock_acquire(rtld_bind_lock, &lockstate);
3363 obj = obj_from_addr(addr);
3364 if (obj == NULL) {
3365 _rtld_error("No shared object contains address");
3366 lock_release(rtld_bind_lock, &lockstate);
3367 return (0);
3368 }
3369 rtld_fill_dl_phdr_info(obj, phdr_info);
3370 lock_release(rtld_bind_lock, &lockstate);
3371 return (1);
3372 }
3373
3374 int
dladdr(const void * addr,Dl_info * info)3375 dladdr(const void *addr, Dl_info *info)
3376 {
3377 const Obj_Entry *obj;
3378 const Elf_Sym *def;
3379 void *symbol_addr;
3380 unsigned long symoffset;
3381 RtldLockState lockstate;
3382
3383 rlock_acquire(rtld_bind_lock, &lockstate);
3384 obj = obj_from_addr(addr);
3385 if (obj == NULL) {
3386 _rtld_error("No shared object contains address");
3387 lock_release(rtld_bind_lock, &lockstate);
3388 return 0;
3389 }
3390 info->dli_fname = obj->path;
3391 info->dli_fbase = obj->mapbase;
3392 info->dli_saddr = NULL;
3393 info->dli_sname = NULL;
3394
3395 /*
3396 * Walk the symbol list looking for the symbol whose address is
3397 * closest to the address sent in.
3398 */
3399 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3400 def = obj->symtab + symoffset;
3401
3402 /*
3403 * For skip the symbol if st_shndx is either SHN_UNDEF or
3404 * SHN_COMMON.
3405 */
3406 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3407 continue;
3408
3409 /*
3410 * If the symbol is greater than the specified address, or if it
3411 * is further away from addr than the current nearest symbol,
3412 * then reject it.
3413 */
3414 symbol_addr = obj->relocbase + def->st_value;
3415 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3416 continue;
3417
3418 /* Update our idea of the nearest symbol. */
3419 info->dli_sname = obj->strtab + def->st_name;
3420 info->dli_saddr = symbol_addr;
3421
3422 /* Exact match? */
3423 if (info->dli_saddr == addr)
3424 break;
3425 }
3426 lock_release(rtld_bind_lock, &lockstate);
3427 return 1;
3428 }
3429
3430 int
dlinfo(void * handle,int request,void * p)3431 dlinfo(void *handle, int request, void *p)
3432 {
3433 const Obj_Entry *obj;
3434 RtldLockState lockstate;
3435 int error;
3436
3437 rlock_acquire(rtld_bind_lock, &lockstate);
3438
3439 if (handle == NULL || handle == RTLD_SELF) {
3440 void *retaddr;
3441
3442 retaddr = __builtin_return_address(0); /* __GNUC__ only */
3443 if ((obj = obj_from_addr(retaddr)) == NULL)
3444 _rtld_error("Cannot determine caller's shared object");
3445 } else
3446 obj = dlcheck(handle);
3447
3448 if (obj == NULL) {
3449 lock_release(rtld_bind_lock, &lockstate);
3450 return (-1);
3451 }
3452
3453 error = 0;
3454 switch (request) {
3455 case RTLD_DI_LINKMAP:
3456 *((struct link_map const **)p) = &obj->linkmap;
3457 break;
3458 case RTLD_DI_ORIGIN:
3459 error = rtld_dirname(obj->path, p);
3460 break;
3461
3462 case RTLD_DI_SERINFOSIZE:
3463 case RTLD_DI_SERINFO:
3464 error = do_search_info(obj, request, (struct dl_serinfo *)p);
3465 break;
3466
3467 default:
3468 _rtld_error("Invalid request %d passed to dlinfo()", request);
3469 error = -1;
3470 }
3471
3472 lock_release(rtld_bind_lock, &lockstate);
3473
3474 return (error);
3475 }
3476
3477 static void
rtld_fill_dl_phdr_info(const Obj_Entry * obj,struct dl_phdr_info * phdr_info)3478 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3479 {
3480
3481 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3482 phdr_info->dlpi_name = obj->path;
3483 phdr_info->dlpi_phdr = obj->phdr;
3484 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3485 phdr_info->dlpi_tls_modid = obj->tlsindex;
3486 phdr_info->dlpi_tls_data = obj->tlsinit;
3487 phdr_info->dlpi_adds = obj_loads;
3488 phdr_info->dlpi_subs = obj_loads - obj_count;
3489 }
3490
3491 int
dl_iterate_phdr(__dl_iterate_hdr_callback callback,void * param)3492 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3493 {
3494 struct dl_phdr_info phdr_info;
3495 const Obj_Entry *obj;
3496 RtldLockState bind_lockstate, phdr_lockstate;
3497 int error;
3498
3499 wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3500 rlock_acquire(rtld_bind_lock, &bind_lockstate);
3501
3502 error = 0;
3503
3504 for (obj = obj_list; obj != NULL; obj = obj->next) {
3505 rtld_fill_dl_phdr_info(obj, &phdr_info);
3506 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3507 break;
3508
3509 }
3510 if (error == 0) {
3511 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3512 error = callback(&phdr_info, sizeof(phdr_info), param);
3513 }
3514
3515 lock_release(rtld_bind_lock, &bind_lockstate);
3516 lock_release(rtld_phdr_lock, &phdr_lockstate);
3517
3518 return (error);
3519 }
3520
3521 static void *
fill_search_info(const char * dir,size_t dirlen,void * param)3522 fill_search_info(const char *dir, size_t dirlen, void *param)
3523 {
3524 struct fill_search_info_args *arg;
3525
3526 arg = param;
3527
3528 if (arg->request == RTLD_DI_SERINFOSIZE) {
3529 arg->serinfo->dls_cnt ++;
3530 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3531 } else {
3532 struct dl_serpath *s_entry;
3533
3534 s_entry = arg->serpath;
3535 s_entry->dls_name = arg->strspace;
3536 s_entry->dls_flags = arg->flags;
3537
3538 strncpy(arg->strspace, dir, dirlen);
3539 arg->strspace[dirlen] = '\0';
3540
3541 arg->strspace += dirlen + 1;
3542 arg->serpath++;
3543 }
3544
3545 return (NULL);
3546 }
3547
3548 static int
do_search_info(const Obj_Entry * obj,int request,struct dl_serinfo * info)3549 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3550 {
3551 struct dl_serinfo _info;
3552 struct fill_search_info_args args;
3553
3554 args.request = RTLD_DI_SERINFOSIZE;
3555 args.serinfo = &_info;
3556
3557 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3558 _info.dls_cnt = 0;
3559
3560 path_enumerate(obj->rpath, fill_search_info, &args);
3561 path_enumerate(ld_library_path, fill_search_info, &args);
3562 path_enumerate(obj->runpath, fill_search_info, &args);
3563 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args);
3564 if (!obj->z_nodeflib)
3565 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3566
3567
3568 if (request == RTLD_DI_SERINFOSIZE) {
3569 info->dls_size = _info.dls_size;
3570 info->dls_cnt = _info.dls_cnt;
3571 return (0);
3572 }
3573
3574 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3575 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3576 return (-1);
3577 }
3578
3579 args.request = RTLD_DI_SERINFO;
3580 args.serinfo = info;
3581 args.serpath = &info->dls_serpath[0];
3582 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3583
3584 args.flags = LA_SER_RUNPATH;
3585 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3586 return (-1);
3587
3588 args.flags = LA_SER_LIBPATH;
3589 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3590 return (-1);
3591
3592 args.flags = LA_SER_RUNPATH;
3593 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL)
3594 return (-1);
3595
3596 args.flags = LA_SER_CONFIG;
3597 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args)
3598 != NULL)
3599 return (-1);
3600
3601 args.flags = LA_SER_DEFAULT;
3602 if (!obj->z_nodeflib &&
3603 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3604 return (-1);
3605 return (0);
3606 }
3607
3608 static int
rtld_dirname(const char * path,char * bname)3609 rtld_dirname(const char *path, char *bname)
3610 {
3611 const char *endp;
3612
3613 /* Empty or NULL string gets treated as "." */
3614 if (path == NULL || *path == '\0') {
3615 bname[0] = '.';
3616 bname[1] = '\0';
3617 return (0);
3618 }
3619
3620 /* Strip trailing slashes */
3621 endp = path + strlen(path) - 1;
3622 while (endp > path && *endp == '/')
3623 endp--;
3624
3625 /* Find the start of the dir */
3626 while (endp > path && *endp != '/')
3627 endp--;
3628
3629 /* Either the dir is "/" or there are no slashes */
3630 if (endp == path) {
3631 bname[0] = *endp == '/' ? '/' : '.';
3632 bname[1] = '\0';
3633 return (0);
3634 } else {
3635 do {
3636 endp--;
3637 } while (endp > path && *endp == '/');
3638 }
3639
3640 if (endp - path + 2 > PATH_MAX)
3641 {
3642 _rtld_error("Filename is too long: %s", path);
3643 return(-1);
3644 }
3645
3646 strncpy(bname, path, endp - path + 1);
3647 bname[endp - path + 1] = '\0';
3648 return (0);
3649 }
3650
3651 static int
rtld_dirname_abs(const char * path,char * base)3652 rtld_dirname_abs(const char *path, char *base)
3653 {
3654 char base_rel[PATH_MAX];
3655
3656 if (rtld_dirname(path, base) == -1)
3657 return (-1);
3658 if (base[0] == '/')
3659 return (0);
3660 if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3661 strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3662 strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3663 return (-1);
3664 strcpy(base, base_rel);
3665 return (0);
3666 }
3667
3668 static void
linkmap_add(Obj_Entry * obj)3669 linkmap_add(Obj_Entry *obj)
3670 {
3671 struct link_map *l = &obj->linkmap;
3672 struct link_map *prev;
3673
3674 obj->linkmap.l_name = obj->path;
3675 obj->linkmap.l_addr = obj->mapbase;
3676 obj->linkmap.l_ld = obj->dynamic;
3677
3678 if (r_debug.r_map == NULL) {
3679 r_debug.r_map = l;
3680 return;
3681 }
3682
3683 /*
3684 * Scan to the end of the list, but not past the entry for the
3685 * dynamic linker, which we want to keep at the very end.
3686 */
3687 for (prev = r_debug.r_map;
3688 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3689 prev = prev->l_next)
3690 ;
3691
3692 /* Link in the new entry. */
3693 l->l_prev = prev;
3694 l->l_next = prev->l_next;
3695 if (l->l_next != NULL)
3696 l->l_next->l_prev = l;
3697 prev->l_next = l;
3698 }
3699
3700 static void
linkmap_delete(Obj_Entry * obj)3701 linkmap_delete(Obj_Entry *obj)
3702 {
3703 struct link_map *l = &obj->linkmap;
3704
3705 if (l->l_prev == NULL) {
3706 if ((r_debug.r_map = l->l_next) != NULL)
3707 l->l_next->l_prev = NULL;
3708 return;
3709 }
3710
3711 if ((l->l_prev->l_next = l->l_next) != NULL)
3712 l->l_next->l_prev = l->l_prev;
3713 }
3714
3715 /*
3716 * Function for the debugger to set a breakpoint on to gain control.
3717 *
3718 * The two parameters allow the debugger to easily find and determine
3719 * what the runtime loader is doing and to whom it is doing it.
3720 *
3721 * When the loadhook trap is hit (r_debug_state, set at program
3722 * initialization), the arguments can be found on the stack:
3723 *
3724 * +8 struct link_map *m
3725 * +4 struct r_debug *rd
3726 * +0 RetAddr
3727 */
3728 void
r_debug_state(struct r_debug * rd,struct link_map * m)3729 r_debug_state(struct r_debug* rd, struct link_map *m)
3730 {
3731 /*
3732 * The following is a hack to force the compiler to emit calls to
3733 * this function, even when optimizing. If the function is empty,
3734 * the compiler is not obliged to emit any code for calls to it,
3735 * even when marked __noinline. However, gdb depends on those
3736 * calls being made.
3737 */
3738 __asm __volatile("" : : : "memory");
3739 }
3740
3741 /*
3742 * A function called after init routines have completed. This can be used to
3743 * break before a program's entry routine is called, and can be used when
3744 * main is not available in the symbol table.
3745 */
3746 void
_r_debug_postinit(struct link_map * m)3747 _r_debug_postinit(struct link_map *m)
3748 {
3749
3750 /* See r_debug_state(). */
3751 __asm __volatile("" : : : "memory");
3752 }
3753
3754 /*
3755 * Get address of the pointer variable in the main program.
3756 * Prefer non-weak symbol over the weak one.
3757 */
3758 static const void **
get_program_var_addr(const char * name,RtldLockState * lockstate)3759 get_program_var_addr(const char *name, RtldLockState *lockstate)
3760 {
3761 SymLook req;
3762 DoneList donelist;
3763
3764 symlook_init(&req, name);
3765 req.lockstate = lockstate;
3766 donelist_init(&donelist);
3767 if (symlook_global(&req, &donelist) != 0)
3768 return (NULL);
3769 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3770 return ((const void **)make_function_pointer(req.sym_out,
3771 req.defobj_out));
3772 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3773 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3774 else
3775 return ((const void **)(req.defobj_out->relocbase +
3776 req.sym_out->st_value));
3777 }
3778
3779 /*
3780 * Set a pointer variable in the main program to the given value. This
3781 * is used to set key variables such as "environ" before any of the
3782 * init functions are called.
3783 */
3784 static void
set_program_var(const char * name,const void * value)3785 set_program_var(const char *name, const void *value)
3786 {
3787 const void **addr;
3788
3789 if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3790 dbg("\"%s\": *%p <-- %p", name, addr, value);
3791 *addr = value;
3792 }
3793 }
3794
3795 /*
3796 * Search the global objects, including dependencies and main object,
3797 * for the given symbol.
3798 */
3799 static int
symlook_global(SymLook * req,DoneList * donelist)3800 symlook_global(SymLook *req, DoneList *donelist)
3801 {
3802 SymLook req1;
3803 const Objlist_Entry *elm;
3804 int res;
3805
3806 symlook_init_from_req(&req1, req);
3807
3808 /* Search all objects loaded at program start up. */
3809 if (req->defobj_out == NULL ||
3810 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3811 res = symlook_list(&req1, &list_main, donelist);
3812 if (res == 0 && (req->defobj_out == NULL ||
3813 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3814 req->sym_out = req1.sym_out;
3815 req->defobj_out = req1.defobj_out;
3816 assert(req->defobj_out != NULL);
3817 }
3818 }
3819
3820 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3821 STAILQ_FOREACH(elm, &list_global, link) {
3822 if (req->defobj_out != NULL &&
3823 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3824 break;
3825 res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3826 if (res == 0 && (req->defobj_out == NULL ||
3827 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3828 req->sym_out = req1.sym_out;
3829 req->defobj_out = req1.defobj_out;
3830 assert(req->defobj_out != NULL);
3831 }
3832 }
3833
3834 return (req->sym_out != NULL ? 0 : ESRCH);
3835 }
3836
3837 /*
3838 * This is a special version of getenv which is far more efficient
3839 * at finding LD_ environment vars.
3840 */
3841 static
3842 const char *
_getenv_ld(const char * id)3843 _getenv_ld(const char *id)
3844 {
3845 const char *envp;
3846 int i, j;
3847 int idlen = strlen(id);
3848
3849 if (ld_index == LD_ARY_CACHE)
3850 return(getenv(id));
3851 if (ld_index == 0) {
3852 for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
3853 if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
3854 ld_ary[j++] = envp;
3855 }
3856 if (j == 0)
3857 ld_ary[j++] = "";
3858 ld_index = j;
3859 }
3860 for (i = ld_index - 1; i >= 0; --i) {
3861 if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
3862 return(ld_ary[i] + idlen + 1);
3863 }
3864 return(NULL);
3865 }
3866
3867 /*
3868 * Given a symbol name in a referencing object, find the corresponding
3869 * definition of the symbol. Returns a pointer to the symbol, or NULL if
3870 * no definition was found. Returns a pointer to the Obj_Entry of the
3871 * defining object via the reference parameter DEFOBJ_OUT.
3872 */
3873 static int
symlook_default(SymLook * req,const Obj_Entry * refobj)3874 symlook_default(SymLook *req, const Obj_Entry *refobj)
3875 {
3876 DoneList donelist;
3877 const Objlist_Entry *elm;
3878 SymLook req1;
3879 int res;
3880
3881 donelist_init(&donelist);
3882 symlook_init_from_req(&req1, req);
3883
3884 /* Look first in the referencing object if linked symbolically. */
3885 if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3886 res = symlook_obj(&req1, refobj);
3887 if (res == 0) {
3888 req->sym_out = req1.sym_out;
3889 req->defobj_out = req1.defobj_out;
3890 assert(req->defobj_out != NULL);
3891 }
3892 }
3893
3894 symlook_global(req, &donelist);
3895
3896 /* Search all dlopened DAGs containing the referencing object. */
3897 STAILQ_FOREACH(elm, &refobj->dldags, link) {
3898 if (req->sym_out != NULL &&
3899 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3900 break;
3901 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3902 if (res == 0 && (req->sym_out == NULL ||
3903 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3904 req->sym_out = req1.sym_out;
3905 req->defobj_out = req1.defobj_out;
3906 assert(req->defobj_out != NULL);
3907 }
3908 }
3909
3910 /*
3911 * Search the dynamic linker itself, and possibly resolve the
3912 * symbol from there. This is how the application links to
3913 * dynamic linker services such as dlopen.
3914 */
3915 if (req->sym_out == NULL ||
3916 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3917 res = symlook_obj(&req1, &obj_rtld);
3918 if (res == 0) {
3919 req->sym_out = req1.sym_out;
3920 req->defobj_out = req1.defobj_out;
3921 assert(req->defobj_out != NULL);
3922 }
3923 }
3924
3925 return (req->sym_out != NULL ? 0 : ESRCH);
3926 }
3927
3928 static int
symlook_list(SymLook * req,const Objlist * objlist,DoneList * dlp)3929 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3930 {
3931 const Elf_Sym *def;
3932 const Obj_Entry *defobj;
3933 const Objlist_Entry *elm;
3934 SymLook req1;
3935 int res;
3936
3937 def = NULL;
3938 defobj = NULL;
3939 STAILQ_FOREACH(elm, objlist, link) {
3940 if (donelist_check(dlp, elm->obj))
3941 continue;
3942 symlook_init_from_req(&req1, req);
3943 if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3944 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3945 def = req1.sym_out;
3946 defobj = req1.defobj_out;
3947 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3948 break;
3949 }
3950 }
3951 }
3952 if (def != NULL) {
3953 req->sym_out = def;
3954 req->defobj_out = defobj;
3955 return (0);
3956 }
3957 return (ESRCH);
3958 }
3959
3960 /*
3961 * Search the chain of DAGS cointed to by the given Needed_Entry
3962 * for a symbol of the given name. Each DAG is scanned completely
3963 * before advancing to the next one. Returns a pointer to the symbol,
3964 * or NULL if no definition was found.
3965 */
3966 static int
symlook_needed(SymLook * req,const Needed_Entry * needed,DoneList * dlp)3967 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3968 {
3969 const Elf_Sym *def;
3970 const Needed_Entry *n;
3971 const Obj_Entry *defobj;
3972 SymLook req1;
3973 int res;
3974
3975 def = NULL;
3976 defobj = NULL;
3977 symlook_init_from_req(&req1, req);
3978 for (n = needed; n != NULL; n = n->next) {
3979 if (n->obj == NULL ||
3980 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3981 continue;
3982 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3983 def = req1.sym_out;
3984 defobj = req1.defobj_out;
3985 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3986 break;
3987 }
3988 }
3989 if (def != NULL) {
3990 req->sym_out = def;
3991 req->defobj_out = defobj;
3992 return (0);
3993 }
3994 return (ESRCH);
3995 }
3996
3997 /*
3998 * Search the symbol table of a single shared object for a symbol of
3999 * the given name and version, if requested. Returns a pointer to the
4000 * symbol, or NULL if no definition was found. If the object is
4001 * filter, return filtered symbol from filtee.
4002 *
4003 * The symbol's hash value is passed in for efficiency reasons; that
4004 * eliminates many recomputations of the hash value.
4005 */
4006 int
symlook_obj(SymLook * req,const Obj_Entry * obj)4007 symlook_obj(SymLook *req, const Obj_Entry *obj)
4008 {
4009 DoneList donelist;
4010 SymLook req1;
4011 int flags, res, mres;
4012
4013 /*
4014 * If there is at least one valid hash at this point, we prefer to
4015 * use the faster GNU version if available.
4016 */
4017 if (obj->valid_hash_gnu)
4018 mres = symlook_obj1_gnu(req, obj);
4019 else if (obj->valid_hash_sysv)
4020 mres = symlook_obj1_sysv(req, obj);
4021 else
4022 return (EINVAL);
4023
4024 if (mres == 0) {
4025 if (obj->needed_filtees != NULL) {
4026 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4027 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4028 donelist_init(&donelist);
4029 symlook_init_from_req(&req1, req);
4030 res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4031 if (res == 0) {
4032 req->sym_out = req1.sym_out;
4033 req->defobj_out = req1.defobj_out;
4034 }
4035 return (res);
4036 }
4037 if (obj->needed_aux_filtees != NULL) {
4038 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4039 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4040 donelist_init(&donelist);
4041 symlook_init_from_req(&req1, req);
4042 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4043 if (res == 0) {
4044 req->sym_out = req1.sym_out;
4045 req->defobj_out = req1.defobj_out;
4046 return (res);
4047 }
4048 }
4049 }
4050 return (mres);
4051 }
4052
4053 /* Symbol match routine common to both hash functions */
4054 static bool
matched_symbol(SymLook * req,const Obj_Entry * obj,Sym_Match_Result * result,const unsigned long symnum)4055 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4056 const unsigned long symnum)
4057 {
4058 Elf_Versym verndx;
4059 const Elf_Sym *symp;
4060 const char *strp;
4061
4062 symp = obj->symtab + symnum;
4063 strp = obj->strtab + symp->st_name;
4064
4065 switch (ELF_ST_TYPE(symp->st_info)) {
4066 case STT_FUNC:
4067 case STT_NOTYPE:
4068 case STT_OBJECT:
4069 case STT_COMMON:
4070 case STT_GNU_IFUNC:
4071 if (symp->st_value == 0)
4072 return (false);
4073 /* fallthrough */
4074 case STT_TLS:
4075 if (symp->st_shndx != SHN_UNDEF)
4076 break;
4077 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4078 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4079 break;
4080 /* fallthrough */
4081 default:
4082 return (false);
4083 }
4084 if (strcmp(req->name, strp) != 0)
4085 return (false);
4086
4087 if (req->ventry == NULL) {
4088 if (obj->versyms != NULL) {
4089 verndx = VER_NDX(obj->versyms[symnum]);
4090 if (verndx > obj->vernum) {
4091 _rtld_error(
4092 "%s: symbol %s references wrong version %d",
4093 obj->path, obj->strtab + symnum, verndx);
4094 return (false);
4095 }
4096 /*
4097 * If we are not called from dlsym (i.e. this
4098 * is a normal relocation from unversioned
4099 * binary), accept the symbol immediately if
4100 * it happens to have first version after this
4101 * shared object became versioned. Otherwise,
4102 * if symbol is versioned and not hidden,
4103 * remember it. If it is the only symbol with
4104 * this name exported by the shared object, it
4105 * will be returned as a match by the calling
4106 * function. If symbol is global (verndx < 2)
4107 * accept it unconditionally.
4108 */
4109 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4110 verndx == VER_NDX_GIVEN) {
4111 result->sym_out = symp;
4112 return (true);
4113 }
4114 else if (verndx >= VER_NDX_GIVEN) {
4115 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4116 == 0) {
4117 if (result->vsymp == NULL)
4118 result->vsymp = symp;
4119 result->vcount++;
4120 }
4121 return (false);
4122 }
4123 }
4124 result->sym_out = symp;
4125 return (true);
4126 }
4127 if (obj->versyms == NULL) {
4128 if (object_match_name(obj, req->ventry->name)) {
4129 _rtld_error("%s: object %s should provide version %s "
4130 "for symbol %s", obj_rtld.path, obj->path,
4131 req->ventry->name, obj->strtab + symnum);
4132 return (false);
4133 }
4134 } else {
4135 verndx = VER_NDX(obj->versyms[symnum]);
4136 if (verndx > obj->vernum) {
4137 _rtld_error("%s: symbol %s references wrong version %d",
4138 obj->path, obj->strtab + symnum, verndx);
4139 return (false);
4140 }
4141 if (obj->vertab[verndx].hash != req->ventry->hash ||
4142 strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4143 /*
4144 * Version does not match. Look if this is a
4145 * global symbol and if it is not hidden. If
4146 * global symbol (verndx < 2) is available,
4147 * use it. Do not return symbol if we are
4148 * called by dlvsym, because dlvsym looks for
4149 * a specific version and default one is not
4150 * what dlvsym wants.
4151 */
4152 if ((req->flags & SYMLOOK_DLSYM) ||
4153 (verndx >= VER_NDX_GIVEN) ||
4154 (obj->versyms[symnum] & VER_NDX_HIDDEN))
4155 return (false);
4156 }
4157 }
4158 result->sym_out = symp;
4159 return (true);
4160 }
4161
4162 /*
4163 * Search for symbol using SysV hash function.
4164 * obj->buckets is known not to be NULL at this point; the test for this was
4165 * performed with the obj->valid_hash_sysv assignment.
4166 */
4167 static int
symlook_obj1_sysv(SymLook * req,const Obj_Entry * obj)4168 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4169 {
4170 unsigned long symnum;
4171 Sym_Match_Result matchres;
4172
4173 matchres.sym_out = NULL;
4174 matchres.vsymp = NULL;
4175 matchres.vcount = 0;
4176
4177 for (symnum = obj->buckets[req->hash % obj->nbuckets];
4178 symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4179 if (symnum >= obj->nchains)
4180 return (ESRCH); /* Bad object */
4181
4182 if (matched_symbol(req, obj, &matchres, symnum)) {
4183 req->sym_out = matchres.sym_out;
4184 req->defobj_out = obj;
4185 return (0);
4186 }
4187 }
4188 if (matchres.vcount == 1) {
4189 req->sym_out = matchres.vsymp;
4190 req->defobj_out = obj;
4191 return (0);
4192 }
4193 return (ESRCH);
4194 }
4195
4196 /* Search for symbol using GNU hash function */
4197 static int
symlook_obj1_gnu(SymLook * req,const Obj_Entry * obj)4198 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4199 {
4200 Elf_Addr bloom_word;
4201 const Elf32_Word *hashval;
4202 Elf32_Word bucket;
4203 Sym_Match_Result matchres;
4204 unsigned int h1, h2;
4205 unsigned long symnum;
4206
4207 matchres.sym_out = NULL;
4208 matchres.vsymp = NULL;
4209 matchres.vcount = 0;
4210
4211 /* Pick right bitmask word from Bloom filter array */
4212 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4213 obj->maskwords_bm_gnu];
4214
4215 /* Calculate modulus word size of gnu hash and its derivative */
4216 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4217 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4218
4219 /* Filter out the "definitely not in set" queries */
4220 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4221 return (ESRCH);
4222
4223 /* Locate hash chain and corresponding value element*/
4224 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4225 if (bucket == 0)
4226 return (ESRCH);
4227 hashval = &obj->chain_zero_gnu[bucket];
4228 do {
4229 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4230 symnum = hashval - obj->chain_zero_gnu;
4231 if (matched_symbol(req, obj, &matchres, symnum)) {
4232 req->sym_out = matchres.sym_out;
4233 req->defobj_out = obj;
4234 return (0);
4235 }
4236 }
4237 } while ((*hashval++ & 1) == 0);
4238 if (matchres.vcount == 1) {
4239 req->sym_out = matchres.vsymp;
4240 req->defobj_out = obj;
4241 return (0);
4242 }
4243 return (ESRCH);
4244 }
4245
4246 static void
trace_loaded_objects(Obj_Entry * obj)4247 trace_loaded_objects(Obj_Entry *obj)
4248 {
4249 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4250 int c;
4251
4252 if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
4253 main_local = "";
4254
4255 if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
4256 fmt1 = "\t%o => %p (%x)\n";
4257
4258 if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
4259 fmt2 = "\t%o (%x)\n";
4260
4261 list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
4262
4263 for (; obj; obj = obj->next) {
4264 Needed_Entry *needed;
4265 char *name, *path;
4266 bool is_lib;
4267
4268 if (list_containers && obj->needed != NULL)
4269 rtld_printf("%s:\n", obj->path);
4270 for (needed = obj->needed; needed; needed = needed->next) {
4271 if (needed->obj != NULL) {
4272 if (needed->obj->traced && !list_containers)
4273 continue;
4274 needed->obj->traced = true;
4275 path = needed->obj->path;
4276 } else
4277 path = "not found";
4278
4279 name = (char *)obj->strtab + needed->name;
4280 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
4281
4282 fmt = is_lib ? fmt1 : fmt2;
4283 while ((c = *fmt++) != '\0') {
4284 switch (c) {
4285 default:
4286 rtld_putchar(c);
4287 continue;
4288 case '\\':
4289 switch (c = *fmt) {
4290 case '\0':
4291 continue;
4292 case 'n':
4293 rtld_putchar('\n');
4294 break;
4295 case 't':
4296 rtld_putchar('\t');
4297 break;
4298 }
4299 break;
4300 case '%':
4301 switch (c = *fmt) {
4302 case '\0':
4303 continue;
4304 case '%':
4305 default:
4306 rtld_putchar(c);
4307 break;
4308 case 'A':
4309 rtld_putstr(main_local);
4310 break;
4311 case 'a':
4312 rtld_putstr(obj_main->path);
4313 break;
4314 case 'o':
4315 rtld_putstr(name);
4316 break;
4317 case 'p':
4318 rtld_putstr(path);
4319 break;
4320 case 'x':
4321 rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4322 0);
4323 break;
4324 }
4325 break;
4326 }
4327 ++fmt;
4328 }
4329 }
4330 }
4331 }
4332
4333 /*
4334 * Unload a dlopened object and its dependencies from memory and from
4335 * our data structures. It is assumed that the DAG rooted in the
4336 * object has already been unreferenced, and that the object has a
4337 * reference count of 0.
4338 */
4339 static void
unload_object(Obj_Entry * root)4340 unload_object(Obj_Entry *root)
4341 {
4342 Obj_Entry *obj;
4343 Obj_Entry **linkp;
4344
4345 assert(root->refcount == 0);
4346
4347 /*
4348 * Pass over the DAG removing unreferenced objects from
4349 * appropriate lists.
4350 */
4351 unlink_object(root);
4352
4353 /* Unmap all objects that are no longer referenced. */
4354 linkp = &obj_list->next;
4355 while ((obj = *linkp) != NULL) {
4356 if (obj->refcount == 0) {
4357 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
4358 obj->path);
4359 dbg("unloading \"%s\"", obj->path);
4360 unload_filtees(root);
4361 munmap(obj->mapbase, obj->mapsize);
4362 linkmap_delete(obj);
4363 *linkp = obj->next;
4364 obj_count--;
4365 obj_free(obj);
4366 } else
4367 linkp = &obj->next;
4368 }
4369 obj_tail = linkp;
4370 }
4371
4372 static void
unlink_object(Obj_Entry * root)4373 unlink_object(Obj_Entry *root)
4374 {
4375 Objlist_Entry *elm;
4376
4377 if (root->refcount == 0) {
4378 /* Remove the object from the RTLD_GLOBAL list. */
4379 objlist_remove(&list_global, root);
4380
4381 /* Remove the object from all objects' DAG lists. */
4382 STAILQ_FOREACH(elm, &root->dagmembers, link) {
4383 objlist_remove(&elm->obj->dldags, root);
4384 if (elm->obj != root)
4385 unlink_object(elm->obj);
4386 }
4387 }
4388 }
4389
4390 static void
ref_dag(Obj_Entry * root)4391 ref_dag(Obj_Entry *root)
4392 {
4393 Objlist_Entry *elm;
4394
4395 assert(root->dag_inited);
4396 STAILQ_FOREACH(elm, &root->dagmembers, link)
4397 elm->obj->refcount++;
4398 }
4399
4400 static void
unref_dag(Obj_Entry * root)4401 unref_dag(Obj_Entry *root)
4402 {
4403 Objlist_Entry *elm;
4404
4405 assert(root->dag_inited);
4406 STAILQ_FOREACH(elm, &root->dagmembers, link)
4407 elm->obj->refcount--;
4408 }
4409
4410 /*
4411 * Common code for MD __tls_get_addr().
4412 */
4413 void *
tls_get_addr_common(Elf_Addr ** dtvp,int index,size_t offset)4414 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
4415 {
4416 Elf_Addr* dtv = *dtvp;
4417 RtldLockState lockstate;
4418
4419 /* Check dtv generation in case new modules have arrived */
4420 if (dtv[0] != tls_dtv_generation) {
4421 Elf_Addr* newdtv;
4422 int to_copy;
4423
4424 wlock_acquire(rtld_bind_lock, &lockstate);
4425 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4426 to_copy = dtv[1];
4427 if (to_copy > tls_max_index)
4428 to_copy = tls_max_index;
4429 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4430 newdtv[0] = tls_dtv_generation;
4431 newdtv[1] = tls_max_index;
4432 free(dtv);
4433 cpu_sfence();
4434 dtv = *dtvp = newdtv;
4435 lock_release(rtld_bind_lock, &lockstate);
4436 }
4437
4438 /* Dynamically allocate module TLS if necessary */
4439 if (!dtv[index + 1]) {
4440 /* Signal safe, wlock will block out signals. */
4441 wlock_acquire(rtld_bind_lock, &lockstate);
4442 dtv = *dtvp;
4443 if (!dtv[index + 1])
4444 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4445 lock_release(rtld_bind_lock, &lockstate);
4446 }
4447 return ((void *)(dtv[index + 1] + offset));
4448 }
4449
4450 #if defined(RTLD_STATIC_TLS_VARIANT_II)
4451
4452 /*
4453 * Allocate the static TLS area. Return a pointer to the TCB. The
4454 * static area is based on negative offsets relative to the tcb.
4455 *
4456 * The TCB contains an errno pointer for the system call layer, but because
4457 * we are the RTLD we really have no idea how the caller was compiled so
4458 * the information has to be passed in. errno can either be:
4459 *
4460 * type 0 errno is a simple non-TLS global pointer.
4461 * (special case for e.g. libc_rtld)
4462 * type 1 errno accessed by GOT entry (dynamically linked programs)
4463 * type 2 errno accessed by %gs:OFFSET (statically linked programs)
4464 */
4465 struct tls_tcb *
allocate_tls(Obj_Entry * objs)4466 allocate_tls(Obj_Entry *objs)
4467 {
4468 Obj_Entry *obj;
4469 size_t data_size;
4470 size_t dtv_size;
4471 struct tls_tcb *tcb;
4472 Elf_Addr *dtv;
4473 Elf_Addr addr;
4474
4475 /*
4476 * Allocate the new TCB. static TLS storage is placed just before the
4477 * TCB to support the %gs:OFFSET (negative offset) model.
4478 */
4479 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4480 ~RTLD_STATIC_TLS_ALIGN_MASK;
4481 tcb = malloc(data_size + sizeof(*tcb));
4482 tcb = (void *)((char *)tcb + data_size); /* actual tcb location */
4483
4484 dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
4485 dtv = malloc(dtv_size);
4486 bzero(dtv, dtv_size);
4487
4488 #ifdef RTLD_TCB_HAS_SELF_POINTER
4489 tcb->tcb_self = tcb;
4490 #endif
4491 tcb->tcb_dtv = dtv;
4492 tcb->tcb_pthread = NULL;
4493
4494 dtv[0] = tls_dtv_generation;
4495 dtv[1] = tls_max_index;
4496
4497 for (obj = objs; obj; obj = obj->next) {
4498 if (obj->tlsoffset) {
4499 addr = (Elf_Addr)tcb - obj->tlsoffset;
4500 memset((void *)(addr + obj->tlsinitsize),
4501 0, obj->tlssize - obj->tlsinitsize);
4502 if (obj->tlsinit) {
4503 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4504 obj->static_tls_copied = true;
4505 }
4506 dtv[obj->tlsindex + 1] = addr;
4507 }
4508 }
4509 return(tcb);
4510 }
4511
4512 void
free_tls(struct tls_tcb * tcb)4513 free_tls(struct tls_tcb *tcb)
4514 {
4515 Elf_Addr *dtv;
4516 int dtv_size, i;
4517 Elf_Addr tls_start, tls_end;
4518 size_t data_size;
4519
4520 data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
4521 ~RTLD_STATIC_TLS_ALIGN_MASK;
4522
4523 dtv = tcb->tcb_dtv;
4524 dtv_size = dtv[1];
4525 tls_end = (Elf_Addr)tcb;
4526 tls_start = (Elf_Addr)tcb - data_size;
4527 for (i = 0; i < dtv_size; i++) {
4528 if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
4529 free((void *)dtv[i+2]);
4530 }
4531 }
4532 free(dtv);
4533
4534 free((void*) tls_start);
4535 }
4536
4537 #else
4538 #error "Unsupported TLS layout"
4539 #endif
4540
4541 /*
4542 * Allocate TLS block for module with given index.
4543 */
4544 void *
allocate_module_tls(int index)4545 allocate_module_tls(int index)
4546 {
4547 Obj_Entry* obj;
4548 char* p;
4549
4550 for (obj = obj_list; obj; obj = obj->next) {
4551 if (obj->tlsindex == index)
4552 break;
4553 }
4554 if (!obj) {
4555 _rtld_error("Can't find module with TLS index %d", index);
4556 die();
4557 }
4558
4559 if (obj->tls_static) {
4560 #if defined(RTLD_STATIC_TLS_VARIANT_II)
4561 p = (char *)tls_get_tcb() - obj->tlsoffset;
4562 #else
4563 #error "Unsupported TLS layout"
4564 #endif
4565 return p;
4566 }
4567
4568 p = malloc(obj->tlssize);
4569 if (p == NULL) {
4570 _rtld_error("Cannot allocate TLS block for index %d", index);
4571 die();
4572 }
4573 memcpy(p, obj->tlsinit, obj->tlsinitsize);
4574 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4575
4576 return p;
4577 }
4578
4579 bool
allocate_tls_offset(Obj_Entry * obj)4580 allocate_tls_offset(Obj_Entry *obj)
4581 {
4582 size_t off;
4583
4584 if (obj->tls_static)
4585 return true;
4586
4587 if (obj->tls_dynamic)
4588 return false;
4589
4590 if (obj->tlssize == 0) {
4591 obj->tls_static = true;
4592 return true;
4593 }
4594
4595 if (obj->tlsindex == 1)
4596 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4597 else
4598 off = calculate_tls_offset(tls_last_offset, tls_last_size,
4599 obj->tlssize, obj->tlsalign);
4600
4601 /*
4602 * If we have already fixed the size of the static TLS block, we
4603 * must stay within that size. When allocating the static TLS, we
4604 * leave a small amount of space spare to be used for dynamically
4605 * loading modules which use static TLS.
4606 */
4607 if (tls_static_space) {
4608 if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4609 return false;
4610 }
4611
4612 tls_last_offset = obj->tlsoffset = off;
4613 tls_last_size = obj->tlssize;
4614 obj->tls_static = true;
4615
4616 return true;
4617 }
4618
4619 void
free_tls_offset(Obj_Entry * obj)4620 free_tls_offset(Obj_Entry *obj)
4621 {
4622 #ifdef RTLD_STATIC_TLS_VARIANT_II
4623 /*
4624 * If we were the last thing to allocate out of the static TLS
4625 * block, we give our space back to the 'allocator'. This is a
4626 * simplistic workaround to allow libGL.so.1 to be loaded and
4627 * unloaded multiple times. We only handle the Variant II
4628 * mechanism for now - this really needs a proper allocator.
4629 */
4630 if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4631 == calculate_tls_end(tls_last_offset, tls_last_size)) {
4632 tls_last_offset -= obj->tlssize;
4633 tls_last_size = 0;
4634 }
4635 #endif
4636 }
4637
4638 struct tls_tcb *
_rtld_allocate_tls(void)4639 _rtld_allocate_tls(void)
4640 {
4641 struct tls_tcb *new_tcb;
4642 RtldLockState lockstate;
4643
4644 wlock_acquire(rtld_bind_lock, &lockstate);
4645 new_tcb = allocate_tls(obj_list);
4646 lock_release(rtld_bind_lock, &lockstate);
4647
4648 return (new_tcb);
4649 }
4650
4651 void
_rtld_free_tls(struct tls_tcb * tcb)4652 _rtld_free_tls(struct tls_tcb *tcb)
4653 {
4654 RtldLockState lockstate;
4655
4656 wlock_acquire(rtld_bind_lock, &lockstate);
4657 free_tls(tcb);
4658 lock_release(rtld_bind_lock, &lockstate);
4659 }
4660
4661 static void
object_add_name(Obj_Entry * obj,const char * name)4662 object_add_name(Obj_Entry *obj, const char *name)
4663 {
4664 Name_Entry *entry;
4665 size_t len;
4666
4667 len = strlen(name);
4668 entry = malloc(sizeof(Name_Entry) + len);
4669
4670 if (entry != NULL) {
4671 strcpy(entry->name, name);
4672 STAILQ_INSERT_TAIL(&obj->names, entry, link);
4673 }
4674 }
4675
4676 static int
object_match_name(const Obj_Entry * obj,const char * name)4677 object_match_name(const Obj_Entry *obj, const char *name)
4678 {
4679 Name_Entry *entry;
4680
4681 STAILQ_FOREACH(entry, &obj->names, link) {
4682 if (strcmp(name, entry->name) == 0)
4683 return (1);
4684 }
4685 return (0);
4686 }
4687
4688 static Obj_Entry *
locate_dependency(const Obj_Entry * obj,const char * name)4689 locate_dependency(const Obj_Entry *obj, const char *name)
4690 {
4691 const Objlist_Entry *entry;
4692 const Needed_Entry *needed;
4693
4694 STAILQ_FOREACH(entry, &list_main, link) {
4695 if (object_match_name(entry->obj, name))
4696 return entry->obj;
4697 }
4698
4699 for (needed = obj->needed; needed != NULL; needed = needed->next) {
4700 if (strcmp(obj->strtab + needed->name, name) == 0 ||
4701 (needed->obj != NULL && object_match_name(needed->obj, name))) {
4702 /*
4703 * If there is DT_NEEDED for the name we are looking for,
4704 * we are all set. Note that object might not be found if
4705 * dependency was not loaded yet, so the function can
4706 * return NULL here. This is expected and handled
4707 * properly by the caller.
4708 */
4709 return (needed->obj);
4710 }
4711 }
4712 _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4713 obj->path, name);
4714 die();
4715 }
4716
4717 static int
check_object_provided_version(Obj_Entry * refobj,const Obj_Entry * depobj,const Elf_Vernaux * vna)4718 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4719 const Elf_Vernaux *vna)
4720 {
4721 const Elf_Verdef *vd;
4722 const char *vername;
4723
4724 vername = refobj->strtab + vna->vna_name;
4725 vd = depobj->verdef;
4726 if (vd == NULL) {
4727 _rtld_error("%s: version %s required by %s not defined",
4728 depobj->path, vername, refobj->path);
4729 return (-1);
4730 }
4731 for (;;) {
4732 if (vd->vd_version != VER_DEF_CURRENT) {
4733 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4734 depobj->path, vd->vd_version);
4735 return (-1);
4736 }
4737 if (vna->vna_hash == vd->vd_hash) {
4738 const Elf_Verdaux *aux = (const Elf_Verdaux *)
4739 ((char *)vd + vd->vd_aux);
4740 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4741 return (0);
4742 }
4743 if (vd->vd_next == 0)
4744 break;
4745 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4746 }
4747 if (vna->vna_flags & VER_FLG_WEAK)
4748 return (0);
4749 _rtld_error("%s: version %s required by %s not found",
4750 depobj->path, vername, refobj->path);
4751 return (-1);
4752 }
4753
4754 static int
rtld_verify_object_versions(Obj_Entry * obj)4755 rtld_verify_object_versions(Obj_Entry *obj)
4756 {
4757 const Elf_Verneed *vn;
4758 const Elf_Verdef *vd;
4759 const Elf_Verdaux *vda;
4760 const Elf_Vernaux *vna;
4761 const Obj_Entry *depobj;
4762 int maxvernum, vernum;
4763
4764 if (obj->ver_checked)
4765 return (0);
4766 obj->ver_checked = true;
4767
4768 maxvernum = 0;
4769 /*
4770 * Walk over defined and required version records and figure out
4771 * max index used by any of them. Do very basic sanity checking
4772 * while there.
4773 */
4774 vn = obj->verneed;
4775 while (vn != NULL) {
4776 if (vn->vn_version != VER_NEED_CURRENT) {
4777 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4778 obj->path, vn->vn_version);
4779 return (-1);
4780 }
4781 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4782 for (;;) {
4783 vernum = VER_NEED_IDX(vna->vna_other);
4784 if (vernum > maxvernum)
4785 maxvernum = vernum;
4786 if (vna->vna_next == 0)
4787 break;
4788 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4789 }
4790 if (vn->vn_next == 0)
4791 break;
4792 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4793 }
4794
4795 vd = obj->verdef;
4796 while (vd != NULL) {
4797 if (vd->vd_version != VER_DEF_CURRENT) {
4798 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4799 obj->path, vd->vd_version);
4800 return (-1);
4801 }
4802 vernum = VER_DEF_IDX(vd->vd_ndx);
4803 if (vernum > maxvernum)
4804 maxvernum = vernum;
4805 if (vd->vd_next == 0)
4806 break;
4807 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4808 }
4809
4810 if (maxvernum == 0)
4811 return (0);
4812
4813 /*
4814 * Store version information in array indexable by version index.
4815 * Verify that object version requirements are satisfied along the
4816 * way.
4817 */
4818 obj->vernum = maxvernum + 1;
4819 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4820
4821 vd = obj->verdef;
4822 while (vd != NULL) {
4823 if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4824 vernum = VER_DEF_IDX(vd->vd_ndx);
4825 assert(vernum <= maxvernum);
4826 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4827 obj->vertab[vernum].hash = vd->vd_hash;
4828 obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4829 obj->vertab[vernum].file = NULL;
4830 obj->vertab[vernum].flags = 0;
4831 }
4832 if (vd->vd_next == 0)
4833 break;
4834 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4835 }
4836
4837 vn = obj->verneed;
4838 while (vn != NULL) {
4839 depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4840 if (depobj == NULL)
4841 return (-1);
4842 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4843 for (;;) {
4844 if (check_object_provided_version(obj, depobj, vna))
4845 return (-1);
4846 vernum = VER_NEED_IDX(vna->vna_other);
4847 assert(vernum <= maxvernum);
4848 obj->vertab[vernum].hash = vna->vna_hash;
4849 obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4850 obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4851 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4852 VER_INFO_HIDDEN : 0;
4853 if (vna->vna_next == 0)
4854 break;
4855 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4856 }
4857 if (vn->vn_next == 0)
4858 break;
4859 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4860 }
4861 return 0;
4862 }
4863
4864 static int
rtld_verify_versions(const Objlist * objlist)4865 rtld_verify_versions(const Objlist *objlist)
4866 {
4867 Objlist_Entry *entry;
4868 int rc;
4869
4870 rc = 0;
4871 STAILQ_FOREACH(entry, objlist, link) {
4872 /*
4873 * Skip dummy objects or objects that have their version requirements
4874 * already checked.
4875 */
4876 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4877 continue;
4878 if (rtld_verify_object_versions(entry->obj) == -1) {
4879 rc = -1;
4880 if (ld_tracing == NULL)
4881 break;
4882 }
4883 }
4884 if (rc == 0 || ld_tracing != NULL)
4885 rc = rtld_verify_object_versions(&obj_rtld);
4886 return rc;
4887 }
4888
4889 const Ver_Entry *
fetch_ventry(const Obj_Entry * obj,unsigned long symnum)4890 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4891 {
4892 Elf_Versym vernum;
4893
4894 if (obj->vertab) {
4895 vernum = VER_NDX(obj->versyms[symnum]);
4896 if (vernum >= obj->vernum) {
4897 _rtld_error("%s: symbol %s has wrong verneed value %d",
4898 obj->path, obj->strtab + symnum, vernum);
4899 } else if (obj->vertab[vernum].hash != 0) {
4900 return &obj->vertab[vernum];
4901 }
4902 }
4903 return NULL;
4904 }
4905
4906 int
_rtld_get_stack_prot(void)4907 _rtld_get_stack_prot(void)
4908 {
4909
4910 return (stack_prot);
4911 }
4912
4913 static void
map_stacks_exec(RtldLockState * lockstate)4914 map_stacks_exec(RtldLockState *lockstate)
4915 {
4916 return;
4917 /*
4918 * Stack protection must be implemented in the kernel before the dynamic
4919 * linker can handle PT_GNU_STACK sections.
4920 * The following is the FreeBSD implementation of map_stacks_exec()
4921 * void (*thr_map_stacks_exec)(void);
4922 *
4923 * if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4924 * return;
4925 * thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4926 * get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4927 * if (thr_map_stacks_exec != NULL) {
4928 * stack_prot |= PROT_EXEC;
4929 * thr_map_stacks_exec();
4930 * }
4931 */
4932 }
4933
4934 /*
4935 * Only called after all primary shared libraries are loaded (EARLY is
4936 * not set). Resolves the static TLS distribution function at first-call.
4937 * This is typically a weak libc symbol that is overrideen by the threading
4938 * library.
4939 */
4940 static void
distribute_static_tls(Objlist * list,RtldLockState * lockstate)4941 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
4942 {
4943 Objlist_Entry *elm;
4944 Obj_Entry *obj;
4945 static void (*dtlsfunc)(size_t, void *, size_t, size_t);
4946
4947 /*
4948 * First time, resolve "_pthread_distribute_static_tls".
4949 */
4950 if (dtlsfunc == NULL) {
4951 dtlsfunc = (void *)dlfunc(RTLD_ALL,
4952 "_pthread_distribute_static_tls");
4953 if (dtlsfunc == NULL)
4954 return;
4955 }
4956
4957 /*
4958 * Initialize static TLS data for the object list using the callback
4959 * function (to either libc or pthreads).
4960 */
4961 STAILQ_FOREACH(elm, list, link) {
4962 obj = elm->obj;
4963 if (/*obj->marker ||*/ !obj->tls_static || obj->static_tls_copied)
4964 continue;
4965 dtlsfunc(obj->tlsoffset, obj->tlsinit,
4966 obj->tlsinitsize, obj->tlssize);
4967 obj->static_tls_copied = true;
4968 }
4969 }
4970
4971 void
symlook_init(SymLook * dst,const char * name)4972 symlook_init(SymLook *dst, const char *name)
4973 {
4974
4975 bzero(dst, sizeof(*dst));
4976 dst->name = name;
4977 dst->hash = elf_hash(name);
4978 dst->hash_gnu = gnu_hash(name);
4979 }
4980
4981 static void
symlook_init_from_req(SymLook * dst,const SymLook * src)4982 symlook_init_from_req(SymLook *dst, const SymLook *src)
4983 {
4984
4985 dst->name = src->name;
4986 dst->hash = src->hash;
4987 dst->hash_gnu = src->hash_gnu;
4988 dst->ventry = src->ventry;
4989 dst->flags = src->flags;
4990 dst->defobj_out = NULL;
4991 dst->sym_out = NULL;
4992 dst->lockstate = src->lockstate;
4993 }
4994
4995
4996 /*
4997 * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
4998 */
4999 static int
parse_libdir(const char * str)5000 parse_libdir(const char *str)
5001 {
5002 static const int RADIX = 10; /* XXXJA: possibly support hex? */
5003 const char *orig;
5004 int fd;
5005 char c;
5006
5007 orig = str;
5008 fd = 0;
5009 for (c = *str; c != '\0'; c = *++str) {
5010 if (c < '0' || c > '9')
5011 return (-1);
5012
5013 fd *= RADIX;
5014 fd += c - '0';
5015 }
5016
5017 /* Make sure we actually parsed something. */
5018 if (str == orig) {
5019 _rtld_error("failed to parse directory FD from '%s'", str);
5020 return (-1);
5021 }
5022 return (fd);
5023 }
5024
5025 #ifdef ENABLE_OSRELDATE
5026 /*
5027 * Overrides for libc_pic-provided functions.
5028 */
5029
5030 int
__getosreldate(void)5031 __getosreldate(void)
5032 {
5033 size_t len;
5034 int oid[2];
5035 int error, osrel;
5036
5037 if (osreldate != 0)
5038 return (osreldate);
5039
5040 oid[0] = CTL_KERN;
5041 oid[1] = KERN_OSRELDATE;
5042 osrel = 0;
5043 len = sizeof(osrel);
5044 error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5045 if (error == 0 && osrel > 0 && len == sizeof(osrel))
5046 osreldate = osrel;
5047 return (osreldate);
5048 }
5049 #endif
5050
5051 /*
5052 * Ask the kernel for the extra tls space to allocate after calculating
5053 * base tls requirements in rtld-elf. 5.9 or later.
5054 */
5055 static int
__getstatictlsextra(void)5056 __getstatictlsextra(void)
5057 {
5058 size_t len;
5059 int oid[2];
5060 int error;
5061 int tls_extra;
5062
5063 oid[0] = CTL_KERN;
5064 oid[1] = KERN_STATIC_TLS_EXTRA;
5065 len = sizeof(tls_extra);
5066 error = sysctl(oid, 2, &tls_extra, &len, NULL, 0);
5067 if (error || len != sizeof(tls_extra))
5068 tls_extra = RTLD_STATIC_TLS_EXTRA_DEFAULT;
5069 if (tls_extra < RTLD_STATIC_TLS_EXTRA_MIN)
5070 tls_extra = RTLD_STATIC_TLS_EXTRA_MIN;
5071 if (tls_extra > RTLD_STATIC_TLS_EXTRA_MAX)
5072 tls_extra = RTLD_STATIC_TLS_EXTRA_MAX;
5073 return tls_extra;
5074 }
5075
5076 /*
5077 * No unresolved symbols for rtld.
5078 */
5079 void
__pthread_cxa_finalize(struct dl_phdr_info * a)5080 __pthread_cxa_finalize(struct dl_phdr_info *a)
5081 {
5082 }
5083
5084 const char *
rtld_strerror(int errnum)5085 rtld_strerror(int errnum)
5086 {
5087
5088 if (errnum < 0 || errnum >= sys_nerr)
5089 return ("Unknown error");
5090 return (sys_errlist[errnum]);
5091 }
5092