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