xref: /freebsd/usr.sbin/kldxref/kldxref.c (revision ce3adf4362fcca6a43e500b2531f0038adbfbd21)
1 /*
2  * Copyright (c) 2000, Boris Popov
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *    This product includes software developed by Boris Popov.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $FreeBSD$
33  */
34 
35 #include <sys/types.h>
36 #include <sys/param.h>
37 #include <sys/exec.h>
38 #include <sys/queue.h>
39 #include <sys/kernel.h>
40 #include <sys/reboot.h>
41 #include <sys/linker.h>
42 #include <sys/stat.h>
43 #include <sys/module.h>
44 #define FREEBSD_ELF
45 #include <err.h>
46 #include <fts.h>
47 #include <string.h>
48 #include <machine/elf.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 #include <errno.h>
53 
54 #include "ef.h"
55 
56 #define	MAXRECSIZE	1024
57 #define check(val)	if ((error = (val)) != 0) break
58 
59 static int dflag;	/* do not create a hint file, only write on stdout */
60 static int verbose;
61 
62 static FILE *fxref;	/* current hints file */
63 
64 static const char *xref_file = "linker.hints";
65 
66 /*
67  * A record is stored in the static buffer recbuf before going to disk.
68  */
69 static char recbuf[MAXRECSIZE];
70 static int recpos;	/* current write position */
71 static int reccnt;	/* total record written to this file so far */
72 
73 static void
74 intalign(void)
75 {
76 	recpos = (recpos + sizeof(int) - 1) & ~(sizeof(int) - 1);
77 }
78 
79 static void
80 record_start(void)
81 {
82 	recpos = 0;
83 	memset(recbuf, 0, MAXRECSIZE);
84 }
85 
86 static int
87 record_end(void)
88 {
89 	if (recpos == 0)
90 		return 0;
91 	reccnt++;
92 	intalign();
93 	fwrite(&recpos, sizeof(recpos), 1, fxref);
94 	return fwrite(recbuf, recpos, 1, fxref) != 1 ? errno : 0;
95 }
96 
97 static int
98 record_buf(const void *buf, int size)
99 {
100 	if (MAXRECSIZE - recpos < size)
101 		errx(1, "record buffer overflow");
102 	memcpy(recbuf + recpos, buf, size);
103 	recpos += size;
104 	return 0;
105 }
106 
107 /*
108  * An int is stored in host order and aligned
109  */
110 static int
111 record_int(int val)
112 {
113 	intalign();
114 	return record_buf(&val, sizeof(val));
115 }
116 
117 /*
118  * A string is stored as 1-byte length plus data, no padding
119  */
120 static int
121 record_string(const char *str)
122 {
123 	int len, error;
124 	u_char val;
125 
126 	if (dflag)
127 		return 0;
128 	val = len = strlen(str);
129 	if (len > 255)
130 		errx(1, "string %s too long", str);
131 	error = record_buf(&val, sizeof(val));
132 	if (error)
133 		return error;
134 	return record_buf(str, len);
135 }
136 
137 static int
138 parse_entry(struct mod_metadata *md, const char *cval,
139     struct elf_file *ef, const char *kldname)
140 {
141 	struct mod_depend mdp;
142 	struct mod_version mdv;
143 	Elf_Off data = (Elf_Off)md->md_data;
144 	int error = 0;
145 
146 	record_start();
147 	switch (md->md_type) {
148 	case MDT_DEPEND:
149 		if (!dflag)
150 			break;
151 		check(EF_SEG_READ(ef, data, sizeof(mdp), &mdp));
152 		printf("  depends on %s.%d (%d,%d)\n", cval,
153 		    mdp.md_ver_preferred, mdp.md_ver_minimum, mdp.md_ver_maximum);
154 		break;
155 	case MDT_VERSION:
156 		check(EF_SEG_READ(ef, data, sizeof(mdv), &mdv));
157 		if (dflag) {
158 			printf("  interface %s.%d\n", cval, mdv.mv_version);
159 		} else {
160 			record_int(MDT_VERSION);
161 			record_string(cval);
162 			record_int(mdv.mv_version);
163 			record_string(kldname);
164 		}
165 		break;
166 	case MDT_MODULE:
167 		if (dflag) {
168 			printf("  module %s\n", cval);
169 		} else {
170 			record_int(MDT_MODULE);
171 			record_string(cval);
172 			record_string(kldname);
173 		}
174 		break;
175 	default:
176 		warnx("unknown metadata record %d in file %s", md->md_type, kldname);
177 	}
178 	if (!error)
179 		record_end();
180 	return error;
181 }
182 
183 static int
184 read_kld(char *filename, char *kldname)
185 {
186 	struct mod_metadata md;
187 	struct elf_file ef;
188 	void **p, **orgp;
189 	int error, eftype, nmlen;
190 	long start, finish, entries;
191 	char kldmodname[MAXMODNAME + 1], cval[MAXMODNAME + 1], *cp;
192 
193 	if (verbose || dflag)
194 		printf("%s\n", filename);
195 	error = ef_open(filename, &ef, verbose);
196 	if (error) {
197 		error = ef_obj_open(filename, &ef, verbose);
198 		if (error) {
199 			if (verbose)
200 				warnc(error, "elf_open(%s)", filename);
201 			return error;
202 		}
203 	}
204 	eftype = EF_GET_TYPE(&ef);
205 	if (eftype != EFT_KLD && eftype != EFT_KERNEL)  {
206 		EF_CLOSE(&ef);
207 		return 0;
208 	}
209 	if (!dflag) {
210 		cp = strrchr(kldname, '.');
211 		nmlen = (cp != NULL) ? cp - kldname : (int)strlen(kldname);
212 		if (nmlen > MAXMODNAME)
213 			nmlen = MAXMODNAME;
214 		strlcpy(kldmodname, kldname, nmlen);
215 /*		fprintf(fxref, "%s:%s:%d\n", kldmodname, kldname, 0);*/
216 	}
217 	do {
218 		check(EF_LOOKUP_SET(&ef, MDT_SETNAME, &start, &finish,
219 		    &entries));
220 		check(EF_SEG_READ_ENTRY_REL(&ef, start, sizeof(*p) * entries,
221 		    (void *)&p));
222 		orgp = p;
223 		while(entries--) {
224 			check(EF_SEG_READ_REL(&ef, (Elf_Off)*p, sizeof(md),
225 			    &md));
226 			p++;
227 			check(EF_SEG_READ(&ef, (Elf_Off)md.md_cval,
228 			    sizeof(cval), cval));
229 			cval[MAXMODNAME] = '\0';
230 			parse_entry(&md, cval, &ef, kldname);
231 		}
232 		if (error)
233 			warnc(error, "error while reading %s", filename);
234 		free(orgp);
235 	} while(0);
236 	EF_CLOSE(&ef);
237 	return error;
238 }
239 
240 /*
241  * Create a temp file in directory root, make sure we don't
242  * overflow the buffer for the destination name
243  */
244 static FILE *
245 maketempfile(char *dest, const char *root)
246 {
247 	char *p;
248 	int n, fd;
249 
250 	p = strrchr(root, '/');
251 	n = p != NULL ? p - root + 1 : 0;
252 	if (snprintf(dest, MAXPATHLEN, "%.*slhint.XXXXXX", n, root) >=
253 	    MAXPATHLEN) {
254 		errno = ENAMETOOLONG;
255 		return NULL;
256 	}
257 
258 	fd = mkstemp(dest);
259 	if (fd < 0)
260 		return NULL;
261 	fchmod(fd, 0644);	/* nothing secret in the file */
262 	return fdopen(fd, "w+");
263 }
264 
265 static char xrefname[MAXPATHLEN], tempname[MAXPATHLEN];
266 
267 static void
268 usage(void)
269 {
270 
271 	fprintf(stderr, "%s\n",
272 	    "usage: kldxref [-Rdv] [-f hintsfile] path ..."
273 	);
274 	exit(1);
275 }
276 
277 int
278 main(int argc, char *argv[])
279 {
280 	FTS *ftsp;
281 	FTSENT *p;
282 	int opt, fts_options, ival;
283 	struct stat sb;
284 
285 	fts_options = FTS_PHYSICAL;
286 
287 	while ((opt = getopt(argc, argv, "Rdf:v")) != -1) {
288 		switch (opt) {
289 		case 'd':	/* no hint file, only print on stdout */
290 			dflag = 1;
291 			break;
292 		case 'f':	/* use this name instead of linker.hints */
293 			xref_file = optarg;
294 			break;
295 		case 'v':
296 			verbose++;
297 			break;
298 		case 'R':	/* recurse on directories */
299 			fts_options |= FTS_COMFOLLOW;
300 			break;
301 		default:
302 			usage();
303 			/* NOTREACHED */
304 		}
305 	}
306 	if (argc - optind < 1)
307 		usage();
308 	argc -= optind;
309 	argv += optind;
310 
311 	if (stat(argv[0], &sb) != 0)
312 		err(1, "%s", argv[0]);
313 	if ((sb.st_mode & S_IFDIR) == 0) {
314 		errno = ENOTDIR;
315 		err(1, "%s", argv[0]);
316 	}
317 
318 	ftsp = fts_open(argv, fts_options, 0);
319 	if (ftsp == NULL)
320 		exit(1);
321 
322 	for (;;) {
323 		p = fts_read(ftsp);
324 		if ((p == NULL || p->fts_info == FTS_D) && fxref) {
325 			/* close and rename the current hint file */
326 			fclose(fxref);
327 			fxref = NULL;
328 			if (reccnt) {
329 				rename(tempname, xrefname);
330 			} else {
331 				/* didn't find any entry, ignore this file */
332 				unlink(tempname);
333 				unlink(xrefname);
334 			}
335 		}
336 		if (p == NULL)
337 			break;
338 		if (p->fts_info == FTS_D && !dflag) {
339 			/* visiting a new directory, create a new hint file */
340 			snprintf(xrefname, sizeof(xrefname), "%s/%s",
341 			    ftsp->fts_path, xref_file);
342 			fxref = maketempfile(tempname, ftsp->fts_path);
343 			if (fxref == NULL)
344 				err(1, "can't create %s", tempname);
345 			ival = 1;
346 			fwrite(&ival, sizeof(ival), 1, fxref);
347 			reccnt = 0;
348 		}
349 		/* skip non-files or .symbols entries */
350 		if (p->fts_info != FTS_F)
351 			continue;
352 		if (p->fts_namelen >= 8 &&
353 		    strcmp(p->fts_name + p->fts_namelen - 8, ".symbols") == 0)
354 			continue;
355 		read_kld(p->fts_path, p->fts_name);
356 	}
357 	fts_close(ftsp);
358 	return 0;
359 }
360