xref: /freebsd/libexec/rtld-elf/map_object.c (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
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
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 *
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 
125 	case PT_INTERP:
126 	    phinterp = phdr;
127 	    break;
128 
129 	case PT_LOAD:
130 	    segs[++nsegs] = phdr;
131 	    if ((segs[nsegs]->p_align & (page_size - 1)) != 0) {
132 		_rtld_error("%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) - rtld_trunc_page(phdr->p_offset);
165 		note_map = mmap(NULL, note_map_len, PROT_READ,
166 		  MAP_PRIVATE, fd, rtld_trunc_page(phdr->p_offset));
167 		if (note_map == MAP_FAILED) {
168 		    _rtld_error("%s: error mapping PT_NOTE (%d)", path, errno);
169 		    goto error;
170 		}
171 		note_start = (Elf_Addr)(note_map + phdr->p_offset -
172 		  rtld_trunc_page(phdr->p_offset));
173 	    } else {
174 		note_start = (Elf_Addr)(char *)hdr + phdr->p_offset;
175 	    }
176 	    note_end = note_start + phdr->p_filesz;
177 	    break;
178 	}
179 
180 	++phdr;
181     }
182     if (phdyn == NULL) {
183 	_rtld_error("%s: object is not dynamically-linked", path);
184 	goto error;
185     }
186 
187     if (nsegs < 0) {
188 	_rtld_error("%s: too few PT_LOAD segments", path);
189 	goto error;
190     }
191 
192     /*
193      * Map the entire address space of the object, to stake out our
194      * contiguous region, and to establish the base address for relocation.
195      */
196     base_vaddr = rtld_trunc_page(segs[0]->p_vaddr);
197     base_vlimit = rtld_round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz);
198     mapsize = base_vlimit - base_vaddr;
199     base_addr = (caddr_t) base_vaddr;
200     base_flags = __getosreldate() >= P_OSREL_MAP_GUARD ? MAP_GUARD :
201 	MAP_PRIVATE | MAP_ANON | MAP_NOCORE;
202     if (npagesizes > 1 && rtld_round_page(segs[0]->p_filesz) >= pagesizes[1])
203 	base_flags |= MAP_ALIGNED_SUPER;
204     if (base_vaddr != 0)
205 	base_flags |= MAP_FIXED | MAP_EXCL;
206 
207     mapbase = mmap(base_addr, mapsize, PROT_NONE, base_flags, -1, 0);
208     if (mapbase == MAP_FAILED) {
209 	_rtld_error("%s: mmap of entire address space failed: %s",
210 	  path, rtld_strerror(errno));
211 	goto error;
212     }
213     if (base_addr != NULL && mapbase != base_addr) {
214 	_rtld_error("%s: mmap returned wrong address: wanted %p, got %p",
215 	  path, base_addr, mapbase);
216 	goto error1;
217     }
218 
219     for (i = 0; i <= nsegs; i++) {
220 	/* Overlay the segment onto the proper region. */
221 	data_offset = rtld_trunc_page(segs[i]->p_offset);
222 	data_vaddr = rtld_trunc_page(segs[i]->p_vaddr);
223 	data_vlimit = rtld_round_page(segs[i]->p_vaddr + segs[i]->p_filesz);
224 	data_addr = mapbase + (data_vaddr - base_vaddr);
225 	data_prot = convert_prot(segs[i]->p_flags);
226 	data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED;
227 	if (data_vlimit != data_vaddr &&
228 	    mmap(data_addr, data_vlimit - data_vaddr, data_prot,
229 	    data_flags | MAP_PREFAULT_READ, fd, data_offset) == MAP_FAILED) {
230 		_rtld_error("%s: mmap of data failed: %s", path,
231 		    rtld_strerror(errno));
232 		goto error1;
233 	}
234 
235 	/* Do BSS setup */
236 	if (segs[i]->p_filesz != segs[i]->p_memsz) {
237 
238 	    /* Clear any BSS in the last page of the segment. */
239 	    clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
240 	    clear_addr = mapbase + (clear_vaddr - base_vaddr);
241 	    clear_page = mapbase + (rtld_trunc_page(clear_vaddr) - base_vaddr);
242 
243 	    if ((nclear = data_vlimit - clear_vaddr) > 0) {
244 		/* Make sure the end of the segment is writable */
245 		if ((data_prot & PROT_WRITE) == 0 && -1 ==
246 		     mprotect(clear_page, page_size, data_prot|PROT_WRITE)) {
247 			_rtld_error("%s: mprotect failed: %s", path,
248 			    rtld_strerror(errno));
249 			goto error1;
250 		}
251 
252 		memset(clear_addr, 0, nclear);
253 
254 		/* Reset the data protection back */
255 		if ((data_prot & PROT_WRITE) == 0)
256 		    mprotect(clear_page, page_size, data_prot);
257 	    }
258 
259 	    /* Overlay the BSS segment onto the proper region. */
260 	    bss_vaddr = data_vlimit;
261 	    bss_vlimit = rtld_round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
262 	    bss_addr = mapbase +  (bss_vaddr - base_vaddr);
263 	    if (bss_vlimit > bss_vaddr) {	/* There is something to do */
264 		if (mmap(bss_addr, bss_vlimit - bss_vaddr, data_prot,
265 		    data_flags | MAP_ANON, -1, 0) == MAP_FAILED) {
266 		    _rtld_error("%s: mmap of bss failed: %s", path,
267 			rtld_strerror(errno));
268 		    goto error1;
269 		}
270 	    }
271 	}
272 
273 	if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
274 	  (data_vlimit - data_vaddr + data_offset) >=
275 	  (hdr->e_phoff + hdr->e_phnum * sizeof (Elf_Phdr))) {
276 	    phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
277 	}
278     }
279 
280     obj = obj_new();
281     if (sb != NULL) {
282 	obj->dev = sb->st_dev;
283 	obj->ino = sb->st_ino;
284     }
285     obj->mapbase = mapbase;
286     obj->mapsize = mapsize;
287     obj->vaddrbase = base_vaddr;
288     obj->relocbase = mapbase - base_vaddr;
289     obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
290     if (hdr->e_entry != 0)
291 	obj->entry = (caddr_t)(obj->relocbase + hdr->e_entry);
292     if (phdr_vaddr != 0) {
293 	obj->phdr = (const Elf_Phdr *)(obj->relocbase + phdr_vaddr);
294     } else {
295 	obj->phdr = malloc(phsize);
296 	if (obj->phdr == NULL) {
297 	    obj_free(obj);
298 	    _rtld_error("%s: cannot allocate program header", path);
299 	    goto error1;
300 	}
301 	memcpy(__DECONST(char *, obj->phdr), (char *)hdr + hdr->e_phoff, phsize);
302 	obj->phdr_alloc = true;
303     }
304     obj->phsize = phsize;
305     if (phinterp != NULL)
306 	obj->interp = (const char *)(obj->relocbase + phinterp->p_vaddr);
307     if (phtls != NULL) {
308 	tls_dtv_generation++;
309 	obj->tlsindex = ++tls_max_index;
310 	obj->tlssize = phtls->p_memsz;
311 	obj->tlsalign = phtls->p_align;
312 	obj->tlspoffset = phtls->p_offset;
313 	obj->tlsinitsize = phtls->p_filesz;
314 	obj->tlsinit = mapbase + phtls->p_vaddr;
315     }
316     obj->stack_flags = stack_flags;
317     if (note_start < note_end)
318 	digest_notes(obj, note_start, note_end);
319     if (note_map != NULL)
320 	munmap(note_map, note_map_len);
321     munmap(hdr, page_size);
322     return (obj);
323 
324 error1:
325     munmap(mapbase, mapsize);
326 error:
327     if (note_map != NULL && note_map != MAP_FAILED)
328 	munmap(note_map, note_map_len);
329     if (!phdr_in_zero_page(hdr))
330 	munmap(phdr, hdr->e_phnum * sizeof(phdr[0]));
331     munmap(hdr, page_size);
332     return (NULL);
333 }
334 
335 bool
336 check_elf_headers(const Elf_Ehdr *hdr, const char *path)
337 {
338 	if (!IS_ELF(*hdr)) {
339 		_rtld_error("%s: invalid file format", path);
340 		return (false);
341 	}
342 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
343 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
344 		_rtld_error("%s: unsupported file layout", path);
345 		return (false);
346 	}
347 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
348 	    hdr->e_version != EV_CURRENT) {
349 		_rtld_error("%s: unsupported file version", path);
350 		return (false);
351 	}
352 	if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
353 		_rtld_error("%s: unsupported file type", path);
354 		return (false);
355 	}
356 	if (hdr->e_machine != ELF_TARG_MACH) {
357 		_rtld_error("%s: unsupported machine", path);
358 		return (false);
359 	}
360 	if (hdr->e_phentsize != sizeof(Elf_Phdr)) {
361 		_rtld_error(
362 	    "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)", path);
363 		return (false);
364 	}
365 	return (true);
366 }
367 
368 static Elf_Ehdr *
369 get_elf_header(int fd, const char *path, const struct stat *sbp,
370     Elf_Phdr **phdr_p)
371 {
372 	Elf_Ehdr *hdr;
373 	Elf_Phdr *phdr;
374 
375 	/* Make sure file has enough data for the ELF header */
376 	if (sbp != NULL && sbp->st_size < (off_t)sizeof(Elf_Ehdr)) {
377 		_rtld_error("%s: invalid file format", path);
378 		return (NULL);
379 	}
380 
381 	hdr = mmap(NULL, page_size, PROT_READ, MAP_PRIVATE | MAP_PREFAULT_READ,
382 	    fd, 0);
383 	if (hdr == MAP_FAILED) {
384 		_rtld_error("%s: read error: %s", path, rtld_strerror(errno));
385 		return (NULL);
386 	}
387 
388 	/* Make sure the file is valid */
389 	if (!check_elf_headers(hdr, path))
390 		goto error;
391 
392 	/*
393 	 * We rely on the program header being in the first page.  This is
394 	 * not strictly required by the ABI specification, but it seems to
395 	 * always true in practice.  And, it simplifies things considerably.
396 	 */
397 	if (phdr_in_zero_page(hdr)) {
398 		phdr = (Elf_Phdr *)((char *)hdr + hdr->e_phoff);
399 	} else {
400 		phdr = mmap(NULL, hdr->e_phnum * sizeof(phdr[0]),
401 		    PROT_READ, MAP_PRIVATE | MAP_PREFAULT_READ, fd,
402 		    hdr->e_phoff);
403 		if (phdr == MAP_FAILED) {
404 			_rtld_error("%s: error mapping phdr: %s", path,
405 			    rtld_strerror(errno));
406 			goto error;
407 		}
408 	}
409 	*phdr_p = phdr;
410 	return (hdr);
411 
412 error:
413 	munmap(hdr, page_size);
414 	return (NULL);
415 }
416 
417 void
418 obj_free(Obj_Entry *obj)
419 {
420     Objlist_Entry *elm;
421 
422     if (obj->tls_static)
423 	free_tls_offset(obj);
424     while (obj->needed != NULL) {
425 	Needed_Entry *needed = obj->needed;
426 	obj->needed = needed->next;
427 	free(needed);
428     }
429     while (!STAILQ_EMPTY(&obj->names)) {
430 	Name_Entry *entry = STAILQ_FIRST(&obj->names);
431 	STAILQ_REMOVE_HEAD(&obj->names, link);
432 	free(entry);
433     }
434     while (!STAILQ_EMPTY(&obj->dldags)) {
435 	elm = STAILQ_FIRST(&obj->dldags);
436 	STAILQ_REMOVE_HEAD(&obj->dldags, link);
437 	free(elm);
438     }
439     while (!STAILQ_EMPTY(&obj->dagmembers)) {
440 	elm = STAILQ_FIRST(&obj->dagmembers);
441 	STAILQ_REMOVE_HEAD(&obj->dagmembers, link);
442 	free(elm);
443     }
444     if (obj->vertab)
445 	free(obj->vertab);
446     if (obj->origin_path)
447 	free(obj->origin_path);
448     if (obj->z_origin)
449 	free(__DECONST(void*, obj->rpath));
450     if (obj->priv)
451 	free(obj->priv);
452     if (obj->path)
453 	free(obj->path);
454     if (obj->phdr_alloc)
455 	free(__DECONST(void *, obj->phdr));
456     free(obj);
457 }
458 
459 Obj_Entry *
460 obj_new(void)
461 {
462     Obj_Entry *obj;
463 
464     obj = CNEW(Obj_Entry);
465     STAILQ_INIT(&obj->dldags);
466     STAILQ_INIT(&obj->dagmembers);
467     STAILQ_INIT(&obj->names);
468     return obj;
469 }
470 
471 /*
472  * Given a set of ELF protection flags, return the corresponding protection
473  * flags for MMAP.
474  */
475 int
476 convert_prot(int elfflags)
477 {
478     int prot = 0;
479     if (elfflags & PF_R)
480 	prot |= PROT_READ;
481     if (elfflags & PF_W)
482 	prot |= PROT_WRITE;
483     if (elfflags & PF_X)
484 	prot |= PROT_EXEC;
485     return prot;
486 }
487 
488 static int
489 convert_flags(int elfflags)
490 {
491     int flags = MAP_PRIVATE; /* All mappings are private */
492 
493     /*
494      * Readonly mappings are marked "MAP_NOCORE", because they can be
495      * reconstructed by a debugger.
496      */
497     if (!(elfflags & PF_W))
498 	flags |= MAP_NOCORE;
499     return flags;
500 }
501