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