xref: /freebsd/libexec/rtld-elf/map_object.c (revision ea44c37d0bd15e796c85f84b57c211ac220c550c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright 1996-1998 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 #include <sys/param.h>
29 #include <sys/mman.h>
30 #include <sys/stat.h>
31 
32 #include <errno.h>
33 #include <stddef.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 
38 #include "debug.h"
39 #include "rtld.h"
40 
41 static Elf_Ehdr *get_elf_header(int, const char *, const struct stat *,
42     Elf_Phdr **phdr);
43 static int convert_flags(int); /* Elf flags -> mmap flags */
44 
45 static bool
46 phdr_in_zero_page(const Elf_Ehdr *hdr)
47 {
48 	return (hdr->e_phoff + hdr->e_phnum * sizeof(Elf_Phdr) <= page_size);
49 }
50 
51 /*
52  * Map a shared object into memory.  The "fd" argument is a file descriptor,
53  * which must be open on the object and positioned at its beginning.
54  * The "path" argument is a pathname that is used only for error messages.
55  *
56  * The return value is a pointer to a newly-allocated Obj_Entry structure
57  * for the shared object.  Returns NULL on failure.
58  */
59 Obj_Entry *
60 map_object(int fd, const char *path, const struct stat *sb, bool ismain)
61 {
62 	Obj_Entry *obj;
63 	Elf_Ehdr *hdr;
64 	int i;
65 	Elf_Phdr *phdr;
66 	Elf_Phdr *phlimit;
67 	Elf_Phdr **segs;
68 	int nsegs;
69 	Elf_Phdr *phdyn;
70 	Elf_Phdr *phinterp;
71 	Elf_Phdr *phtls;
72 	caddr_t mapbase;
73 	size_t mapsize;
74 	Elf_Addr base_vaddr;
75 	Elf_Addr base_vlimit;
76 	caddr_t base_addr;
77 	int base_flags;
78 	Elf_Off data_offset;
79 	Elf_Addr data_vaddr;
80 	Elf_Addr data_vlimit;
81 	caddr_t data_addr;
82 	int data_prot;
83 	int data_flags;
84 	Elf_Addr clear_vaddr;
85 	caddr_t clear_addr;
86 	caddr_t clear_page;
87 	Elf_Addr phdr_vaddr;
88 	size_t nclear, phsize;
89 	Elf_Addr bss_vaddr;
90 	Elf_Addr bss_vlimit;
91 	caddr_t bss_addr;
92 	Elf_Word stack_flags;
93 	Elf_Addr note_start;
94 	Elf_Addr note_end;
95 	char *note_map;
96 	size_t note_map_len;
97 
98 	hdr = get_elf_header(fd, path, sb, &phdr);
99 	if (hdr == NULL)
100 		return (NULL);
101 
102 	/*
103 	 * Scan the program header entries, and save key information.
104 	 * We expect that the loadable segments are ordered by load address.
105 	 */
106 	phsize = hdr->e_phnum * sizeof(phdr[0]);
107 	phlimit = phdr + hdr->e_phnum;
108 	nsegs = -1;
109 	phdyn = phinterp = phtls = NULL;
110 	phdr_vaddr = 0;
111 	note_start = 0;
112 	note_end = 0;
113 	note_map = NULL;
114 	note_map_len = 0;
115 	segs = xcalloc(hdr->e_phnum, sizeof(segs[0]));
116 	stack_flags = PF_X | PF_R | PF_W;
117 	while (phdr < phlimit) {
118 		switch (phdr->p_type) {
119 		case PT_INTERP:
120 			phinterp = phdr;
121 			break;
122 
123 		case PT_LOAD:
124 			segs[++nsegs] = phdr;
125 			if ((segs[nsegs]->p_align & (page_size - 1)) != 0) {
126 				_rtld_error(
127 				    "%s: PT_LOAD segment %d not page-aligned",
128 				    path, nsegs);
129 				goto error;
130 			}
131 			break;
132 
133 		case PT_PHDR:
134 			phdr_vaddr = phdr->p_vaddr;
135 			phsize = phdr->p_memsz;
136 			break;
137 
138 		case PT_DYNAMIC:
139 			phdyn = phdr;
140 			break;
141 
142 		case PT_TLS:
143 			phtls = phdr;
144 			break;
145 
146 		case PT_GNU_STACK:
147 			stack_flags = phdr->p_flags;
148 			break;
149 
150 		case PT_NOTE:
151 			if (phdr->p_offset > page_size ||
152 			    phdr->p_offset + phdr->p_filesz > page_size) {
153 				note_map_len = rtld_round_page(phdr->p_offset +
154 				    phdr->p_filesz) -
155 				    rtld_trunc_page(phdr->p_offset);
156 				note_map = mmap(NULL, note_map_len, PROT_READ,
157 				    MAP_PRIVATE, fd,
158 				    rtld_trunc_page(phdr->p_offset));
159 				if (note_map == MAP_FAILED) {
160 					_rtld_error(
161 					    "%s: error mapping PT_NOTE (%d)",
162 					    path, errno);
163 					goto error;
164 				}
165 				note_start = (Elf_Addr)(note_map +
166 				    phdr->p_offset -
167 				    rtld_trunc_page(phdr->p_offset));
168 			} else {
169 				note_start = (Elf_Addr)(char *)hdr +
170 				    phdr->p_offset;
171 			}
172 			note_end = note_start + phdr->p_filesz;
173 			break;
174 		}
175 
176 		++phdr;
177 	}
178 	if (phdyn == NULL) {
179 		_rtld_error("%s: object is not dynamically-linked", path);
180 		goto error;
181 	}
182 
183 	if (nsegs < 0) {
184 		_rtld_error("%s: too few PT_LOAD segments", path);
185 		goto error;
186 	}
187 
188 	/*
189 	 * Map the entire address space of the object, to stake out our
190 	 * contiguous region, and to establish the base address for relocation.
191 	 */
192 	base_vaddr = rtld_trunc_page(segs[0]->p_vaddr);
193 	base_vlimit = rtld_round_page(segs[nsegs]->p_vaddr +
194 	    segs[nsegs]->p_memsz);
195 	mapsize = base_vlimit - base_vaddr;
196 	base_addr = (caddr_t)base_vaddr;
197 	base_flags = MAP_GUARD;
198 	if (npagesizes > 1 &&  rtld_round_page(segs[0]->p_filesz) >=
199 	    pagesizes[1])
200 		base_flags |= MAP_ALIGNED_SUPER;
201 	if (base_vaddr != 0)
202 		base_flags |= MAP_FIXED | MAP_EXCL;
203 
204 	mapbase = mmap(base_addr, mapsize, PROT_NONE, base_flags, -1, 0);
205 	if (mapbase == MAP_FAILED) {
206 		_rtld_error("%s: mmap of entire address space failed: %s",
207 		    path, rtld_strerror(errno));
208 		goto error;
209 	}
210 	if (base_addr != NULL && mapbase != base_addr) {
211 		_rtld_error(
212 		    "%s: mmap returned wrong address: wanted %p, got %p",
213 		    path, base_addr, mapbase);
214 		goto error1;
215 	}
216 
217 	for (i = 0; i <= nsegs; i++) {
218 		/* Overlay the segment onto the proper region. */
219 		data_offset = rtld_trunc_page(segs[i]->p_offset);
220 		data_vaddr = rtld_trunc_page(segs[i]->p_vaddr);
221 		data_vlimit = rtld_round_page(segs[i]->p_vaddr +
222 		    segs[i]->p_filesz);
223 		data_addr = mapbase + (data_vaddr - base_vaddr);
224 		data_prot = convert_prot(segs[i]->p_flags);
225 		data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED;
226 		if (data_vlimit != data_vaddr && mmap(data_addr,
227 		    data_vlimit - data_vaddr, data_prot, data_flags |
228 		    MAP_PREFAULT_READ, fd, data_offset) == MAP_FAILED) {
229 			_rtld_error("%s: mmap of data failed: %s",
230 			    path, rtld_strerror(errno));
231 			goto error1;
232 		}
233 
234 		/* Do BSS setup */
235 		if (segs[i]->p_filesz != segs[i]->p_memsz) {
236 			/* Clear any BSS in the last page of the segment. */
237 			clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
238 			clear_addr = mapbase + (clear_vaddr - base_vaddr);
239 			clear_page = mapbase + (rtld_trunc_page(clear_vaddr) -
240 			    base_vaddr);
241 
242 			if ((nclear = data_vlimit - clear_vaddr) > 0) {
243 				/*
244 				 * Make sure the end of the segment is
245 				 * writable.
246 				 */
247 				if ((data_prot & PROT_WRITE) == 0 &&
248 				    mprotect(clear_page, page_size,
249 				    data_prot | PROT_WRITE) == -1) {
250 					_rtld_error("%s: mprotect failed: %s",
251 					    path, rtld_strerror(errno));
252 					goto error1;
253 				}
254 
255 				memset(clear_addr, 0, nclear);
256 
257 				/* Reset the data protection back */
258 				if ((data_prot & PROT_WRITE) == 0)
259 					mprotect(clear_page, page_size,
260 					    data_prot);
261 			}
262 
263 			/* Overlay the BSS segment onto the proper region. */
264 			bss_vaddr = data_vlimit;
265 			bss_vlimit = rtld_round_page(segs[i]->p_vaddr +
266 			    segs[i]->p_memsz);
267 			bss_addr = mapbase + (bss_vaddr - base_vaddr);
268 			if (bss_vlimit > bss_vaddr) {
269 				/* There is something to do */
270 				if (mmap(bss_addr, bss_vlimit - bss_vaddr,
271 				    data_prot, data_flags | MAP_ANON, -1,
272 				    0) == MAP_FAILED) {
273 					_rtld_error(
274 					    "%s: mmap of bss failed: %s",
275 					    path, rtld_strerror(errno));
276 					goto error1;
277 				}
278 			}
279 		}
280 
281 		if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
282 		    data_vlimit - data_vaddr + data_offset >=
283 		    hdr->e_phoff + hdr->e_phnum * sizeof(Elf_Phdr)) {
284 			phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
285 		}
286 	}
287 
288 	obj = obj_new();
289 	if (sb != NULL) {
290 		obj->dev = sb->st_dev;
291 		obj->ino = sb->st_ino;
292 	}
293 	obj->mapbase = mapbase;
294 	obj->mapsize = mapsize;
295 	obj->vaddrbase = base_vaddr;
296 	obj->relocbase = mapbase - base_vaddr;
297 	obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
298 	if (hdr->e_entry != 0)
299 		obj->entry = (caddr_t)(obj->relocbase + hdr->e_entry);
300 	if (phdr_vaddr != 0) {
301 		obj->phdr = (const Elf_Phdr *)(obj->relocbase + phdr_vaddr);
302 	} else {
303 		obj->phdr = malloc(phsize);
304 		if (obj->phdr == NULL) {
305 			obj_free(obj);
306 			_rtld_error("%s: cannot allocate program header",
307 			    path);
308 			goto error1;
309 		}
310 		memcpy(__DECONST(char *, obj->phdr), (char *)hdr + hdr->e_phoff,
311 		    phsize);
312 		obj->phdr_alloc = true;
313 	}
314 	obj->phnum = phsize / sizeof(*phdr);
315 	if (phinterp != NULL)
316 		obj->interp = (const char *)(obj->relocbase +
317 		    phinterp->p_vaddr);
318 	if (phtls != NULL) {
319 		if (ismain)
320 			obj->tlsindex = 1;
321 		else {
322 			tls_dtv_generation++;
323 			obj->tlsindex = ++tls_max_index;
324 		}
325 		obj->tlssize = phtls->p_memsz;
326 		obj->tlsalign = phtls->p_align;
327 		obj->tlspoffset = phtls->p_offset;
328 		obj->tlsinitsize = phtls->p_filesz;
329 		obj->tlsinit = obj->relocbase + phtls->p_vaddr;
330 	}
331 	obj->stack_flags = stack_flags;
332 	if (note_start < note_end)
333 		digest_notes(obj, note_start, note_end);
334 finish:
335 	if (note_map != NULL && note_map != MAP_FAILED)
336 		munmap(note_map, note_map_len);
337 	munmap(hdr, page_size);
338 	free(segs);
339 	return (obj);
340 
341 error1:
342 	munmap(mapbase, mapsize);
343 error:
344 	if (!phdr_in_zero_page(hdr))
345 		munmap(phdr, hdr->e_phnum * sizeof(phdr[0]));
346 	obj = NULL;
347 	goto finish;
348 }
349 
350 bool
351 check_elf_headers(const Elf_Ehdr *hdr, const char *path)
352 {
353 	if (!IS_ELF(*hdr)) {
354 		_rtld_error("%s: invalid file format", path);
355 		return (false);
356 	}
357 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
358 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
359 		_rtld_error("%s: unsupported file layout", path);
360 		return (false);
361 	}
362 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
363 	    hdr->e_version != EV_CURRENT) {
364 		_rtld_error("%s: unsupported file version", path);
365 		return (false);
366 	}
367 	if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
368 		_rtld_error("%s: unsupported file type", path);
369 		return (false);
370 	}
371 	if (hdr->e_machine != ELF_TARG_MACH) {
372 		_rtld_error("%s: unsupported machine", path);
373 		return (false);
374 	}
375 	if (hdr->e_phentsize != sizeof(Elf_Phdr)) {
376 		_rtld_error(
377 	    "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)",
378 		    path);
379 		return (false);
380 	}
381 	return (true);
382 }
383 
384 static Elf_Ehdr *
385 get_elf_header(int fd, const char *path, const struct stat *sbp,
386     Elf_Phdr **phdr_p)
387 {
388 	Elf_Ehdr *hdr;
389 	Elf_Phdr *phdr;
390 
391 	/* Make sure file has enough data for the ELF header */
392 	if (sbp != NULL && sbp->st_size < (off_t)sizeof(Elf_Ehdr)) {
393 		_rtld_error("%s: invalid file format", path);
394 		return (NULL);
395 	}
396 
397 	hdr = mmap(NULL, page_size, PROT_READ, MAP_PRIVATE | MAP_PREFAULT_READ,
398 	    fd, 0);
399 	if (hdr == MAP_FAILED) {
400 		_rtld_error("%s: read error: %s", path, rtld_strerror(errno));
401 		return (NULL);
402 	}
403 
404 	/* Make sure the file is valid */
405 	if (!check_elf_headers(hdr, path))
406 		goto error;
407 
408 	/*
409 	 * We rely on the program header being in the first page.  This is
410 	 * not strictly required by the ABI specification, but it seems to
411 	 * always true in practice.  And, it simplifies things considerably.
412 	 */
413 	if (phdr_in_zero_page(hdr)) {
414 		phdr = (Elf_Phdr *)((char *)hdr + hdr->e_phoff);
415 	} else {
416 		phdr = mmap(NULL, hdr->e_phnum * sizeof(phdr[0]), PROT_READ,
417 		    MAP_PRIVATE | MAP_PREFAULT_READ, fd, hdr->e_phoff);
418 		if (phdr == MAP_FAILED) {
419 			_rtld_error("%s: error mapping phdr: %s", path,
420 			    rtld_strerror(errno));
421 			goto error;
422 		}
423 	}
424 	*phdr_p = phdr;
425 	return (hdr);
426 
427 error:
428 	munmap(hdr, page_size);
429 	return (NULL);
430 }
431 
432 void
433 obj_free(Obj_Entry *obj)
434 {
435 	Objlist_Entry *elm;
436 
437 	if (obj->tls_static)
438 		free_tls_offset(obj);
439 	while (obj->needed != NULL) {
440 		Needed_Entry *needed = obj->needed;
441 
442 		obj->needed = needed->next;
443 		free(needed);
444 	}
445 	while (!STAILQ_EMPTY(&obj->names)) {
446 		Name_Entry *entry = STAILQ_FIRST(&obj->names);
447 
448 		STAILQ_REMOVE_HEAD(&obj->names, link);
449 		free(entry);
450 	}
451 	while (!STAILQ_EMPTY(&obj->dldags)) {
452 		elm = STAILQ_FIRST(&obj->dldags);
453 		STAILQ_REMOVE_HEAD(&obj->dldags, link);
454 		free(elm);
455 	}
456 	while (!STAILQ_EMPTY(&obj->dagmembers)) {
457 		elm = STAILQ_FIRST(&obj->dagmembers);
458 		STAILQ_REMOVE_HEAD(&obj->dagmembers, link);
459 		free(elm);
460 	}
461 	if (obj->vertab)
462 		free(obj->vertab);
463 	if (obj->origin_path)
464 		free(obj->origin_path);
465 	if (obj->z_origin)
466 		free(__DECONST(void *, obj->rpath));
467 	if (obj->priv)
468 		free(obj->priv);
469 	if (obj->path)
470 		free(obj->path);
471 	if (obj->phdr_alloc)
472 		free(__DECONST(void *, obj->phdr));
473 	free(obj);
474 }
475 
476 Obj_Entry *
477 obj_new(void)
478 {
479 	Obj_Entry *obj;
480 
481 	obj = CNEW(Obj_Entry);
482 	STAILQ_INIT(&obj->dldags);
483 	STAILQ_INIT(&obj->dagmembers);
484 	STAILQ_INIT(&obj->names);
485 	return (obj);
486 }
487 
488 /*
489  * Given a set of ELF protection flags, return the corresponding protection
490  * flags for MMAP.
491  */
492 int
493 convert_prot(int elfflags)
494 {
495 	int prot = 0;
496 
497 	if ((elfflags & PF_R) != 0)
498 		prot |= PROT_READ;
499 	if ((elfflags & PF_W) != 0)
500 		prot |= PROT_WRITE;
501 	if ((elfflags & PF_X) != 0)
502 		prot |= PROT_EXEC;
503 	return (prot);
504 }
505 
506 static int
507 convert_flags(int elfflags)
508 {
509 	int flags = MAP_PRIVATE; /* All mappings are private */
510 
511 	/*
512 	 * Readonly mappings are marked "MAP_NOCORE", because they can be
513 	 * reconstructed by a debugger.
514 	 */
515 	if ((elfflags & PF_W) == 0)
516 		flags |= MAP_NOCORE;
517 	return (flags);
518 }
519