xref: /netbsd-src/usr.bin/mkdep/mkdep.c (revision 274254cdae52594c1aa480a736aef78313d15c9c)
1 /* $NetBSD: mkdep.c,v 1.32 2008/07/21 14:19:24 lukem Exp $ */
2 
3 /*-
4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Matthias Scheler.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
35 
36 #include <sys/cdefs.h>
37 #if !defined(lint)
38 __COPYRIGHT("@(#) Copyright (c) 1999 The NetBSD Foundation, Inc.\
39  All rights reserved.");
40 __RCSID("$NetBSD: mkdep.c,v 1.32 2008/07/21 14:19:24 lukem Exp $");
41 #endif /* not lint */
42 
43 #include <sys/mman.h>
44 #include <sys/param.h>
45 #include <sys/wait.h>
46 #include <ctype.h>
47 #include <err.h>
48 #include <fcntl.h>
49 #include <locale.h>
50 #include <paths.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 #include "findcc.h"
57 
58 typedef struct opt opt_t;
59 struct opt {
60 	opt_t	*left;
61 	opt_t	*right;
62 	int	len;
63 	int	count;
64 	char	name[4];
65 };
66 
67 typedef struct {
68 	int	len;
69 	char	suff[12];
70 } suff_list_t;
71 
72 /* tree of includes for -o processing */
73 opt_t *opt;
74 int width;
75 
76 #define DEFAULT_PATH		_PATH_DEFPATH
77 #define DEFAULT_FILENAME	".depend"
78 
79 static void save_for_optional(const char *, const char *);
80 static int write_optional(int, opt_t *, int);
81 
82 
83 static inline void *
84 deconst(const void *p)
85 {
86 	return (const char *)p - (const char *)0 + (char *)0;
87 }
88 
89 static void
90 usage(void)
91 {
92 	(void)fprintf(stderr,
93 	    "usage: %s [-aDdopq] [-f file] [-s suffixes] -- [flags] file ...\n",
94 	    getprogname());
95 	exit(EXIT_FAILURE);
96 }
97 
98 static int
99 run_cc(int argc, char **argv, const char **fname)
100 {
101 	const char *CC, *tmpdir;
102 	char * volatile pathname;
103 	static char tmpfilename[MAXPATHLEN];
104 	char **args;
105 	int tmpfd;
106 	pid_t pid, cpid;
107 	int status;
108 
109 	if ((CC = getenv("CC")) == NULL)
110 		CC = DEFAULT_CC;
111 	if ((pathname = findcc(CC)) == NULL)
112 		if (!setenv("PATH", DEFAULT_PATH, 1))
113 			pathname = findcc(CC);
114 	if (pathname == NULL)
115 		err(EXIT_FAILURE, "%s: not found", CC);
116 	if ((args = malloc((argc + 3) * sizeof(char *))) == NULL)
117 		err(EXIT_FAILURE, "malloc");
118 
119 	args[0] = deconst(CC);
120 	args[1] = deconst("-M");
121 	(void)memcpy(&args[2], argv, (argc + 1) * sizeof(char *));
122 
123 	if ((tmpdir = getenv("TMPDIR")) == NULL)
124 		tmpdir = _PATH_TMP;
125 	(void)snprintf(tmpfilename, sizeof (tmpfilename), "%s/%s", tmpdir,
126 	    "mkdepXXXXXX");
127 	if ((tmpfd = mkstemp(tmpfilename)) < 0) {
128 		warn("unable to create temporary file %s", tmpfilename);
129 		exit(EXIT_FAILURE);
130 	}
131 	(void)unlink(tmpfilename);
132 	*fname = tmpfilename;
133 
134 	switch (cpid = vfork()) {
135 	case 0:
136 		(void)dup2(tmpfd, STDOUT_FILENO);
137 		(void)close(tmpfd);
138 
139 		(void)execv(pathname, args);
140 		_exit(EXIT_FAILURE);
141 		/* NOTREACHED */
142 
143 	case -1:
144 		err(EXIT_FAILURE, "unable to fork");
145 	}
146 
147 	free(pathname);
148 	free(args);
149 
150 	while (((pid = wait(&status)) != cpid) && (pid >= 0))
151 		continue;
152 
153 	if (status)
154 		errx(EXIT_FAILURE, "compile failed.");
155 
156 	return tmpfd;
157 }
158 
159 static const char *
160 read_fname(void)
161 {
162 	static char *fbuf;
163 	static int fbuflen;
164 	int len, ch;
165 
166 	for (len = 0; (ch = getchar()) != EOF; len++) {
167 		if (isspace(ch)) {
168 			if (len != 0)
169 				break;
170 			len--;
171 			continue;
172 		}
173 		if (len >= fbuflen - 1) {
174 			fbuf = realloc(fbuf, fbuflen += 32);
175 			if (fbuf == NULL)
176 				err(EXIT_FAILURE, "no memory");
177 		}
178 		fbuf[len] = ch;
179 	}
180 	if (len == 0)
181 		return NULL;
182 	fbuf[len] = 0;
183 	return fbuf;
184 }
185 
186 int
187 main(int argc, char **argv)
188 {
189 	int 	aflag, dflag, oflag, qflag;
190 	const char *filename;
191 	int	dependfile;
192 	char	*buf, *lim, *ptr, *line, *suf, *colon, *eol;
193 	int	ok_ind, ch;
194 	int	sz;
195 	int	fd;
196 	const char *fname;
197 	const char *suffixes = NULL, *s;
198 	suff_list_t *suff_list = NULL, *sl;
199 
200 	suf = NULL;		/* XXXGCC -Wuninitialized [sun2] */
201 	sl = NULL;		/* XXXGCC -Wuninitialized [sun2] */
202 
203 	setlocale(LC_ALL, "");
204 	setprogname(argv[0]);
205 
206 	aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
207 	dflag = 0;
208 	oflag = 0;
209 	qflag = 0;
210 	filename = DEFAULT_FILENAME;
211 	dependfile = -1;
212 
213 	opterr = 0;	/* stop getopt() bleating about errors. */
214 	for (;;) {
215 		ok_ind = optind;
216 		ch = getopt(argc, argv, "aDdf:opqs:");
217 		switch (ch) {
218 		case -1:
219 			ok_ind = optind;
220 			break;
221 		case 'a':	/* Append to output file */
222 			aflag &= ~O_TRUNC;
223 			continue;
224 		case 'D':	/* Process *.d files (don't run cc -M) */
225 			dflag = 2;	/* Read names from stdin */
226 			opterr = 1;
227 			continue;
228 		case 'd':	/* Process *.d files (don't run cc -M) */
229 			dflag = 1;
230 			opterr = 1;
231 			continue;
232 		case 'f':	/* Name of output file */
233 			filename = optarg;
234 			continue;
235 		case 'o':	/* Mark dependant files .OPTIONAL */
236 			oflag = 1;
237 			continue;
238 		case 'p':	/* Program mode (x.o: -> x:) */
239 			suffixes = "";
240 			continue;
241 		case 'q':	/* Quiet */
242 			qflag = 1;
243 			continue;
244 		case 's':	/* Suffix list */
245 			suffixes = optarg;
246 			continue;
247 		default:
248 			if (dflag)
249 				usage();
250 			/* Unknown arguments are passed to "${CC} -M" */
251 			break;
252 		}
253 		break;
254 	}
255 
256 	argc -= ok_ind;
257 	argv += ok_ind;
258 	if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
259 		usage();
260 
261 	if (suffixes != NULL) {
262 		/* parse list once and save names and lengths */
263 		/* allocate an extra entry to mark end of list */
264 		for (sz = 1, s = suffixes; *s != 0; s++)
265 			if (*s == '.')
266 			    sz++;
267 		suff_list = calloc(sz, sizeof *suff_list);
268 		if (suff_list == NULL)
269 			err(2, "malloc");
270 		sl = suff_list;
271 		for (s = suffixes; (s = strchr(s, '.')); s += sz, sl++ ) {
272 			sz = strcspn(s, ", ");
273 			if (sz > sizeof sl->suff)
274 				errx(2, "suffix too long");
275 			sl->len = sz;
276 			memcpy(sl->suff, s, sz);
277 		}
278 	}
279 
280 	dependfile = open(filename, aflag, 0666);
281 	if (dependfile == -1)
282 		err(EXIT_FAILURE, "unable to %s to file %s\n",
283 		    aflag & O_TRUNC ? "write" : "append", filename);
284 
285 	while (dflag == 2 || *argv != NULL) {
286 		if (dflag) {
287 			if (dflag == 2) {
288 				fname = read_fname();
289 				if (fname == NULL)
290 					break;
291 			} else
292 				fname = *argv++;
293 			fd = open(fname, O_RDONLY, 0);
294 			if (fd == -1) {
295 				if (!qflag)
296 					warn("ignoring %s", fname);
297 				continue;
298 			}
299 		} else {
300 			fd = run_cc(argc, argv, &fname);
301 			/* consume all args... */
302 			argv += argc;
303 		}
304 
305 		sz = lseek(fd, 0, SEEK_END);
306 		if (sz == 0) {
307 			close(fd);
308 			continue;
309 		}
310 		buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
311 		close(fd);
312 
313 		if (buf == MAP_FAILED)
314 			err(EXIT_FAILURE, "unable to mmap file %s", fname);
315 		lim = buf + sz - 1;
316 
317 		/* Remove leading "./" from filenames */
318 		for (ptr = buf; ptr < lim; ptr++) {
319 			if (ptr[1] != '.' || ptr[2] != '/'
320 			    || !isspace((unsigned char)ptr[0]))
321 				continue;
322 			ptr[1] = ' ';
323 			ptr[2] = ' ';
324 		}
325 
326 		for (line = eol = buf; eol <= lim;) {
327 			while (eol <= lim && *eol++ != '\n')
328 				/* Find end of this line */
329 				continue;
330 			if (line == eol - 1) {
331 				/* empty line - ignore */
332 				line = eol;
333 				continue;
334 			}
335 			if (eol[-2] == '\\')
336 				/* Assemble continuation lines */
337 				continue;
338 			for (colon = line; *colon != ':'; colon++) {
339 				if (colon >= eol) {
340 					colon = NULL;
341 					break;
342 				}
343 			}
344 			if (isspace((unsigned char)*line) || colon == NULL) {
345 				/* No dependency - just transcribe line */
346 				write(dependfile, line, eol - line);
347 				line = eol;
348 				continue;
349 			}
350 			if (suff_list != NULL) {
351 				/* Find the .o: */
352 				/* First allow for any whitespace */
353 				for (suf = colon; suf > buf; suf--) {
354 					if (!isspace((unsigned char)suf[-1]))
355 						break;
356 				}
357 				if (suf == buf)
358 					errx(EXIT_FAILURE,
359 					    "Corrupted file `%s'", fname);
360 				/* Then look for any valid suffix */
361 				for (sl = suff_list; sl->len != 0; sl++) {
362 					if (!memcmp(suf - sl->len, sl->suff,
363 						    sl->len))
364 						break;
365 				}
366 			}
367 			if (suff_list != NULL && sl->len != 0) {
368 				suf -= sl->len;
369 				for (sl = suff_list; sl->len != 0; sl++) {
370 					if (sl != suff_list)
371 						write(dependfile, " ", 1);
372 					write(dependfile, line, suf - line);
373 					write(dependfile, sl->suff, sl->len);
374 				}
375 				write(dependfile, colon, eol - colon);
376 			} else
377 				write(dependfile, line, eol - line);
378 
379 			if (oflag)
380 				save_for_optional(colon + 1, eol);
381 			line = eol;
382 		}
383 		munmap(buf, sz);
384 	}
385 
386 	if (oflag && opt != NULL) {
387 		write(dependfile, ".OPTIONAL:", 10);
388 		width = 9;
389 		sz = write_optional(dependfile, opt, 0);
390 		/* 'depth' is about 39 for an i386 kernel */
391 		/* fprintf(stderr, "Recursion depth %d\n", sz); */
392 	}
393 	close(dependfile);
394 
395 	exit(EXIT_SUCCESS);
396 }
397 
398 
399 /*
400  * Only save each file once - the kernel .depend is 3MB and there is
401  * no point doubling its size.
402  * The data seems to be 'random enough' so the simple binary tree
403  * only has a reasonable depth.
404  */
405 static void
406 save_for_optional(const char *start, const char *limit)
407 {
408 	opt_t **l, *n;
409 	const char *name, *end;
410 	int c;
411 
412 	while (start < limit && strchr(" \t\n\\", *start))
413 		start++;
414 	for (name = start; ; name = end) {
415 		while (name < limit && strchr(" \t\n\\", *name))
416 			name++;
417 		for (end = name; end < limit && !strchr(" \t\n\\", *end);)
418 			end++;
419 		if (name >= limit)
420 			break;
421 		if (end[-1] == 'c' && end[-2] == '.' && name == start)
422 			/* ignore dependency on the files own .c */
423 			continue;
424 		for (l = &opt;;) {
425 			n = *l;
426 			if (n == NULL) {
427 				n = malloc(sizeof *n + (end - name));
428 				n->left = n->right = 0;
429 				n->len = end - name;
430 				n->count = 1;
431 				n->name[0] = ' ';
432 				memcpy(n->name + 1, name, end - name);
433 				*l = n;
434 				break;
435 			}
436 			c = (end - name) - n->len;
437 			if (c == 0)
438 				c = memcmp(n->name + 1, name, (end - name));
439 			if (c == 0) {
440 				/* Duplicate */
441 				n->count++;
442 				break;
443 			}
444 			if (c < 0)
445 				l = &n->left;
446 			else
447 				l = &n->right;
448 		}
449 	}
450 }
451 
452 static int
453 write_optional(int fd, opt_t *node, int depth)
454 {
455 	int d1 = ++depth;
456 
457 	if (node->left)
458 		d1 = write_optional(fd, node->left, d1);
459 	if (width > 76 - node->len) {
460 		write(fd, " \\\n ", 4);
461 		width = 1;
462 	}
463 	width += 1 + node->len;
464 	write(fd, node->name, 1 + node->len);
465 	if (node->right)
466 		depth = write_optional(fd, node->right, depth);
467 	return d1 > depth ? d1 : depth;
468 }
469