xref: /dragonfly/libexec/rtld-elf/map_object.c (revision 6e278935)
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: src/libexec/rtld-elf/map_object.c,v 1.25 2011/01/25 21:12:31 kib Exp $
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_Off base_offset;
69     Elf_Addr base_vaddr;
70     Elf_Addr base_vlimit;
71     caddr_t base_addr;
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 
87     hdr = get_elf_header(fd, path);
88     if (hdr == NULL)
89 	return (NULL);
90 
91     /*
92      * Scan the program header entries, and save key information.
93      *
94      * We expect that the loadable segments are ordered by load address.
95      */
96     phdr = (Elf_Phdr *) ((char *)hdr + hdr->e_phoff);
97     phsize  = hdr->e_phnum * sizeof (phdr[0]);
98     phlimit = phdr + hdr->e_phnum;
99     nsegs = -1;
100     phdyn = phinterp = phtls = NULL;
101     phdr_vaddr = 0;
102     segs = alloca(sizeof(segs[0]) * hdr->e_phnum);
103     while (phdr < phlimit) {
104 	switch (phdr->p_type) {
105 
106 	case PT_INTERP:
107 	    phinterp = phdr;
108 	    break;
109 
110 	case PT_LOAD:
111 	    segs[++nsegs] = phdr;
112 	    if ((segs[nsegs]->p_align & (PAGE_SIZE - 1)) != 0) {
113 		_rtld_error("%s: PT_LOAD segment %d not page-aligned",
114 		    path, nsegs);
115 		return NULL;
116 	    }
117 	    break;
118 
119 	case PT_PHDR:
120 	    phdr_vaddr = phdr->p_vaddr;
121 	    phsize = phdr->p_memsz;
122 	    break;
123 
124 	case PT_DYNAMIC:
125 	    phdyn = phdr;
126 	    break;
127 
128 	case PT_TLS:
129 	    phtls = phdr;
130 	    break;
131 	}
132 
133 	++phdr;
134     }
135     if (phdyn == NULL) {
136 	_rtld_error("%s: object is not dynamically-linked", path);
137 	return NULL;
138     }
139 
140     if (nsegs < 0) {
141 	_rtld_error("%s: too few PT_LOAD segments", path);
142 	return NULL;
143     }
144 
145     /*
146      * Map the entire address space of the object, to stake out our
147      * contiguous region, and to establish the base address for relocation.
148      */
149     base_offset = trunc_page(segs[0]->p_offset);
150     base_vaddr = trunc_page(segs[0]->p_vaddr);
151     base_vlimit = round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz);
152     mapsize = base_vlimit - base_vaddr;
153     base_addr = hdr->e_type == ET_EXEC ? (caddr_t) base_vaddr : NULL;
154 
155     mapbase = mmap(base_addr, mapsize, PROT_NONE, MAP_ANON | MAP_PRIVATE |
156       MAP_NOCORE, -1, 0);
157     if (mapbase == (caddr_t) -1) {
158 	_rtld_error("%s: mmap of entire address space failed: %s",
159 	  path, strerror(errno));
160 	return NULL;
161     }
162     if (base_addr != NULL && mapbase != base_addr) {
163 	_rtld_error("%s: mmap returned wrong address: wanted %p, got %p",
164 	  path, base_addr, mapbase);
165 	munmap(mapbase, mapsize);
166 	return NULL;
167     }
168 
169     for (i = 0; i <= nsegs; i++) {
170 	/* Overlay the segment onto the proper region. */
171 	data_offset = trunc_page(segs[i]->p_offset);
172 	data_vaddr = trunc_page(segs[i]->p_vaddr);
173 	data_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_filesz);
174 	data_addr = mapbase + (data_vaddr - base_vaddr);
175 	data_prot = convert_prot(segs[i]->p_flags);
176 	data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED;
177 	if (mmap(data_addr, data_vlimit - data_vaddr, data_prot,
178 	  data_flags, fd, data_offset) == (caddr_t) -1) {
179 	    _rtld_error("%s: mmap of data failed: %s", path, strerror(errno));
180 	    return NULL;
181 	}
182 
183 	/* Do BSS setup */
184 	if (segs[i]->p_filesz != segs[i]->p_memsz) {
185 
186 	    /* Clear any BSS in the last page of the segment. */
187 	    clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
188 	    clear_addr = mapbase + (clear_vaddr - base_vaddr);
189 	    clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr);
190 
191 	    if ((nclear = data_vlimit - clear_vaddr) > 0) {
192 		/* Make sure the end of the segment is writable */
193 		if ((data_prot & PROT_WRITE) == 0) {
194 		    if (mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE) < 0) {
195 			_rtld_error("%s: mprotect failed: %s", path,
196 			    strerror(errno));
197 			return NULL;
198 		    }
199 		}
200 
201 		memset(clear_addr, 0, nclear);
202 
203 		/*
204 		 * reset the data protection back, enable the segment to be
205 		 * coredumped since we modified it.
206 		 */
207 		if ((data_prot & PROT_WRITE) == 0) {
208 		    madvise(clear_page, PAGE_SIZE, MADV_CORE);
209 		    mprotect(clear_page, PAGE_SIZE, data_prot);
210 		}
211 	    }
212 
213 	    /* Overlay the BSS segment onto the proper region. */
214 	    bss_vaddr = data_vlimit;
215 	    bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
216 	    bss_addr = mapbase +  (bss_vaddr - base_vaddr);
217 	    if (bss_vlimit > bss_vaddr) {	/* There is something to do */
218 		if (mprotect(bss_addr, bss_vlimit - bss_vaddr, data_prot) == -1) {
219 		    _rtld_error("%s: mprotect of bss failed: %s", path,
220 			strerror(errno));
221 		    return NULL;
222 		}
223 	    }
224 	}
225 
226 	if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
227 	  (data_vlimit - data_vaddr + data_offset) >=
228 	  (hdr->e_phoff + hdr->e_phnum * sizeof (Elf_Phdr))) {
229 	    phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
230 	}
231     }
232 
233     obj = obj_new();
234     if (sb != NULL) {
235 	obj->dev = sb->st_dev;
236 	obj->ino = sb->st_ino;
237     }
238     obj->mapbase = mapbase;
239     obj->mapsize = mapsize;
240     obj->textsize = round_page(segs[0]->p_vaddr + segs[0]->p_memsz) -
241       base_vaddr;
242     obj->vaddrbase = base_vaddr;
243     obj->relocbase = mapbase - base_vaddr;
244     obj->dynamic = (const Elf_Dyn *) (obj->relocbase + phdyn->p_vaddr);
245     if (hdr->e_entry != 0)
246 	obj->entry = (caddr_t) (obj->relocbase + hdr->e_entry);
247     if (phdr_vaddr != 0) {
248 	obj->phdr = (const Elf_Phdr *) (obj->relocbase + phdr_vaddr);
249     } else {
250 	obj->phdr = malloc(phsize);
251 	if (obj->phdr == NULL) {
252 	    obj_free(obj);
253 	    _rtld_error("%s: cannot allocate program header", path);
254 	     return NULL;
255 	}
256 	memcpy((char *)obj->phdr, (char *)hdr + hdr->e_phoff, phsize);
257 	obj->phdr_alloc = true;
258     }
259     obj->phsize = phsize;
260     if (phinterp != NULL)
261 	obj->interp = (const char *) (obj->relocbase + phinterp->p_vaddr);
262     if (phtls != NULL) {
263 	tls_dtv_generation++;
264 	obj->tlsindex = ++tls_max_index;
265 	obj->tlssize = phtls->p_memsz;
266 	obj->tlsalign = phtls->p_align;
267 	obj->tlsinitsize = phtls->p_filesz;
268 	obj->tlsinit = mapbase + phtls->p_vaddr;
269     }
270     return obj;
271 }
272 
273 static Elf_Ehdr *
274 get_elf_header (int fd, const char *path)
275 {
276     static union {
277 	Elf_Ehdr hdr;
278 	char buf[PAGE_SIZE];
279     } u;
280     ssize_t nbytes;
281 
282     if ((nbytes = pread(fd, u.buf, PAGE_SIZE, 0)) == -1) {
283 	_rtld_error("%s: read error: %s", path, strerror(errno));
284 	return NULL;
285     }
286 
287     /* Make sure the file is valid */
288     if (nbytes < (ssize_t)sizeof(Elf_Ehdr) || !IS_ELF(u.hdr)) {
289 	_rtld_error("%s: invalid file format", path);
290 	return NULL;
291     }
292     if (u.hdr.e_ident[EI_CLASS] != ELF_TARG_CLASS
293       || u.hdr.e_ident[EI_DATA] != ELF_TARG_DATA) {
294 	_rtld_error("%s: unsupported file layout", path);
295 	return NULL;
296     }
297     if (u.hdr.e_ident[EI_VERSION] != EV_CURRENT
298       || u.hdr.e_version != EV_CURRENT) {
299 	_rtld_error("%s: unsupported file version", path);
300 	return NULL;
301     }
302     if (u.hdr.e_type != ET_EXEC && u.hdr.e_type != ET_DYN) {
303 	_rtld_error("%s: unsupported file type", path);
304 	return NULL;
305     }
306     if (u.hdr.e_machine != ELF_TARG_MACH) {
307 	_rtld_error("%s: unsupported machine", path);
308 	return NULL;
309     }
310 
311     /*
312      * We rely on the program header being in the first page.  This is
313      * not strictly required by the ABI specification, but it seems to
314      * always true in practice.  And, it simplifies things considerably.
315      */
316     if (u.hdr.e_phentsize != sizeof(Elf_Phdr)) {
317 	_rtld_error(
318 	  "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)", path);
319 	return NULL;
320     }
321     if (u.hdr.e_phoff + u.hdr.e_phnum * sizeof(Elf_Phdr) > (size_t)nbytes) {
322 	_rtld_error("%s: program header too large", path);
323 	return NULL;
324     }
325 
326     return (&u.hdr);
327 }
328 
329 void
330 obj_free(Obj_Entry *obj)
331 {
332     Objlist_Entry *elm;
333 
334     if (obj->tls_done)
335 	free_tls_offset(obj);
336     while (obj->needed != NULL) {
337 	Needed_Entry *needed = obj->needed;
338 	obj->needed = needed->next;
339 	free(needed);
340     }
341     while (!STAILQ_EMPTY(&obj->names)) {
342 	Name_Entry *entry = STAILQ_FIRST(&obj->names);
343 	STAILQ_REMOVE_HEAD(&obj->names, link);
344 	free(entry);
345     }
346     while (!STAILQ_EMPTY(&obj->dldags)) {
347 	elm = STAILQ_FIRST(&obj->dldags);
348 	STAILQ_REMOVE_HEAD(&obj->dldags, link);
349 	free(elm);
350     }
351     while (!STAILQ_EMPTY(&obj->dagmembers)) {
352 	elm = STAILQ_FIRST(&obj->dagmembers);
353 	STAILQ_REMOVE_HEAD(&obj->dagmembers, link);
354 	free(elm);
355     }
356     if (obj->vertab)
357 	free(obj->vertab);
358     if (obj->origin_path)
359 	free(obj->origin_path);
360     if (obj->z_origin)
361 	free(obj->rpath);
362     if (obj->priv)
363 	free(obj->priv);
364     if (obj->path)
365 	free(obj->path);
366     if (obj->phdr_alloc)
367 	free((void *)obj->phdr);
368     free(obj);
369 }
370 
371 Obj_Entry *
372 obj_new(void)
373 {
374     Obj_Entry *obj;
375 
376     obj = CNEW(Obj_Entry);
377     STAILQ_INIT(&obj->dldags);
378     STAILQ_INIT(&obj->dagmembers);
379     STAILQ_INIT(&obj->names);
380     return obj;
381 }
382 
383 /*
384  * Given a set of ELF protection flags, return the corresponding protection
385  * flags for MMAP.
386  */
387 static int
388 convert_prot(int elfflags)
389 {
390     int prot = 0;
391     if (elfflags & PF_R)
392 	prot |= PROT_READ;
393     if (elfflags & PF_W)
394 	prot |= PROT_WRITE;
395     if (elfflags & PF_X)
396 	prot |= PROT_EXEC;
397     return prot;
398 }
399 
400 static int
401 convert_flags(int elfflags)
402 {
403     int flags = MAP_PRIVATE; /* All mappings are private */
404 
405     /*
406      * Readonly mappings are marked "MAP_NOCORE", because they can be
407      * reconstructed by a debugger.
408      */
409     if (!(elfflags & PF_W))
410 	flags |= MAP_NOCORE;
411     return flags;
412 }
413