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