xref: /freebsd/libexec/rtld-elf/rtld.h (revision 4f8f43b06ed07e96a250855488cc531799d5b78f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #ifndef RTLD_H /* { */
29 #define RTLD_H 1
30 
31 #include <machine/elf.h>
32 #include <sys/types.h>
33 #include <sys/queue.h>
34 
35 #include <elf-hints.h>
36 #include <link.h>
37 #include <stdarg.h>
38 #include <stdbool.h>
39 #include <setjmp.h>
40 #include <stddef.h>
41 
42 #include "rtld_lock.h"
43 #include "rtld_machdep.h"
44 
45 #define NEW(type)	((type *) xmalloc(sizeof(type)))
46 #define CNEW(type)	((type *) xcalloc(1, sizeof(type)))
47 
48 extern size_t tls_last_offset;
49 extern size_t tls_last_size;
50 extern size_t tls_static_space;
51 extern Elf_Addr tls_dtv_generation;
52 extern int tls_max_index;
53 
54 extern int npagesizes;
55 extern size_t *pagesizes;
56 extern size_t page_size;
57 
58 extern int main_argc;
59 extern char **main_argv;
60 extern char **environ;
61 
62 struct stat;
63 struct Struct_Obj_Entry;
64 
65 /* Lists of shared objects */
66 typedef struct Struct_Objlist_Entry {
67     STAILQ_ENTRY(Struct_Objlist_Entry) link;
68     struct Struct_Obj_Entry *obj;
69 } Objlist_Entry;
70 
71 typedef STAILQ_HEAD(Struct_Objlist, Struct_Objlist_Entry) Objlist;
72 
73 /* Types of init and fini functions */
74 typedef void (*InitFunc)(void);
75 typedef void (*InitArrFunc)(int, char **, char **);
76 
77 /* Lists of shared object dependencies */
78 typedef struct Struct_Needed_Entry {
79     struct Struct_Needed_Entry *next;
80     struct Struct_Obj_Entry *obj;
81     unsigned long name;		/* Offset of name in string table */
82 } Needed_Entry;
83 
84 typedef struct Struct_Name_Entry {
85     STAILQ_ENTRY(Struct_Name_Entry) link;
86     char   name[1];
87 } Name_Entry;
88 
89 /* Lock object */
90 typedef struct Struct_LockInfo {
91     void *context;		/* Client context for creating locks */
92     void *thelock;		/* The one big lock */
93     /* Debugging aids. */
94     volatile int rcount;	/* Number of readers holding lock */
95     volatile int wcount;	/* Number of writers holding lock */
96     /* Methods */
97     void *(*lock_create)(void *context);
98     void (*rlock_acquire)(void *lock);
99     void (*wlock_acquire)(void *lock);
100     void (*rlock_release)(void *lock);
101     void (*wlock_release)(void *lock);
102     void (*lock_destroy)(void *lock);
103     void (*context_destroy)(void *context);
104 } LockInfo;
105 
106 typedef struct Struct_Ver_Entry {
107 	Elf_Word     hash;
108 	unsigned int flags;
109 	const char  *name;
110 	const char  *file;
111 } Ver_Entry;
112 
113 typedef struct Struct_Sym_Match_Result {
114     const Elf_Sym *sym_out;
115     const Elf_Sym *vsymp;
116     int vcount;
117 } Sym_Match_Result;
118 
119 #define VER_INFO_HIDDEN	0x01
120 
121 /*
122  * Shared object descriptor.
123  *
124  * Items marked with "(%)" are dynamically allocated, and must be freed
125  * when the structure is destroyed.
126  *
127  * CAUTION: It appears that the JDK port peeks into these structures.
128  * It looks at "next" and "mapbase" at least.  Don't add new members
129  * near the front, until this can be straightened out.
130  */
131 typedef struct Struct_Obj_Entry {
132     /*
133      * These two items have to be set right for compatibility with the
134      * original ElfKit crt1.o.
135      */
136     Elf_Size magic;		/* Magic number (sanity check) */
137     Elf_Size version;		/* Version number of struct format */
138 
139     TAILQ_ENTRY(Struct_Obj_Entry) next;
140     char *path;			/* Pathname of underlying file (%) */
141     char *origin_path;		/* Directory path of origin file */
142     int refcount;		/* DAG references */
143     int holdcount;		/* Count of transient references */
144     int dl_refcount;		/* Number of times loaded by dlopen */
145 
146     /* These items are computed by map_object() or by digest_phdr(). */
147     caddr_t mapbase;		/* Base address of mapped region */
148     size_t mapsize;		/* Size of mapped region in bytes */
149     Elf_Addr vaddrbase;		/* Base address in shared object file */
150     caddr_t relocbase;		/* Relocation constant = mapbase - vaddrbase */
151     const Elf_Dyn *dynamic;	/* Dynamic section */
152     caddr_t entry;		/* Entry point */
153     const Elf_Phdr *phdr;	/* Program header if it is mapped, else NULL */
154     size_t phsize;		/* Size of program header in bytes */
155     const char *interp;		/* Pathname of the interpreter, if any */
156     Elf_Word stack_flags;
157 
158     /* TLS information */
159     int tlsindex;		/* Index in DTV for this module */
160     void *tlsinit;		/* Base address of TLS init block */
161     size_t tlsinitsize;		/* Size of TLS init block for this module */
162     size_t tlssize;		/* Size of TLS block for this module */
163     size_t tlsoffset;		/* Offset of static TLS block for this module */
164     size_t tlsalign;		/* Alignment of static TLS block */
165     size_t tlspoffset;		/* p_offset of the static TLS block */
166 
167     caddr_t relro_page;
168     size_t relro_size;
169 
170     /* Items from the dynamic section. */
171     Elf_Addr *pltgot;		/* PLT or GOT, depending on architecture */
172     const Elf_Rel *rel;		/* Relocation entries */
173     unsigned long relsize;	/* Size in bytes of relocation info */
174     const Elf_Rela *rela;	/* Relocation entries with addend */
175     unsigned long relasize;	/* Size in bytes of addend relocation info */
176     const Elf_Relr *relr;	/* RELR relocation entries */
177     unsigned long relrsize;	/* Size in bytes of RELR relocations */
178     const Elf_Rel *pltrel;	/* PLT relocation entries */
179     unsigned long pltrelsize;	/* Size in bytes of PLT relocation info */
180     const Elf_Rela *pltrela;	/* PLT relocation entries with addend */
181     unsigned long pltrelasize;	/* Size in bytes of PLT addend reloc info */
182     const Elf_Sym *symtab;	/* Symbol table */
183     const char *strtab;		/* String table */
184     unsigned long strsize;	/* Size in bytes of string table */
185 #ifdef __powerpc__
186 #ifdef __powerpc64__
187     Elf_Addr glink;		/* GLINK PLT call stub section */
188 #else
189     Elf_Addr *gotptr;		/* GOT pointer (secure-plt only) */
190 #endif
191 #endif
192 
193     const Elf_Verneed *verneed; /* Required versions. */
194     Elf_Word verneednum;	/* Number of entries in verneed table */
195     const Elf_Verdef  *verdef;	/* Provided versions. */
196     Elf_Word verdefnum;		/* Number of entries in verdef table */
197     const Elf_Versym *versyms;  /* Symbol versions table */
198 
199     const Elf_Hashelt *buckets;	/* Hash table buckets array */
200     unsigned long nbuckets;	/* Number of buckets */
201     const Elf_Hashelt *chains;	/* Hash table chain array */
202     unsigned long nchains;	/* Number of entries in chain array */
203 
204     Elf32_Word nbuckets_gnu;		/* Number of GNU hash buckets*/
205     Elf32_Word symndx_gnu;		/* 1st accessible symbol on dynsym table */
206     Elf32_Word maskwords_bm_gnu;  	/* Bloom filter words - 1 (bitmask) */
207     Elf32_Word shift2_gnu;		/* Bloom filter shift count */
208     Elf32_Word dynsymcount;		/* Total entries in dynsym table */
209     const Elf_Addr *bloom_gnu;		/* Bloom filter used by GNU hash func */
210     const Elf_Hashelt *buckets_gnu;	/* GNU hash table bucket array */
211     const Elf_Hashelt *chain_zero_gnu;	/* GNU hash table value array (Zeroed) */
212 
213     const char *rpath;		/* Search path specified in object */
214     const char *runpath;	/* Search path with different priority */
215     Needed_Entry *needed;	/* Shared objects needed by this one (%) */
216     Needed_Entry *needed_filtees;
217     Needed_Entry *needed_aux_filtees;
218 
219     STAILQ_HEAD(, Struct_Name_Entry) names; /* List of names for this object we
220 					       know about. */
221     Ver_Entry *vertab;		/* Versions required /defined by this object */
222     int vernum;			/* Number of entries in vertab */
223 
224     Elf_Addr init;		/* Initialization function to call */
225     Elf_Addr fini;		/* Termination function to call */
226     Elf_Addr preinit_array;	/* Pre-initialization array of functions */
227     Elf_Addr init_array;	/* Initialization array of functions */
228     Elf_Addr fini_array;	/* Termination array of functions */
229     int preinit_array_num;	/* Number of entries in preinit_array */
230     int init_array_num; 	/* Number of entries in init_array */
231     int fini_array_num; 	/* Number of entries in fini_array */
232 
233     int32_t osrel;		/* OSREL note value */
234     uint32_t fctl0;		/* FEATURE_CONTROL note desc[0] value */
235 
236     bool mainprog : 1;		/* True if this is the main program */
237     bool rtld : 1;		/* True if this is the dynamic linker */
238     bool relocated : 1;		/* True if processed by relocate_objects() */
239     bool ver_checked : 1;	/* True if processed by rtld_verify_object_versions */
240     bool textrel : 1;		/* True if there are relocations to text seg */
241     bool symbolic : 1;		/* True if generated with "-Bsymbolic" */
242     bool bind_now : 1;		/* True if all relocations should be made first */
243     bool traced : 1;		/* Already printed in ldd trace output */
244     bool jmpslots_done : 1;	/* Already have relocated the jump slots */
245     bool init_done : 1;		/* Already have added object to init list */
246     bool tls_static : 1;	/* Already allocated offset for static TLS */
247     bool tls_dynamic : 1;	/* A non-static DTV entry has been allocated */
248     bool phdr_alloc : 1;	/* Phdr is allocated and needs to be freed. */
249     bool z_origin : 1;		/* Process rpath and soname tokens */
250     bool z_nodelete : 1;	/* Do not unload the object and dependencies */
251     bool z_noopen : 1;		/* Do not load on dlopen */
252     bool z_loadfltr : 1;	/* Immediately load filtees */
253     bool z_interpose : 1;	/* Interpose all objects but main */
254     bool z_nodeflib : 1;	/* Don't search default library path */
255     bool z_global : 1;		/* Make the object global */
256     bool z_pie : 1;		/* Object proclaimed itself PIE executable */
257     bool static_tls : 1;	/* Needs static TLS allocation */
258     bool static_tls_copied : 1;	/* Needs static TLS copying */
259     bool ref_nodel : 1;		/* Refcount increased to prevent dlclose */
260     bool init_scanned: 1;	/* Object is already on init list. */
261     bool on_fini_list: 1;	/* Object is already on fini list. */
262     bool dag_inited : 1;	/* Object has its DAG initialized. */
263     bool filtees_loaded : 1;	/* Filtees loaded */
264     bool irelative : 1;		/* Object has R_MACHDEP_IRELATIVE relocs */
265     bool irelative_nonplt : 1;	/* Object has R_MACHDEP_IRELATIVE non-plt relocs */
266     bool gnu_ifunc : 1;		/* Object has references to STT_GNU_IFUNC */
267     bool non_plt_gnu_ifunc : 1;	/* Object has non-plt IFUNC references */
268     bool ifuncs_resolved : 1;	/* Object ifuncs were already resolved */
269     bool crt_no_init : 1;	/* Object' crt does not call _init/_fini */
270     bool valid_hash_sysv : 1;	/* A valid System V hash hash tag is available */
271     bool valid_hash_gnu : 1;	/* A valid GNU hash tag is available */
272     bool dlopened : 1;		/* dlopen()-ed (vs. load statically) */
273     bool marker : 1;		/* marker on the global obj list */
274     bool unholdfree : 1;	/* unmap upon last unhold */
275     bool doomed : 1;		/* Object cannot be referenced */
276 
277     struct link_map linkmap;	/* For GDB and dlinfo() */
278     Objlist dldags;		/* Object belongs to these dlopened DAGs (%) */
279     Objlist dagmembers;		/* DAG has these members (%) */
280     dev_t dev;			/* Object's filesystem's device */
281     ino_t ino;			/* Object's inode number */
282     void *priv;			/* Platform-dependent */
283 } Obj_Entry;
284 
285 #define RTLD_MAGIC	0xd550b87a
286 #define RTLD_VERSION	1
287 
288 TAILQ_HEAD(obj_entry_q, Struct_Obj_Entry);
289 
290 #define RTLD_STATIC_TLS_EXTRA	128
291 
292 /* Flags to be passed into symlook_ family of functions. */
293 #define SYMLOOK_IN_PLT	0x01	/* Lookup for PLT symbol */
294 #define SYMLOOK_DLSYM	0x02	/* Return newest versioned symbol. Used by
295 				   dlsym. */
296 #define	SYMLOOK_EARLY	0x04	/* Symlook is done during initialization. */
297 #define	SYMLOOK_IFUNC	0x08	/* Allow IFUNC processing in
298 				   reloc_non_plt(). */
299 
300 /* Flags for load_object(). */
301 #define	RTLD_LO_NOLOAD	0x01	/* dlopen() specified RTLD_NOLOAD. */
302 #define	RTLD_LO_DLOPEN	0x02	/* Load_object() called from dlopen(). */
303 #define	RTLD_LO_TRACE	0x04	/* Only tracing. */
304 #define	RTLD_LO_NODELETE 0x08	/* Loaded object cannot be closed. */
305 #define	RTLD_LO_FILTEES 0x10	/* Loading filtee. */
306 #define	RTLD_LO_EARLY	0x20	/* Do not call ctors, postpone it to the
307 				   initialization during the image start. */
308 #define	RTLD_LO_IGNSTLS 0x40	/* Do not allocate static TLS */
309 #define	RTLD_LO_DEEPBIND 0x80	/* Force symbolic for this object */
310 
311 /*
312  * Symbol cache entry used during relocation to avoid multiple lookups
313  * of the same symbol.
314  */
315 typedef struct Struct_SymCache {
316     const Elf_Sym *sym;		/* Symbol table entry */
317     const Obj_Entry *obj;	/* Shared object which defines it */
318 } SymCache;
319 
320 /*
321  * This structure provides a reentrant way to keep a list of objects and
322  * check which ones have already been processed in some way.
323  */
324 typedef struct Struct_DoneList {
325     const Obj_Entry **objs;		/* Array of object pointers */
326     unsigned int num_alloc;		/* Allocated size of the array */
327     unsigned int num_used;		/* Number of array slots used */
328 } DoneList;
329 
330 struct Struct_RtldLockState {
331 	int lockstate;
332 	sigjmp_buf env;
333 };
334 
335 struct fill_search_info_args {
336 	int request;
337 	unsigned int flags;
338 	struct dl_serinfo *serinfo;
339 	struct dl_serpath *serpath;
340 	char *strspace;
341 };
342 
343 /*
344  * The pack of arguments and results for the symbol lookup functions.
345  */
346 typedef struct Struct_SymLook {
347     const char *name;
348     unsigned long hash;
349     uint32_t hash_gnu;
350     const Ver_Entry *ventry;
351     int flags;
352     const Obj_Entry *defobj_out;
353     const Elf_Sym *sym_out;
354     struct Struct_RtldLockState *lockstate;
355 } SymLook;
356 
357 void _rtld_error(const char *, ...) __printflike(1, 2) __exported;
358 void rtld_die(void) __dead2;
359 const char *rtld_strerror(int);
360 Obj_Entry *map_object(int, const char *, const struct stat *);
361 void *xcalloc(size_t, size_t);
362 void *xmalloc(size_t);
363 char *xstrdup(const char *);
364 void *xmalloc_aligned(size_t size, size_t align, size_t offset);
365 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
366 extern Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
367 extern bool ld_bind_not;
368 extern bool ld_fast_sigblock;
369 
370 void dump_relocations(Obj_Entry *);
371 void dump_obj_relocations(Obj_Entry *);
372 void dump_Elf_Rel(Obj_Entry *, const Elf_Rel *, u_long);
373 void dump_Elf_Rela(Obj_Entry *, const Elf_Rela *, u_long);
374 
375 /*
376  * Function declarations.
377  */
378 uintptr_t rtld_round_page(uintptr_t);
379 uintptr_t rtld_trunc_page(uintptr_t);
380 Elf32_Word elf_hash(const char *);
381 const Elf_Sym *find_symdef(unsigned long, const Obj_Entry *,
382   const Obj_Entry **, int, SymCache *, struct Struct_RtldLockState *);
383 void lockdflt_init(void);
384 void digest_notes(Obj_Entry *, Elf_Addr, Elf_Addr);
385 Obj_Entry *globallist_curr(const Obj_Entry *obj);
386 Obj_Entry *globallist_next(const Obj_Entry *obj);
387 void obj_free(Obj_Entry *);
388 Obj_Entry *obj_new(void);
389 Obj_Entry *obj_from_addr(const void *);
390 void _rtld_bind_start(void);
391 void *rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def);
392 void symlook_init(SymLook *, const char *);
393 int symlook_obj(SymLook *, const Obj_Entry *);
394 void *tls_get_addr_common(uintptr_t **dtvp, int index, size_t offset);
395 void *allocate_tls(Obj_Entry *, void *, size_t, size_t);
396 void free_tls(void *, size_t, size_t);
397 void *allocate_module_tls(int index);
398 bool allocate_tls_offset(Obj_Entry *obj);
399 void free_tls_offset(Obj_Entry *obj);
400 const Ver_Entry *fetch_ventry(const Obj_Entry *obj, unsigned long);
401 int convert_prot(int elfflags);
402 bool check_elf_headers(const Elf_Ehdr *hdr, const char *path);
403 
404 /*
405  * MD function declarations.
406  */
407 int do_copy_relocations(Obj_Entry *);
408 int reloc_non_plt(Obj_Entry *, Obj_Entry *, int flags,
409     struct Struct_RtldLockState *);
410 int reloc_plt(Obj_Entry *, int flags, struct Struct_RtldLockState *);
411 int reloc_jmpslots(Obj_Entry *, int flags, struct Struct_RtldLockState *);
412 int reloc_iresolve(Obj_Entry *, struct Struct_RtldLockState *);
413 int reloc_iresolve_nonplt(Obj_Entry *, struct Struct_RtldLockState *);
414 int reloc_gnu_ifunc(Obj_Entry *, int flags, struct Struct_RtldLockState *);
415 void ifunc_init(Elf_Auxinfo[__min_size(AT_COUNT)]);
416 void init_pltgot(Obj_Entry *);
417 void allocate_initial_tls(Obj_Entry *);
418 
419 #endif /* } */
420