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