xref: /netbsd-src/libexec/ld.elf_so/map_object.c (revision 46f5119e40af2e51998f686b2fdcc76b5488f7f3)
1 /*	$NetBSD: map_object.c,v 1.42 2011/03/09 23:10:07 joerg 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.42 2011/03/09 23:10:07 joerg 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 "debug.h"
50 #include "rtld.h"
51 
52 static int protflags(int);	/* Elf flags -> mmap protection */
53 
54 #define EA_UNDEF		(~(Elf_Addr)0)
55 
56 /*
57  * Map a shared object into memory.  The argument is a file descriptor,
58  * which must be open on the object and positioned at its beginning.
59  *
60  * The return value is a pointer to a newly-allocated Obj_Entry structure
61  * for the shared object.  Returns NULL on failure.
62  */
63 Obj_Entry *
64 _rtld_map_object(const char *path, int fd, const struct stat *sb)
65 {
66 	Obj_Entry	*obj;
67 	Elf_Ehdr	*ehdr;
68 	Elf_Phdr	*phdr;
69 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
70 	Elf_Phdr	*phtls;
71 #endif
72 	size_t		 phsize;
73 	Elf_Phdr	*phlimit;
74 	Elf_Phdr	*segs[2];
75 	int		 nsegs;
76 	caddr_t		 mapbase = MAP_FAILED;
77 	size_t		 mapsize = 0;
78 	int		 mapflags;
79 	Elf_Off		 base_offset;
80 #ifdef MAP_ALIGNED
81 	Elf_Addr	 base_alignment;
82 #endif
83 	Elf_Addr	 base_vaddr;
84 	Elf_Addr	 base_vlimit;
85 	Elf_Addr	 text_vlimit;
86 	int		 text_flags;
87 	caddr_t		 base_addr;
88 	Elf_Off		 data_offset;
89 	Elf_Addr	 data_vaddr;
90 	Elf_Addr	 data_vlimit;
91 	int		 data_flags;
92 	caddr_t		 data_addr;
93 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
94 	Elf_Addr	 tls_vaddr = 0; /* Noise GCC */
95 #endif
96 	Elf_Addr	 phdr_vaddr;
97 	size_t		 phdr_memsz;
98 	caddr_t		 gap_addr;
99 	size_t		 gap_size;
100 	int i;
101 #ifdef RTLD_LOADER
102 	Elf_Addr	 clear_vaddr;
103 	caddr_t		 clear_addr;
104 	size_t		 nclear;
105 #endif
106 
107 	if (sb != NULL && sb->st_size < (off_t)sizeof (Elf_Ehdr)) {
108 		_rtld_error("%s: unrecognized file format1", path);
109 		return NULL;
110 	}
111 
112 	obj = _rtld_obj_new();
113 	obj->path = xstrdup(path);
114 	obj->pathlen = strlen(path);
115 	if (sb != NULL) {
116 		obj->dev = sb->st_dev;
117 		obj->ino = sb->st_ino;
118 	}
119 
120 	ehdr = mmap(NULL, _rtld_pagesz, PROT_READ, MAP_FILE | MAP_SHARED, fd,
121 	    (off_t)0);
122 	obj->ehdr = ehdr;
123 	if (ehdr == MAP_FAILED) {
124 		_rtld_error("%s: read error: %s", path, xstrerror(errno));
125 		goto bad;
126 	}
127 	/* Make sure the file is valid */
128 	if (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0 ||
129 	    ehdr->e_ident[EI_CLASS] != ELFCLASS) {
130 		_rtld_error("%s: unrecognized file format2 [%x != %x]", path,
131 		    ehdr->e_ident[EI_CLASS], ELFCLASS);
132 		goto bad;
133 	}
134 	/* Elf_e_ident includes class */
135 	if (ehdr->e_ident[EI_VERSION] != EV_CURRENT ||
136 	    ehdr->e_version != EV_CURRENT ||
137 	    ehdr->e_ident[EI_DATA] != ELFDEFNNAME(MACHDEP_ENDIANNESS)) {
138 		_rtld_error("%s: unsupported file version", path);
139 		goto bad;
140 	}
141 	if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) {
142 		_rtld_error("%s: unsupported file type", path);
143 		goto bad;
144 	}
145 	switch (ehdr->e_machine) {
146 		ELFDEFNNAME(MACHDEP_ID_CASES)
147 	default:
148 		_rtld_error("%s: unsupported machine", path);
149 		goto bad;
150 	}
151 
152 	/*
153          * We rely on the program header being in the first page.  This is
154          * not strictly required by the ABI specification, but it seems to
155          * always true in practice.  And, it simplifies things considerably.
156          */
157 	assert(ehdr->e_phentsize == sizeof(Elf_Phdr));
158 	assert(ehdr->e_phoff + ehdr->e_phnum * sizeof(Elf_Phdr) <=
159 	    _rtld_pagesz);
160 
161 	/*
162          * Scan the program header entries, and save key information.
163          *
164          * We rely on there being exactly two load segments, text and data,
165          * in that order.
166          */
167 	phdr = (Elf_Phdr *) ((caddr_t)ehdr + ehdr->e_phoff);
168 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
169 	phtls = NULL;
170 #endif
171 	phsize = ehdr->e_phnum * sizeof(phdr[0]);
172 	obj->phdr = NULL;
173 	phdr_vaddr = EA_UNDEF;
174 	phdr_memsz = 0;
175 	phlimit = phdr + ehdr->e_phnum;
176 	nsegs = 0;
177 	while (phdr < phlimit) {
178 		switch (phdr->p_type) {
179 		case PT_INTERP:
180 			obj->interp = (void *)(uintptr_t)phdr->p_vaddr;
181  			dbg(("%s: PT_INTERP %p", obj->path, obj->interp));
182 			break;
183 
184 		case PT_LOAD:
185 			if (nsegs < 2)
186 				segs[nsegs] = phdr;
187 			++nsegs;
188 			dbg(("%s: PT_LOAD %p", obj->path, phdr));
189 			break;
190 
191 		case PT_PHDR:
192 			phdr_vaddr = phdr->p_vaddr;
193 			phdr_memsz = phdr->p_memsz;
194 			dbg(("%s: PT_PHDR %p phsize %zu", obj->path,
195 			    (void *)(uintptr_t)phdr_vaddr, phdr_memsz));
196 			break;
197 
198 		case PT_DYNAMIC:
199 			obj->dynamic = (void *)(uintptr_t)phdr->p_vaddr;
200  			dbg(("%s: PT_DYNAMIC %p", obj->path, obj->dynamic));
201 			break;
202 
203 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
204 		case PT_TLS:
205 			phtls = phdr;
206 			break;
207 #endif
208 		}
209 
210 		++phdr;
211 	}
212 	phdr = (Elf_Phdr *) ((caddr_t)ehdr + ehdr->e_phoff);
213 	obj->entry = (void *)(uintptr_t)ehdr->e_entry;
214 	if (!obj->dynamic) {
215 		_rtld_error("%s: not dynamically linked", path);
216 		goto bad;
217 	}
218 	if (nsegs != 2) {
219 		_rtld_error("%s: wrong number of segments (%d != 2)", path,
220 		    nsegs);
221 		goto bad;
222 	}
223 
224 	/*
225 	 * Map the entire address space of the object as a file
226 	 * region to stake out our contiguous region and establish a
227 	 * base for relocation.  We use a file mapping so that
228 	 * the kernel will give us whatever alignment is appropriate
229 	 * for the platform we're running on.
230 	 *
231 	 * We map it using the text protection, map the data segment
232 	 * into the right place, then map an anon segment for the bss
233 	 * and unmap the gaps left by padding to alignment.
234 	 */
235 
236 #ifdef MAP_ALIGNED
237 	base_alignment = segs[0]->p_align;
238 #endif
239 	base_offset = round_down(segs[0]->p_offset);
240 	base_vaddr = round_down(segs[0]->p_vaddr);
241 	base_vlimit = round_up(segs[1]->p_vaddr + segs[1]->p_memsz);
242 	text_vlimit = round_up(segs[0]->p_vaddr + segs[0]->p_memsz);
243 	text_flags = protflags(segs[0]->p_flags);
244 	data_offset = round_down(segs[1]->p_offset);
245 	data_vaddr = round_down(segs[1]->p_vaddr);
246 	data_vlimit = round_up(segs[1]->p_vaddr + segs[1]->p_filesz);
247 	data_flags = protflags(segs[1]->p_flags);
248 #ifdef RTLD_LOADER
249 	clear_vaddr = segs[1]->p_vaddr + segs[1]->p_filesz;
250 #endif
251 
252 	obj->textsize = text_vlimit - base_vaddr;
253 	obj->vaddrbase = base_vaddr;
254 	obj->isdynamic = ehdr->e_type == ET_DYN;
255 
256 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
257 	if (phtls != NULL) {
258 		++_rtld_tls_dtv_generation;
259 		obj->tlsindex = ++_rtld_tls_max_index;
260 		obj->tlssize = phtls->p_memsz;
261 		obj->tlsalign = phtls->p_align;
262 		obj->tlsinitsize = phtls->p_filesz;
263 		tls_vaddr = phtls->p_vaddr;
264 	}
265 #endif
266 
267 	obj->phdr_loaded = false;
268 	for (i = 0; i < nsegs; i++) {
269 		if (phdr_vaddr != EA_UNDEF &&
270 		    segs[i]->p_vaddr <= phdr_vaddr &&
271 		    segs[i]->p_memsz >= phdr_memsz) {
272 			obj->phdr_loaded = true;
273 			break;
274 		}
275 		if (segs[i]->p_offset <= ehdr->e_phoff &&
276 		    segs[i]->p_memsz >= phsize) {
277 			phdr_vaddr = segs[i]->p_vaddr + ehdr->e_phoff;
278 			phdr_memsz = phsize;
279 			obj->phdr_loaded = true;
280 			break;
281 		}
282 	}
283 	if (obj->phdr_loaded) {
284 		obj->phdr = (void *)(uintptr_t)phdr_vaddr;
285 		obj->phsize = phdr_memsz;
286 	} else {
287 		Elf_Phdr *buf;
288 		buf = xmalloc(phsize);
289 		if (buf == NULL) {
290 			_rtld_error("%s: cannot allocate program header", path);
291 			goto bad;
292 		}
293 		memcpy(buf, phdr, phsize);
294 		obj->phdr = buf;
295 		obj->phsize = phsize;
296 	}
297 	dbg(("%s: phdr %p phsize %zu (%s)", obj->path, obj->phdr, obj->phsize,
298 	     obj->phdr_loaded ? "loaded" : "allocated"));
299 
300 	/* Unmap header if it overlaps the first load section. */
301 	if (base_offset < _rtld_pagesz) {
302 		munmap(ehdr, _rtld_pagesz);
303 		obj->ehdr = MAP_FAILED;
304 	}
305 
306 	/*
307 	 * Calculate log2 of the base section alignment.
308 	 */
309 	mapflags = 0;
310 #ifdef MAP_ALIGNED
311 	if (base_alignment > _rtld_pagesz) {
312 		unsigned int log2 = 0;
313 		for (; base_alignment > 1; base_alignment >>= 1)
314 			log2++;
315 		mapflags = MAP_ALIGNED(log2);
316 	}
317 #endif
318 
319 #ifdef RTLD_LOADER
320 	base_addr = obj->isdynamic ? NULL : (caddr_t)base_vaddr;
321 #else
322 	base_addr = NULL;
323 #endif
324 	mapsize = base_vlimit - base_vaddr;
325 	mapbase = mmap(base_addr, mapsize, text_flags,
326 	    mapflags | MAP_FILE | MAP_PRIVATE, fd, base_offset);
327 	if (mapbase == MAP_FAILED) {
328 		_rtld_error("mmap of entire address space failed: %s",
329 		    xstrerror(errno));
330 		goto bad;
331 	}
332 
333 	/* Overlay the data segment onto the proper region. */
334 	data_addr = mapbase + (data_vaddr - base_vaddr);
335 	if (mmap(data_addr, data_vlimit - data_vaddr, data_flags,
336 	    MAP_FILE | MAP_PRIVATE | MAP_FIXED, fd, data_offset) ==
337 	    MAP_FAILED) {
338 		_rtld_error("mmap of data failed: %s", xstrerror(errno));
339 		goto bad;
340 	}
341 
342 	/* Overlay the bss segment onto the proper region. */
343 	if (mmap(mapbase + data_vlimit - base_vaddr, base_vlimit - data_vlimit,
344 	    data_flags, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) ==
345 	    MAP_FAILED) {
346 		_rtld_error("mmap of bss failed: %s", xstrerror(errno));
347 		goto bad;
348 	}
349 
350 	/* Unmap the gap between the text and data. */
351 	gap_addr = mapbase + round_up(text_vlimit - base_vaddr);
352 	gap_size = data_addr - gap_addr;
353 	if (gap_size != 0 && mprotect(gap_addr, gap_size, PROT_NONE) == -1) {
354 		_rtld_error("mprotect of text -> data gap failed: %s",
355 		    xstrerror(errno));
356 		goto bad;
357 	}
358 
359 #ifdef RTLD_LOADER
360 	/* Clear any BSS in the last page of the data segment. */
361 	clear_addr = mapbase + (clear_vaddr - base_vaddr);
362 	if ((nclear = data_vlimit - clear_vaddr) > 0)
363 		memset(clear_addr, 0, nclear);
364 
365 	/* Non-file portion of BSS mapped above. */
366 #endif
367 
368 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
369 	if (phtls != NULL)
370 		obj->tlsinit = mapbase + tls_vaddr;
371 #endif
372 
373 	obj->mapbase = mapbase;
374 	obj->mapsize = mapsize;
375 	obj->relocbase = mapbase - base_vaddr;
376 
377 	if (obj->dynamic)
378 		obj->dynamic = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->dynamic);
379 	if (obj->entry)
380 		obj->entry = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->entry);
381 	if (obj->interp)
382 		obj->interp = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->interp);
383 	if (obj->phdr_loaded)
384 		obj->phdr =  (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->phdr);
385 
386 	return obj;
387 
388 bad:
389 	if (obj->ehdr != MAP_FAILED)
390 		munmap(obj->ehdr, _rtld_pagesz);
391 	if (mapbase != MAP_FAILED)
392 		munmap(mapbase, mapsize);
393 	_rtld_obj_free(obj);
394 	return NULL;
395 }
396 
397 void
398 _rtld_obj_free(Obj_Entry *obj)
399 {
400 	Objlist_Entry *elm;
401 
402 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
403 	if (obj->tls_done)
404 		_rtld_tls_offset_free(obj);
405 #endif
406 	xfree(obj->path);
407 	while (obj->needed != NULL) {
408 		Needed_Entry *needed = obj->needed;
409 		obj->needed = needed->next;
410 		xfree(needed);
411 	}
412 	while ((elm = SIMPLEQ_FIRST(&obj->dldags)) != NULL) {
413 		SIMPLEQ_REMOVE_HEAD(&obj->dldags, link);
414 		xfree(elm);
415 	}
416 	while ((elm = SIMPLEQ_FIRST(&obj->dagmembers)) != NULL) {
417 		SIMPLEQ_REMOVE_HEAD(&obj->dagmembers, link);
418 		xfree(elm);
419 	}
420 	if (!obj->phdr_loaded)
421 		xfree((void *)(uintptr_t)obj->phdr);
422 	xfree(obj);
423 #ifdef COMBRELOC
424 	_rtld_combreloc_reset(obj);
425 #endif
426 }
427 
428 Obj_Entry *
429 _rtld_obj_new(void)
430 {
431 	Obj_Entry *obj;
432 
433 	obj = CNEW(Obj_Entry);
434 	SIMPLEQ_INIT(&obj->dldags);
435 	SIMPLEQ_INIT(&obj->dagmembers);
436 	return obj;
437 }
438 
439 /*
440  * Given a set of ELF protection flags, return the corresponding protection
441  * flags for MMAP.
442  */
443 static int
444 protflags(int elfflags)
445 {
446 	int prot = 0;
447 
448 	if (elfflags & PF_R)
449 		prot |= PROT_READ;
450 #ifdef RTLD_LOADER
451 	if (elfflags & PF_W)
452 		prot |= PROT_WRITE;
453 #endif
454 	if (elfflags & PF_X)
455 		prot |= PROT_EXEC;
456 	return prot;
457 }
458