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