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