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