xref: /freebsd/libexec/rtld-elf/map_object.c (revision 77b7cdf1999ee965ad494fddd184b18f532ac91a)
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 int convert_prot(int);	/* Elf flags -> mmap protection */
42 static int convert_flags(int); /* Elf flags -> mmap flags */
43 
44 /*
45  * Map a shared object into memory.  The "fd" argument is a file descriptor,
46  * which must be open on the object and positioned at its beginning.
47  * The "path" argument is a pathname that is used only for error messages.
48  *
49  * The return value is a pointer to a newly-allocated Obj_Entry structure
50  * for the shared object.  Returns NULL on failure.
51  */
52 Obj_Entry *
53 map_object(int fd, const char *path, const struct stat *sb)
54 {
55     Obj_Entry *obj;
56     union {
57 	Elf_Ehdr hdr;
58 	char buf[PAGE_SIZE];
59     } u;
60     int i;
61     ssize_t nbytes;
62     Elf_Phdr *phdr;
63     Elf_Phdr *phlimit;
64     Elf_Phdr **segs;
65     int nsegs;
66     Elf_Phdr *phdyn;
67     Elf_Phdr *phphdr;
68     Elf_Phdr *phinterp;
69     caddr_t mapbase;
70     size_t mapsize;
71     Elf_Off base_offset;
72     Elf_Addr base_vaddr;
73     Elf_Addr base_vlimit;
74     caddr_t base_addr;
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     size_t nclear;
85     Elf_Addr bss_vaddr;
86     Elf_Addr bss_vlimit;
87     caddr_t bss_addr;
88 
89     if ((nbytes = read(fd, u.buf, PAGE_SIZE)) == -1) {
90 	_rtld_error("%s: read error: %s", path, strerror(errno));
91 	return NULL;
92     }
93 
94     /* Make sure the file is valid */
95     if (nbytes < (ssize_t)sizeof(Elf_Ehdr)
96       || u.hdr.e_ident[EI_MAG0] != ELFMAG0
97       || u.hdr.e_ident[EI_MAG1] != ELFMAG1
98       || u.hdr.e_ident[EI_MAG2] != ELFMAG2
99       || u.hdr.e_ident[EI_MAG3] != ELFMAG3) {
100 	_rtld_error("%s: invalid file format", path);
101 	return NULL;
102     }
103     if (u.hdr.e_ident[EI_CLASS] != ELF_TARG_CLASS
104       || u.hdr.e_ident[EI_DATA] != ELF_TARG_DATA) {
105 	_rtld_error("%s: unsupported file layout", path);
106 	return NULL;
107     }
108     if (u.hdr.e_ident[EI_VERSION] != EV_CURRENT
109       || u.hdr.e_version != EV_CURRENT) {
110 	_rtld_error("%s: unsupported file version", path);
111 	return NULL;
112     }
113     if (u.hdr.e_type != ET_EXEC && u.hdr.e_type != ET_DYN) {
114 	_rtld_error("%s: unsupported file type", path);
115 	return NULL;
116     }
117     if (u.hdr.e_machine != ELF_TARG_MACH) {
118 	_rtld_error("%s: unsupported machine", path);
119 	return NULL;
120     }
121 
122     /*
123      * We rely on the program header being in the first page.  This is
124      * not strictly required by the ABI specification, but it seems to
125      * always true in practice.  And, it simplifies things considerably.
126      */
127     if (u.hdr.e_phentsize != sizeof(Elf_Phdr)) {
128 	_rtld_error(
129 	  "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)", path);
130 	return NULL;
131     }
132     if (u.hdr.e_phoff + u.hdr.e_phnum * sizeof(Elf_Phdr) > (size_t)nbytes) {
133 	_rtld_error("%s: program header too large", path);
134 	return NULL;
135     }
136 
137     /*
138      * Scan the program header entries, and save key information.
139      *
140      * We rely on there being exactly two load segments, text and data,
141      * in that order.
142      */
143     phdr = (Elf_Phdr *) (u.buf + u.hdr.e_phoff);
144     phlimit = phdr + u.hdr.e_phnum;
145     nsegs = -1;
146     phdyn = phphdr = phinterp = NULL;
147     segs = alloca(sizeof(segs[0]) * u.hdr.e_phnum);
148     while (phdr < phlimit) {
149 	switch (phdr->p_type) {
150 
151 	case PT_INTERP:
152 	    phinterp = phdr;
153 	    break;
154 
155 	case PT_LOAD:
156 	    segs[++nsegs] = phdr;
157     	    if (segs[nsegs]->p_align < PAGE_SIZE) {
158 		_rtld_error("%s: PT_LOAD segment %d not page-aligned",
159 		    path, nsegs);
160 		return NULL;
161 	    }
162 	    break;
163 
164 	case PT_PHDR:
165 	    phphdr = phdr;
166 	    break;
167 
168 	case PT_DYNAMIC:
169 	    phdyn = phdr;
170 	    break;
171 	}
172 
173 	++phdr;
174     }
175     if (phdyn == NULL) {
176 	_rtld_error("%s: object is not dynamically-linked", path);
177 	return NULL;
178     }
179 
180     if (nsegs < 0) {
181 	_rtld_error("%s: too few PT_LOAD segments", path);
182 	return NULL;
183     }
184 
185     /*
186      * Map the entire address space of the object, to stake out our
187      * contiguous region, and to establish the base address for relocation.
188      */
189     base_offset = trunc_page(segs[0]->p_offset);
190     base_vaddr = trunc_page(segs[0]->p_vaddr);
191     base_vlimit = round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz);
192     mapsize = base_vlimit - base_vaddr;
193     base_addr = u.hdr.e_type == ET_EXEC ? (caddr_t) base_vaddr : NULL;
194 
195     mapbase = mmap(base_addr, mapsize, convert_prot(segs[0]->p_flags),
196       convert_flags(segs[0]->p_flags), fd, base_offset);
197     if (mapbase == (caddr_t) -1) {
198 	_rtld_error("%s: mmap of entire address space failed: %s",
199 	  path, strerror(errno));
200 	return NULL;
201     }
202     if (base_addr != NULL && mapbase != base_addr) {
203 	_rtld_error("%s: mmap returned wrong address: wanted %p, got %p",
204 	  path, base_addr, mapbase);
205 	munmap(mapbase, mapsize);
206 	return NULL;
207     }
208 
209     for (i = 0; i <=  nsegs; i++) {
210 	/* Overlay the segment onto the proper region. */
211 	data_offset = trunc_page(segs[i]->p_offset);
212 	data_vaddr = trunc_page(segs[i]->p_vaddr);
213 	data_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_filesz);
214 	data_addr = mapbase + (data_vaddr - base_vaddr);
215 	data_prot = convert_prot(segs[i]->p_flags);
216 	data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED;
217 	/* Do not call mmap on the first segment - this is redundant */
218 	if (i && mmap(data_addr, data_vlimit - data_vaddr, data_prot,
219 	  data_flags, fd, data_offset) == (caddr_t) -1) {
220 	    _rtld_error("%s: mmap of data failed: %s", path, strerror(errno));
221 	    return NULL;
222 	}
223 
224 	/* Clear any BSS in the last page of the segment. */
225 	clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
226 	clear_addr = mapbase + (clear_vaddr - base_vaddr);
227 	clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr);
228 	if ((nclear = data_vlimit - clear_vaddr) > 0) {
229 	    /* Make sure the end of the segment is writable */
230 	    if ((data_prot & PROT_WRITE) == 0 &&
231 		-1 ==  mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE)) {
232 			_rtld_error("%s: mprotect failed: %s", path,
233 			    strerror(errno));
234 			return NULL;
235 	    }
236 
237 	    memset(clear_addr, 0, nclear);
238 
239 	    /* Reset the data protection back */
240 	    if ((data_prot & PROT_WRITE) == 0)
241 		 mprotect(clear_page, PAGE_SIZE, data_prot);
242 	}
243 
244 	/* Overlay the BSS segment onto the proper region. */
245 	bss_vaddr = data_vlimit;
246 	bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
247 	bss_addr = mapbase +  (bss_vaddr - base_vaddr);
248 	if (bss_vlimit > bss_vaddr) {	/* There is something to do */
249 	    if (mmap(bss_addr, bss_vlimit - bss_vaddr, data_prot,
250 		MAP_PRIVATE|MAP_FIXED|MAP_ANON, -1, 0) == (caddr_t) -1) {
251 		    _rtld_error("%s: mmap of bss failed: %s", path,
252 			strerror(errno));
253 		return NULL;
254 	    }
255 	}
256     }
257 
258     obj = obj_new();
259     if (sb != NULL) {
260 	obj->dev = sb->st_dev;
261 	obj->ino = sb->st_ino;
262     }
263     obj->mapbase = mapbase;
264     obj->mapsize = mapsize;
265     obj->textsize = round_page(segs[0]->p_vaddr + segs[0]->p_memsz) -
266       base_vaddr;
267     obj->vaddrbase = base_vaddr;
268     obj->relocbase = mapbase - base_vaddr;
269     obj->dynamic = (const Elf_Dyn *) (obj->relocbase + phdyn->p_vaddr);
270     if (u.hdr.e_entry != 0)
271 	obj->entry = (caddr_t) (obj->relocbase + u.hdr.e_entry);
272     if (phphdr != NULL) {
273 	obj->phdr = (const Elf_Phdr *) (obj->relocbase + phphdr->p_vaddr);
274 	obj->phsize = phphdr->p_memsz;
275     }
276     if (phinterp != NULL)
277 	obj->interp = (const char *) (obj->relocbase + phinterp->p_vaddr);
278 
279     return obj;
280 }
281 
282 void
283 obj_free(Obj_Entry *obj)
284 {
285     Objlist_Entry *elm;
286 
287     free(obj->path);
288     while (obj->needed != NULL) {
289 	Needed_Entry *needed = obj->needed;
290 	obj->needed = needed->next;
291 	free(needed);
292     }
293     while (!STAILQ_EMPTY(&obj->dldags)) {
294 	elm = STAILQ_FIRST(&obj->dldags);
295 	STAILQ_REMOVE_HEAD(&obj->dldags, link);
296 	free(elm);
297     }
298     while (!STAILQ_EMPTY(&obj->dagmembers)) {
299 	elm = STAILQ_FIRST(&obj->dagmembers);
300 	STAILQ_REMOVE_HEAD(&obj->dagmembers, link);
301 	free(elm);
302     }
303     free(obj->priv);
304     free(obj);
305 }
306 
307 Obj_Entry *
308 obj_new(void)
309 {
310     Obj_Entry *obj;
311 
312     obj = CNEW(Obj_Entry);
313     STAILQ_INIT(&obj->dldags);
314     STAILQ_INIT(&obj->dagmembers);
315     return obj;
316 }
317 
318 /*
319  * Given a set of ELF protection flags, return the corresponding protection
320  * flags for MMAP.
321  */
322 static int
323 convert_prot(int elfflags)
324 {
325     int prot = 0;
326     if (elfflags & PF_R)
327 	prot |= PROT_READ;
328     if (elfflags & PF_W)
329 	prot |= PROT_WRITE;
330     if (elfflags & PF_X)
331 	prot |= PROT_EXEC;
332     return prot;
333 }
334 
335 static int
336 convert_flags(int elfflags)
337 {
338     int flags = MAP_PRIVATE; /* All mappings are private */
339 
340     /*
341      * Readonly mappings are marked "MAP_NOCORE", because they can be
342      * reconstructed by a debugger.
343      */
344     if (!(elfflags & PF_W))
345 	flags |= MAP_NOCORE;
346     return flags;
347 }
348