xref: /netbsd-src/usr.bin/mkdep/mkdep.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /* $NetBSD: mkdep.c,v 1.40 2011/09/04 20:30:06 joerg 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.40 2011/09/04 20:30:06 joerg 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 <getopt.h>
50 #include <locale.h>
51 #include <paths.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include "findcc.h"
58 
59 typedef struct opt opt_t;
60 struct opt {
61 	opt_t	*left;
62 	opt_t	*right;
63 	int	len;
64 	int	count;
65 	char	name[4];
66 };
67 
68 typedef struct suff_list {
69 	size_t	len;
70 	char	*suff;
71 	struct suff_list *next;
72 } suff_list_t;
73 
74 /* tree of includes for -o processing */
75 static opt_t *opt;
76 static int width;
77 
78 #define DEFAULT_PATH		_PATH_DEFPATH
79 #define DEFAULT_FILENAME	".depend"
80 
81 static void save_for_optional(const char *, const char *);
82 static int write_optional(int, opt_t *, int);
83 
84 static inline void *
85 deconst(const void *p)
86 {
87 	return (const char *)p - (const char *)0 + (char *)0;
88 }
89 
90 __dead static void
91 usage(void)
92 {
93 	(void)fprintf(stderr,
94 	    "usage: %s [-aDdopq] [-f file] [-s suffixes] -- [flags] file ...\n",
95 	    getprogname());
96 	exit(EXIT_FAILURE);
97 }
98 
99 static int
100 run_cc(int argc, char **argv, const char **fname)
101 {
102 	const char *CC, *tmpdir;
103 	char * volatile pathname;
104 	static char tmpfilename[MAXPATHLEN];
105 	char **args;
106 	int tmpfd;
107 	pid_t pid, cpid;
108 	int status;
109 
110 	if ((CC = getenv("CC")) == NULL)
111 		CC = DEFAULT_CC;
112 	if ((pathname = findcc(CC)) == NULL)
113 		if (!setenv("PATH", DEFAULT_PATH, 1))
114 			pathname = findcc(CC);
115 	if (pathname == NULL)
116 		err(EXIT_FAILURE, "%s: not found", CC);
117 	if ((args = malloc((argc + 3) * sizeof(char *))) == NULL)
118 		err(EXIT_FAILURE, "malloc");
119 
120 	args[0] = deconst(CC);
121 	args[1] = deconst("-M");
122 	(void)memcpy(&args[2], argv, (argc + 1) * sizeof(char *));
123 
124 	if ((tmpdir = getenv("TMPDIR")) == NULL)
125 		tmpdir = _PATH_TMP;
126 	(void)snprintf(tmpfilename, sizeof (tmpfilename), "%s/%s", tmpdir,
127 	    "mkdepXXXXXX");
128 	if ((tmpfd = mkstemp(tmpfilename)) < 0)
129 		err(EXIT_FAILURE,  "Unable to create temporary file %s",
130 		    tmpfilename);
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 static struct option longopt[] = {
187 	{ "sysroot", 1, NULL, 'R' },
188 	{ NULL, 0, NULL, '\0' },
189 };
190 
191 static void
192 addsuff(suff_list_t **l, const char *s, size_t len)
193 {
194 	suff_list_t *p = calloc(1, sizeof(*p));
195 	if (p == NULL)
196 		err(1, "calloc");
197 	p->suff = malloc(len + 1);
198 	if (p->suff == NULL)
199 		err(1, "malloc");
200 	memcpy(p->suff, s, len);
201 	p->suff[len] = '\0';
202 	p->len = len;
203 	p->next = *l;
204 	*l = p;
205 }
206 
207 int
208 main(int argc, char **argv)
209 {
210 	int 	aflag, dflag, oflag, qflag;
211 	const char *filename;
212 	int	dependfile;
213 	char	*buf, *lim, *ptr, *line, *suf, *colon, *eol;
214 	int	ok_ind, ch;
215 	size_t	sz;
216 	int	fd;
217 	size_t  slen;
218 	const char *fname;
219 	const char *suffixes = NULL, *s;
220 	suff_list_t *suff_list = NULL, *sl;
221 
222 	suf = NULL;		/* XXXGCC -Wuninitialized [sun2] */
223 	sl = NULL;		/* XXXGCC -Wuninitialized [sun2] */
224 
225 	setlocale(LC_ALL, "");
226 	setprogname(argv[0]);
227 
228 	aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
229 	dflag = 0;
230 	oflag = 0;
231 	qflag = 0;
232 	filename = DEFAULT_FILENAME;
233 	dependfile = -1;
234 
235 	opterr = 0;	/* stop getopt() bleating about errors. */
236 	for (;;) {
237 		ok_ind = optind;
238 		ch = getopt_long(argc, argv, "aDdf:opqRs:", longopt, NULL);
239 		switch (ch) {
240 		case -1:
241 			ok_ind = optind;
242 			break;
243 		case 'a':	/* Append to output file */
244 			aflag &= ~O_TRUNC;
245 			continue;
246 		case 'D':	/* Process *.d files (don't run cc -M) */
247 			dflag = 2;	/* Read names from stdin */
248 			opterr = 1;
249 			continue;
250 		case 'd':	/* Process *.d files (don't run cc -M) */
251 			dflag = 1;
252 			opterr = 1;
253 			continue;
254 		case 'f':	/* Name of output file */
255 			filename = optarg;
256 			continue;
257 		case 'o':	/* Mark dependent files .OPTIONAL */
258 			oflag = 1;
259 			continue;
260 		case 'p':	/* Program mode (x.o: -> x:) */
261 			suffixes = "";
262 			continue;
263 		case 'q':	/* Quiet */
264 			qflag = 1;
265 			continue;
266 		case 'R':
267 			/* sysroot = optarg */
268 			continue;
269 		case 's':	/* Suffix list */
270 			suffixes = optarg;
271 			continue;
272 		default:
273 			if (dflag)
274 				usage();
275 			/* Unknown arguments are passed to "${CC} -M" */
276 			break;
277 		}
278 		break;
279 	}
280 
281 	argc -= ok_ind;
282 	argv += ok_ind;
283 	if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
284 		usage();
285 
286 	if (suffixes != NULL) {
287 		if (*suffixes) {
288 			for (s = suffixes; (sz = strcspn(s, ", ")) != 0;) {
289 				addsuff(&suff_list, s, sz);
290 				s += sz;
291 				while (*s && strchr(", ", *s))
292 					s++;
293 			}
294 		} else
295 			addsuff(&suff_list, "", 0);
296 	}
297 
298 	dependfile = open(filename, aflag, 0666);
299 	if (dependfile == -1)
300 		err(EXIT_FAILURE, "unable to %s to file %s\n",
301 		    aflag & O_TRUNC ? "write" : "append", filename);
302 
303 	while (dflag == 2 || *argv != NULL) {
304 		if (dflag) {
305 			if (dflag == 2) {
306 				fname = read_fname();
307 				if (fname == NULL)
308 					break;
309 			} else
310 				fname = *argv++;
311 			fd = open(fname, O_RDONLY, 0);
312 			if (fd == -1) {
313 				if (!qflag)
314 					warn("ignoring %s", fname);
315 				continue;
316 			}
317 		} else {
318 			fd = run_cc(argc, argv, &fname);
319 			/* consume all args... */
320 			argv += argc;
321 		}
322 
323 		sz = lseek(fd, 0, SEEK_END);
324 		if (sz == 0) {
325 			close(fd);
326 			continue;
327 		}
328 		buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
329 		close(fd);
330 
331 		if (buf == MAP_FAILED)
332 			err(EXIT_FAILURE, "unable to mmap file %s", fname);
333 		lim = buf + sz - 1;
334 
335 		/* Remove leading "./" from filenames */
336 		for (ptr = buf; ptr < lim; ptr++) {
337 			if (ptr[1] != '.' || ptr[2] != '/'
338 			    || !isspace((unsigned char)ptr[0]))
339 				continue;
340 			ptr[1] = ' ';
341 			ptr[2] = ' ';
342 		}
343 
344 		for (line = eol = buf; eol <= lim;) {
345 			while (eol <= lim && *eol++ != '\n')
346 				/* Find end of this line */
347 				continue;
348 			if (line == eol - 1) {
349 				/* empty line - ignore */
350 				line = eol;
351 				continue;
352 			}
353 			if (eol[-2] == '\\')
354 				/* Assemble continuation lines */
355 				continue;
356 			for (colon = line; *colon != ':'; colon++) {
357 				if (colon >= eol) {
358 					colon = NULL;
359 					break;
360 				}
361 			}
362 			if (isspace((unsigned char)*line) || colon == NULL) {
363 				/* No dependency - just transcribe line */
364 				write(dependfile, line, eol - line);
365 				line = eol;
366 				continue;
367 			}
368 			if (suff_list != NULL) {
369 				/* Find the .o: */
370 				/* First allow for any whitespace */
371 				for (suf = colon; suf > buf; suf--) {
372 					if (!isspace((unsigned char)suf[-1]))
373 						break;
374 				}
375 				if (suf == buf)
376 					errx(EXIT_FAILURE,
377 					    "Corrupted file `%s'", fname);
378 				/* Then look for any valid suffix */
379 				for (sl = suff_list; sl != NULL;
380 				    sl = sl->next) {
381 					if (sl->len && buf <= suf - sl->len &&
382 					    !memcmp(suf - sl->len, sl->suff,
383 						    sl->len))
384 						break;
385 				}
386 				/*
387 				 * Not found, check for .o, since the
388 				 * original file will have it.
389 				 */
390 				if (sl == NULL) {
391 					if (memcmp(suf - 2, ".o", 2) == 0)
392 						slen = 2;
393 					else
394 						slen = 0;
395 				} else
396 					slen = sl->len;
397 			}
398 			if (suff_list != NULL && slen != 0) {
399 				suf -= slen;
400 				for (sl = suff_list; sl != NULL; sl = sl->next)
401 				{
402 					if (sl != suff_list)
403 						write(dependfile, " ", 1);
404 					write(dependfile, line, suf - line);
405 					write(dependfile, sl->suff, sl->len);
406 				}
407 				write(dependfile, colon, eol - colon);
408 			} else
409 				write(dependfile, line, eol - line);
410 
411 			if (oflag)
412 				save_for_optional(colon + 1, eol);
413 			line = eol;
414 		}
415 		munmap(buf, sz);
416 	}
417 
418 	if (oflag && opt != NULL) {
419 		write(dependfile, ".OPTIONAL:", 10);
420 		width = 9;
421 		sz = write_optional(dependfile, opt, 0);
422 		/* 'depth' is about 39 for an i386 kernel */
423 		/* fprintf(stderr, "Recursion depth %d\n", sz); */
424 	}
425 	close(dependfile);
426 
427 	exit(EXIT_SUCCESS);
428 }
429 
430 
431 /*
432  * Only save each file once - the kernel .depend is 3MB and there is
433  * no point doubling its size.
434  * The data seems to be 'random enough' so the simple binary tree
435  * only has a reasonable depth.
436  */
437 static void
438 save_for_optional(const char *start, const char *limit)
439 {
440 	opt_t **l, *n;
441 	const char *name, *end;
442 	int c;
443 
444 	while (start < limit && strchr(" \t\n\\", *start))
445 		start++;
446 	for (name = start; ; name = end) {
447 		while (name < limit && strchr(" \t\n\\", *name))
448 			name++;
449 		for (end = name; end < limit && !strchr(" \t\n\\", *end);)
450 			end++;
451 		if (name >= limit)
452 			break;
453 		if (end[-1] == 'c' && end[-2] == '.' && name == start)
454 			/* ignore dependency on the files own .c */
455 			continue;
456 		for (l = &opt;;) {
457 			n = *l;
458 			if (n == NULL) {
459 				n = malloc(sizeof *n + (end - name));
460 				n->left = n->right = 0;
461 				n->len = end - name;
462 				n->count = 1;
463 				n->name[0] = ' ';
464 				memcpy(n->name + 1, name, end - name);
465 				*l = n;
466 				break;
467 			}
468 			c = (end - name) - n->len;
469 			if (c == 0)
470 				c = memcmp(n->name + 1, name, (end - name));
471 			if (c == 0) {
472 				/* Duplicate */
473 				n->count++;
474 				break;
475 			}
476 			if (c < 0)
477 				l = &n->left;
478 			else
479 				l = &n->right;
480 		}
481 	}
482 }
483 
484 static int
485 write_optional(int fd, opt_t *node, int depth)
486 {
487 	int d1 = ++depth;
488 
489 	if (node->left)
490 		d1 = write_optional(fd, node->left, d1);
491 	if (width > 76 - node->len) {
492 		write(fd, " \\\n ", 4);
493 		width = 1;
494 	}
495 	width += 1 + node->len;
496 	write(fd, node->name, 1 + node->len);
497 	if (node->right)
498 		depth = write_optional(fd, node->right, depth);
499 	return d1 > depth ? d1 : depth;
500 }
501