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