xref: /netbsd/usr.sbin/kvm_mkdb/nlist_elf32.c (revision c1e0a5bd)
1 /* $NetBSD: nlist_elf32.c,v 1.19 2010/08/28 21:30:03 joerg Exp $ */
2 
3 /*
4  * Copyright (c) 1996 Christopher G. Demetriou
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *          This product includes software developed for the
18  *          NetBSD Project.  See http://www.NetBSD.org/ for
19  *          information about NetBSD.
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  * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
35  */
36 
37 #include <sys/cdefs.h>
38 #ifndef lint
39 __RCSID("$NetBSD: nlist_elf32.c,v 1.19 2010/08/28 21:30:03 joerg Exp $");
40 #endif /* not lint */
41 
42 /* If not included by nlist_elf64.c, ELFSIZE won't be defined. */
43 #ifndef ELFSIZE
44 #define	ELFSIZE		32
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/mman.h>
49 #include <sys/stat.h>
50 #include <sys/sysctl.h>
51 #include <sys/ioctl.h>
52 #include <sys/ksyms.h>
53 
54 #include <a.out.h>
55 #include <db.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <kvm.h>
60 #include <limits.h>
61 #include <paths.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 #include "extern.h"
68 
69 #if defined(NLIST_ELF32) || defined(NLIST_ELF64)
70 #include <sys/exec_elf.h>
71 #endif
72 
73 #if (defined(NLIST_ELF32) && (ELFSIZE == 32)) || \
74     (defined(NLIST_ELF64) && (ELFSIZE == 64))
75 
76 typedef struct nlist NLIST;
77 #define	_strx	n_un.n_strx
78 #define	_name	n_un.n_name
79 
80 #define	badfmt(str)							\
81 	do {								\
82 		warnx("%s: %s: %s", kfile, str, strerror(EFTYPE));	\
83 		punt();							\
84 	} while (0)
85 
86 #define	check(off, size)	((off < 0) || (off + size > mappedsize))
87 #define	BAD			do { rv = -1; goto out; } while (0)
88 #define	BADUNMAP		do { rv = -1; goto unmap; } while (0)
89 
90 static const char *kfile;
91 
92 int
93 ELFNAMEEND(create_knlist)(name, db)
94 	const char *name;
95 	DB *db;
96 {
97 	struct stat st;
98 	struct nlist nbuf;
99 	DBT key, data;
100 	char *mappedfile, *symname, *nsymname, *fsymname, *tmpcp, *strtab;
101 	size_t mappedsize, symnamesize, fsymnamesize;
102 	Elf_Ehdr *ehdrp;
103 	Elf_Shdr *shdrp, *symshdrp, *symstrshdrp;
104 	Elf_Sym *symp;
105 	Elf_Off shdr_off;
106 	Elf_Word shdr_size;
107 #if (ELFSIZE == 32)
108 	Elf32_Half nshdr;
109 #elif (ELFSIZE == 64)
110 	Elf64_Word nshdr;
111 #endif
112 	unsigned long i, nsyms;
113 	int fd, rv, malloced = 0, isksyms;
114 
115 	rv = -1;
116 #ifdef __GNUC__
117 	/* fix compiler warnings */
118 	symshdrp = NULL;
119 	symstrshdrp = NULL;
120 #endif
121 
122 	/*
123 	 * Open and map the whole file.  If we can't open/stat it,
124 	 * something bad is going on so we punt.
125 	 */
126 	kfile = name;
127 	if ((fd = open(name, O_RDONLY, 0)) < 0) {
128 		warn("%s", kfile);
129 		punt();
130 	}
131 	if (fstat(fd, &st) < 0) {
132 		warn("%s", kfile);
133 		punt();
134 	}
135 	if (st.st_size > SIZE_T_MAX)
136 		BAD;
137 
138 
139 	/*
140 	 * Map the file in its entirety.
141 	 */
142 	mappedfile = MAP_FAILED;
143 	mappedsize = st.st_size;
144 	isksyms = S_ISCHR(st.st_mode) &&
145 	    strncmp(name, _PATH_KSYMS, sizeof(_PATH_KSYMS)) == 0;
146 
147 	if (mappedsize == 0) {
148 		/* if it's a character device, stat returns size 0 */
149 		if (!isksyms)
150 			BAD;
151 	} else {
152 		mappedfile = mmap(NULL, mappedsize, PROT_READ,
153 		    MAP_PRIVATE|MAP_FILE, fd, 0);
154 	}
155 
156 	/*
157 	 * If mmap failed, try to read the file instead.
158 	 */
159 	if (mappedfile == MAP_FAILED) {
160 		int allocsiz, readsz;
161 
162 		if (isksyms != 0) {
163 			if (ioctl(fd, KIOCGSIZE, &allocsiz) < 0)
164 				BAD;
165 			mappedsize = allocsiz;
166 		} else
167 			allocsiz = mappedsize;
168 
169 		if ((mappedfile = malloc(mappedsize)) == NULL)
170 			BAD;
171 		malloced = 1;
172 		if ((readsz = read(fd, mappedfile, mappedsize)) < 0)
173 			BADUNMAP;
174 
175 		if (readsz != mappedsize) /* Sanity */
176 			BADUNMAP;
177 	}
178 	/*
179 	 * Make sure we can access the executable's header
180 	 * directly, and make sure the recognize the executable
181 	 * as an ELF binary.
182 	 */
183 	if (check(0, sizeof *ehdrp))
184 		BADUNMAP;
185 	ehdrp = (Elf_Ehdr *)&mappedfile[0];
186 
187 	if (memcmp(ehdrp->e_ident, ELFMAG, SELFMAG) != 0 ||
188 	    ehdrp->e_ident[EI_CLASS] != ELFCLASS)
189 		BADUNMAP;
190 
191 	switch (ehdrp->e_machine) {
192 	ELFDEFNNAME(MACHDEP_ID_CASES)
193 
194 	default:
195 		BADUNMAP;
196 	}
197 
198 	/*
199 	 * We've recognized it as an ELF binary.  From here
200 	 * on out, all errors are fatal.
201 	 */
202 
203 	/*
204 	 * Find the symbol list and string table.
205 	 */
206 	nshdr = ehdrp->e_shnum;
207 	shdr_off = ehdrp->e_shoff;
208 	shdr_size = ehdrp->e_shentsize * nshdr;
209 
210 	if (check(shdr_off, shdr_size) ||
211 	    (sizeof *shdrp != ehdrp->e_shentsize))
212 		badfmt("bogus section header table");
213 	shdrp = (Elf_Shdr *)&mappedfile[shdr_off];
214 
215 	for (i = 0; i < nshdr; i++) {
216 		if (shdrp[i].sh_type == SHT_SYMTAB) {
217 			symshdrp = &shdrp[i];
218 			symstrshdrp = &shdrp[shdrp[i].sh_link];
219 		}
220 	}
221 
222 	if (symshdrp == NULL)
223 		badfmt("no symbol section header found");
224 	if (symshdrp->sh_offset == 0)
225 		badfmt("stripped");
226 	if (check(symshdrp->sh_offset, symshdrp->sh_size))
227 		badfmt("bogus symbol section header");
228 	if (check(symstrshdrp->sh_offset, symstrshdrp->sh_size))
229 		badfmt("bogus symbol string section header");
230 
231 	symp = (Elf_Sym *)&mappedfile[symshdrp->sh_offset];
232 	nsyms = symshdrp->sh_size / sizeof(*symp);
233 	strtab = &mappedfile[symstrshdrp->sh_offset];
234 
235 	/*
236 	 * Set up the data item, pointing to a nlist structure.
237 	 * which we fill in for each symbol.
238 	 */
239 	data.data = (u_char *)&nbuf;
240 	data.size = sizeof(nbuf);
241 
242 	/*
243 	 * Create a buffer (to be expanded later, if necessary)
244 	 * to hold symbol names after we've added underscores
245 	 * to them.
246 	 */
247 	symnamesize = 1024;
248 	if ((symname = malloc(symnamesize)) == NULL) {
249 		warn("malloc");
250 		punt();
251 	}
252 
253 	/*
254 	 * Read each symbol and enter it into the database.
255 	 */
256 	for (i = 0; i < nsyms; i++) {
257 
258 		/*
259 		 * No symbol name; ignore this symbol.
260 		 */
261 		if (symp[i].st_name == 0)
262 			continue;
263 
264 		/*
265 		 * Find symbol name, copy it (with added underscore) to
266 		 * temporary buffer, and prepare the database key for
267 		 * insertion.
268 		 */
269 		fsymname = &strtab[symp[i].st_name];
270 		fsymnamesize = strlen(fsymname) + 1;
271 		while (symnamesize < fsymnamesize + 1) {
272 			if ((nsymname = realloc(symname, symnamesize * 2)) == NULL) {
273 				warn("malloc");
274 				punt();
275 			}
276 			symname = nsymname;
277 			symnamesize *= 2;
278 		}
279 		strlcpy(symname, "_", symnamesize);
280 		strlcat(symname, fsymname, symnamesize);
281 
282 		key.data = symname;
283 		key.size = strlen((char *)key.data);
284 
285 		/*
286 		 * Convert the symbol information into an nlist structure,
287 		 * as best we can.
288 		 */
289 		nbuf.n_value = symp[i].st_value;
290 		switch (ELFDEFNNAME(ST_TYPE)(symp[i].st_info)) {
291 		default:
292 		case STT_NOTYPE:
293 			nbuf.n_type = N_UNDF;
294 			break;
295 		case STT_OBJECT:
296 			nbuf.n_type = N_DATA;
297 			break;
298 		case STT_FUNC:
299 			nbuf.n_type = N_TEXT;
300 			break;
301 		case STT_FILE:
302 			nbuf.n_type = N_FN;
303 			break;
304 		}
305 		if (ELFDEFNNAME(ST_BIND)(symp[i].st_info) != STB_LOCAL)
306 			nbuf.n_type |= N_EXT;
307 		nbuf.n_desc = 0;				/* XXX */
308 		nbuf.n_other = 0;				/* XXX */
309 
310 		/*
311 		 * Enter the symbol into the database.
312 		 */
313 		if (db->put(db, &key, &data, 0)) {
314 			warn("record enter");
315 			punt();
316 		}
317 
318 		/*
319 		 * If it's the kernel version string, we've gotta keep
320 		 * some extra data around.  Under a separate key,
321 		 * we enter the first line (i.e. up to the first newline,
322 		 * with the newline replaced by a NUL to terminate the
323 		 * entered string) of the version string.
324 		 */
325 		if (strcmp((char *)key.data, VRS_SYM) == 0) {
326 			key.data = (u_char *)VRS_KEY;
327 			key.size = sizeof(VRS_KEY) - 1;
328 			/* Find the version string, relative to its section */
329 			if (isksyms) {
330 				/* reading from /dev/ksyms, use sysctl */
331 				size_t sz;
332 				int mib[2];
333 				char *kv;
334 
335 				mib[0] = CTL_KERN;
336 				mib[1] = KERN_VERSION;
337 				if (sysctl(mib, 2, NULL, &sz, NULL, 0) == -1) {
338 					warn("sysctl version size");
339 					punt();
340 				}
341 				if ((kv = malloc(sz)) == NULL) {
342 					warn("malloc version string");
343 					punt();
344 				}
345 				if (sysctl(mib, 2, kv, &sz, NULL, 0) == -1) {
346 					warn("sysctl version string");
347 					punt();
348 				}
349 				data.data = kv;
350 			} else
351 				data.data = strdup(&mappedfile[nbuf.n_value -
352 				    shdrp[symp[i].st_shndx].sh_addr +
353 				    shdrp[symp[i].st_shndx].sh_offset]);
354 			/* assumes newline terminates version. */
355 			if ((tmpcp = strchr(data.data, '\n')) != NULL)
356 				*tmpcp = '\0';
357 			data.size = strlen((char *)data.data);
358 
359 			if (db->put(db, &key, &data, 0)) {
360 				warn("record enter");
361 				punt();
362 			}
363 
364 			/* free pointer created by strdup(). */
365 			free(data.data);
366 
367 			/* Restore to original values */
368 			data.data = (u_char *)&nbuf;
369 			data.size = sizeof(nbuf);
370 		}
371 	}
372 
373 	rv = 0;
374 
375 unmap:
376 	if (malloced)
377 		free(mappedfile);
378 	else
379 		munmap(mappedfile, mappedsize);
380 out:
381 	return (rv);
382 }
383 
384 #endif
385