xref: /netbsd-src/libexec/ld.elf_so/map_object.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: map_object.c,v 1.35 2007/10/05 22:21:07 ad Exp $	 */
2 
3 /*
4  * Copyright 1996 John D. Polstra.
5  * Copyright 1996 Matt Thomas <matt@3am-software.com>
6  * Copyright 2002 Charles M. Hannum <root@ihack.net>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by John Polstra.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __RCSID("$NetBSD: map_object.c,v 1.35 2007/10/05 22:21:07 ad Exp $");
38 #endif /* not lint */
39 
40 #include <errno.h>
41 #include <stddef.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #include <sys/mman.h>
48 
49 #include "rtld.h"
50 
51 static int protflags(int);	/* Elf flags -> mmap protection */
52 
53 /*
54  * Map a shared object into memory.  The argument is a file descriptor,
55  * which must be open on the object and positioned at its beginning.
56  *
57  * The return value is a pointer to a newly-allocated Obj_Entry structure
58  * for the shared object.  Returns NULL on failure.
59  */
60 Obj_Entry *
61 _rtld_map_object(const char *path, int fd, const struct stat *sb)
62 {
63 	Obj_Entry	*obj;
64 	Elf_Ehdr	*ehdr;
65 	Elf_Phdr	*phdr;
66 	Elf_Phdr	*phlimit;
67 	Elf_Phdr	*segs[2];
68 	int		 nsegs;
69 	caddr_t		 mapbase = MAP_FAILED;
70 	size_t		 mapsize = 0;
71 	int		 mapflags;
72 	Elf_Off		 base_offset;
73 #ifdef MAP_ALIGNED
74 	Elf_Addr	 base_alignment;
75 #endif
76 	Elf_Addr	 base_vaddr;
77 	Elf_Addr	 base_vlimit;
78 	Elf_Addr	 text_vlimit;
79 	int		 text_flags;
80 	caddr_t		 base_addr;
81 	Elf_Off		 data_offset;
82 	Elf_Addr	 data_vaddr;
83 	Elf_Addr	 data_vlimit;
84 	int		 data_flags;
85 	caddr_t		 data_addr;
86 	caddr_t		 gap_addr;
87 	size_t		 gap_size;
88 #ifdef RTLD_LOADER
89 	Elf_Addr	 clear_vaddr;
90 	caddr_t		 clear_addr;
91 	size_t		 nclear;
92 #endif
93 
94 	if (sb != NULL && sb->st_size < sizeof (Elf_Ehdr)) {
95 		_rtld_error("%s: unrecognized file format", path);
96 		return NULL;
97 	}
98 
99 	obj = _rtld_obj_new();
100 	obj->path = xstrdup(path);
101 	obj->pathlen = strlen(path);
102 	if (sb != NULL) {
103 		obj->dev = sb->st_dev;
104 		obj->ino = sb->st_ino;
105 	}
106 
107 	ehdr = mmap(NULL, _rtld_pagesz, PROT_READ, MAP_FILE | MAP_SHARED, fd,
108 	    (off_t)0);
109 	if (ehdr == MAP_FAILED) {
110 		_rtld_error("%s: read error: %s", path, xstrerror(errno));
111 		goto bad;
112 	}
113 	/* Make sure the file is valid */
114 	if (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0 ||
115 	    ehdr->e_ident[EI_CLASS] != ELFCLASS) {
116 		_rtld_error("%s: unrecognized file format", path);
117 		goto bad;
118 	}
119 	/* Elf_e_ident includes class */
120 	if (ehdr->e_ident[EI_VERSION] != EV_CURRENT ||
121 	    ehdr->e_version != EV_CURRENT ||
122 	    ehdr->e_ident[EI_DATA] != ELFDEFNNAME(MACHDEP_ENDIANNESS)) {
123 		_rtld_error("%s: unsupported file version", path);
124 		goto bad;
125 	}
126 	if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) {
127 		_rtld_error("%s: unsupported file type", path);
128 		goto bad;
129 	}
130 	switch (ehdr->e_machine) {
131 		ELFDEFNNAME(MACHDEP_ID_CASES)
132 	default:
133 		_rtld_error("%s: unsupported machine", path);
134 		goto bad;
135 	}
136 
137 	/*
138          * We rely on the program header being in the first page.  This is
139          * not strictly required by the ABI specification, but it seems to
140          * always true in practice.  And, it simplifies things considerably.
141          */
142 	assert(ehdr->e_phentsize == sizeof(Elf_Phdr));
143 	assert(ehdr->e_phoff + ehdr->e_phnum * sizeof(Elf_Phdr) <=
144 	    _rtld_pagesz);
145 
146 	/*
147          * Scan the program header entries, and save key information.
148          *
149          * We rely on there being exactly two load segments, text and data,
150          * in that order.
151          */
152 	phdr = (Elf_Phdr *) ((caddr_t)ehdr + ehdr->e_phoff);
153 	phlimit = phdr + ehdr->e_phnum;
154 	nsegs = 0;
155 	while (phdr < phlimit) {
156 		switch (phdr->p_type) {
157 		case PT_INTERP:
158 			obj->interp = (void *)phdr->p_vaddr;
159 			break;
160 
161 		case PT_LOAD:
162 			if (nsegs < 2)
163 				segs[nsegs] = phdr;
164 			++nsegs;
165 			break;
166 
167 		case PT_DYNAMIC:
168 			obj->dynamic = (void *)phdr->p_vaddr;
169 			break;
170 		}
171 
172 		++phdr;
173 	}
174 	obj->entry = (void *)ehdr->e_entry;
175 	if (!obj->dynamic) {
176 		_rtld_error("%s: not dynamically linked", path);
177 		goto bad;
178 	}
179 	if (nsegs != 2) {
180 		_rtld_error("%s: wrong number of segments (%d != 2)", path,
181 		    nsegs);
182 		goto bad;
183 	}
184 
185 	/*
186 	 * Map the entire address space of the object as a file
187 	 * region to stake out our contiguous region and establish a
188 	 * base for relocation.  We use a file mapping so that
189 	 * the kernel will give us whatever alignment is appropriate
190 	 * for the platform we're running on.
191 	 *
192 	 * We map it using the text protection, map the data segment
193 	 * into the right place, then map an anon segment for the bss
194 	 * and unmap the gaps left by padding to alignment.
195 	 */
196 
197 #ifdef MAP_ALIGNED
198 	base_alignment = segs[0]->p_align;
199 #endif
200 	base_offset = round_down(segs[0]->p_offset);
201 	base_vaddr = round_down(segs[0]->p_vaddr);
202 	base_vlimit = round_up(segs[1]->p_vaddr + segs[1]->p_memsz);
203 	text_vlimit = round_up(segs[0]->p_vaddr + segs[0]->p_memsz);
204 	text_flags = protflags(segs[0]->p_flags);
205 	data_offset = round_down(segs[1]->p_offset);
206 	data_vaddr = round_down(segs[1]->p_vaddr);
207 	data_vlimit = round_up(segs[1]->p_vaddr + segs[1]->p_filesz);
208 	data_flags = protflags(segs[1]->p_flags);
209 #ifdef RTLD_LOADER
210 	clear_vaddr = segs[1]->p_vaddr + segs[1]->p_filesz;
211 #endif
212 
213 	obj->textsize = text_vlimit - base_vaddr;
214 	obj->vaddrbase = base_vaddr;
215 	obj->isdynamic = ehdr->e_type == ET_DYN;
216 
217 	munmap(ehdr, _rtld_pagesz);
218 	ehdr = MAP_FAILED;
219 
220 	/*
221 	 * Calculate log2 of the base section alignment.
222 	 */
223 	mapflags = 0;
224 #ifdef MAP_ALIGNED
225 	if (base_alignment > _rtld_pagesz) {
226 		unsigned int log2 = 0;
227 		for (; base_alignment > 1; base_alignment >>= 1)
228 			log2++;
229 		mapflags = MAP_ALIGNED(log2);
230 	}
231 #endif
232 
233 #ifdef RTLD_LOADER
234 	base_addr = obj->isdynamic ? NULL : (caddr_t)base_vaddr;
235 #else
236 	base_addr = NULL;
237 #endif
238 	mapsize = base_vlimit - base_vaddr;
239 	mapbase = mmap(base_addr, mapsize, text_flags,
240 	    mapflags | MAP_FILE | MAP_PRIVATE, fd, base_offset);
241 	if (mapbase == MAP_FAILED) {
242 		_rtld_error("mmap of entire address space failed: %s",
243 		    xstrerror(errno));
244 		goto bad;
245 	}
246 
247 	/* Overlay the data segment onto the proper region. */
248 	data_addr = mapbase + (data_vaddr - base_vaddr);
249 	if (mmap(data_addr, data_vlimit - data_vaddr, data_flags,
250 	    MAP_FILE | MAP_PRIVATE | MAP_FIXED, fd, data_offset) ==
251 	    MAP_FAILED) {
252 		_rtld_error("mmap of data failed: %s", xstrerror(errno));
253 		goto bad;
254 	}
255 
256 	/* Overlay the bss segment onto the proper region. */
257 	if (mmap(mapbase + data_vlimit - base_vaddr, base_vlimit - data_vlimit,
258 	    data_flags, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) ==
259 	    MAP_FAILED) {
260 		_rtld_error("mmap of bss failed: %s", xstrerror(errno));
261 		goto bad;
262 	}
263 
264 	/* Unmap the gap between the text and data. */
265 	gap_addr = mapbase + round_up(text_vlimit - base_vaddr);
266 	gap_size = data_addr - gap_addr;
267 	if (gap_size != 0 && mprotect(gap_addr, gap_size, PROT_NONE) == -1) {
268 		_rtld_error("mprotect of text -> data gap failed: %s",
269 		    xstrerror(errno));
270 		goto bad;
271 	}
272 
273 #ifdef RTLD_LOADER
274 	/* Clear any BSS in the last page of the data segment. */
275 	clear_addr = mapbase + (clear_vaddr - base_vaddr);
276 	if ((nclear = data_vlimit - clear_vaddr) > 0)
277 		memset(clear_addr, 0, nclear);
278 
279 	/* Non-file portion of BSS mapped above. */
280 #endif
281 
282 	obj->mapbase = mapbase;
283 	obj->mapsize = mapsize;
284 	obj->relocbase = mapbase - base_vaddr;
285 
286 	if (obj->dynamic)
287 		obj->dynamic = (void *)(obj->relocbase + (Elf_Addr)obj->dynamic);
288 	if (obj->entry)
289 		obj->entry = (void *)(obj->relocbase + (Elf_Addr)obj->entry);
290 	if (obj->interp)
291 		obj->interp = (void *)(obj->relocbase + (Elf_Addr)obj->interp);
292 
293 	return obj;
294 
295 bad:
296 	if (ehdr != MAP_FAILED)
297 		munmap(ehdr, _rtld_pagesz);
298 	if (mapbase != MAP_FAILED)
299 		munmap(mapbase, mapsize);
300 	_rtld_obj_free(obj);
301 	return NULL;
302 }
303 
304 void
305 _rtld_obj_free(Obj_Entry *obj)
306 {
307 	Objlist_Entry *elm;
308 
309 	xfree(obj->path);
310 	while (obj->needed != NULL) {
311 		Needed_Entry *needed = obj->needed;
312 		obj->needed = needed->next;
313 		xfree(needed);
314 	}
315 	while ((elm = SIMPLEQ_FIRST(&obj->dldags)) != NULL) {
316 		SIMPLEQ_REMOVE_HEAD(&obj->dldags, link);
317 		xfree(elm);
318 	}
319 	while ((elm = SIMPLEQ_FIRST(&obj->dagmembers)) != NULL) {
320 		SIMPLEQ_REMOVE_HEAD(&obj->dagmembers, link);
321 		xfree(elm);
322 	}
323 	xfree(obj);
324 }
325 
326 Obj_Entry *
327 _rtld_obj_new(void)
328 {
329 	Obj_Entry *obj;
330 
331 	obj = CNEW(Obj_Entry);
332 	SIMPLEQ_INIT(&obj->dldags);
333 	SIMPLEQ_INIT(&obj->dagmembers);
334 	return obj;
335 }
336 
337 /*
338  * Given a set of ELF protection flags, return the corresponding protection
339  * flags for MMAP.
340  */
341 static int
342 protflags(int elfflags)
343 {
344 	int prot = 0;
345 
346 	if (elfflags & PF_R)
347 		prot |= PROT_READ;
348 #ifdef RTLD_LOADER
349 	if (elfflags & PF_W)
350 		prot |= PROT_WRITE;
351 #endif
352 	if (elfflags & PF_X)
353 		prot |= PROT_EXEC;
354 	return prot;
355 }
356