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