xref: /netbsd-src/usr.bin/mkdep/mkdep.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /* $NetBSD: mkdep.c,v 1.26 2005/12/12 22:49:37 wiz 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.26 2005/12/12 22:49:37 wiz 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 <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 
64 #include "findcc.h"
65 
66 typedef struct opt opt_t;
67 struct opt {
68 	opt_t	*left;
69 	opt_t	*right;
70 	int	len;
71 	int	count;
72 	char	name[4];
73 };
74 
75 typedef struct {
76 	int	len;
77 	char	suff[12];
78 } suff_list_t;
79 
80 /* tree of includes for -o processing */
81 opt_t *opt;
82 int width;
83 
84 #define DEFAULT_PATH		_PATH_DEFPATH
85 #define DEFAULT_FILENAME	".depend"
86 
87 static void save_for_optional(const char *, const char *);
88 static int write_optional(int, opt_t *, int);
89 
90 
91 static inline void *
92 deconst(const void *p)
93 {
94 	return (const char *)p - (const char *)0 + (char *)0;
95 }
96 
97 static void
98 usage(void)
99 {
100 	(void)fprintf(stderr,
101 	    "usage: %s [-aDdopq] [-f file] [-s suffixes] -- [flags] file ...\n",
102 	    getprogname());
103 	exit(EXIT_FAILURE);
104 }
105 
106 static int
107 run_cc(int argc, char **argv, const char **fname)
108 {
109 	const char *CC, *pathname, *tmpdir;
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 	while (((pid = wait(&status)) != cpid) && (pid >= 0))
155 		continue;
156 
157 	if (status)
158 		errx(EXIT_FAILURE, "compile failed.");
159 
160 	return tmpfd;
161 }
162 
163 static const char *
164 read_fname(void)
165 {
166 	static char *fbuf;
167 	static int fbuflen;
168 	int len, ch;
169 
170 	for (len = 0; (ch = getchar()) != EOF; len++) {
171 		if (isspace(ch)) {
172 			if (len != 0)
173 				break;
174 			len--;
175 			continue;
176 		}
177 		if (len >= fbuflen - 1) {
178 			fbuf = realloc(fbuf, fbuflen += 32);
179 			if (fbuf == NULL)
180 				err(EXIT_FAILURE, "no memory");
181 		}
182 		fbuf[len] = ch;
183 	}
184 	if (len == 0)
185 		return NULL;
186 	fbuf[len] = 0;
187 	return fbuf;
188 }
189 
190 int
191 main(int argc, char **argv)
192 {
193 	int 	aflag, dflag, oflag, qflag;
194 	const char *filename;
195 	int	dependfile;
196 	char	*buf, *lim, *ptr, *line, *suf, *colon, *eol;
197 	int	ok_ind, ch;
198 	int	sz;
199 	int	fd;
200 	const char *fname;
201 	const char *suffixes = NULL, *s;
202 	suff_list_t *suff_list = NULL, *sl;
203 
204 	suf = NULL;		/* XXXGCC -Wuninitialized [sun2] */
205 	sl = NULL;		/* XXXGCC -Wuninitialized [sun2] */
206 
207 	setlocale(LC_ALL, "");
208 	setprogname(argv[0]);
209 
210 	aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
211 	dflag = 0;
212 	oflag = 0;
213 	qflag = 0;
214 	filename = DEFAULT_FILENAME;
215 	dependfile = -1;
216 
217 	opterr = 0;	/* stop getopt() bleating about errors. */
218 	for (;;) {
219 		ok_ind = optind;
220 		ch = getopt(argc, argv, "aDdf:opqs:");
221 		switch (ch) {
222 		case -1:
223 			ok_ind = optind;
224 			break;
225 		case 'a':	/* Append to output file */
226 			aflag &= ~O_TRUNC;
227 			continue;
228 		case 'D':	/* Process *.d files (don't run cc -M) */
229 			dflag = 2;	/* Read names from stdin */
230 			opterr = 1;
231 			continue;
232 		case 'd':	/* Process *.d files (don't run cc -M) */
233 			dflag = 1;
234 			opterr = 1;
235 			continue;
236 		case 'f':	/* Name of output file */
237 			filename = optarg;
238 			continue;
239 		case 'o':	/* Mark dependant files .OPTIONAL */
240 			oflag = 1;
241 			continue;
242 		case 'p':	/* Program mode (x.o: -> x:) */
243 			suffixes = "";
244 			continue;
245 		case 'q':	/* Quiet */
246 			qflag = 1;
247 			continue;
248 		case 's':	/* Suffix list */
249 			suffixes = optarg;
250 			continue;
251 		default:
252 			if (dflag)
253 				usage();
254 			/* Unknown arguments are passed to "${CC} -M" */
255 			break;
256 		}
257 		break;
258 	}
259 
260 	argc -= ok_ind;
261 	argv += ok_ind;
262 	if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
263 		usage();
264 
265 	if (suffixes != NULL) {
266 		/* parse list once and save names and lengths */
267 		/* allocate an extra entry to mark end of list */
268 		for (sz = 1, s = suffixes; *s != 0; s++)
269 			if (*s == '.')
270 			    sz++;
271 		suff_list = calloc(sz, sizeof *suff_list);
272 		if (suff_list == NULL)
273 			err(2, "malloc");
274 		sl = suff_list;
275 		for (s = suffixes; (s = strchr(s, '.')); s += sz, sl++ ) {
276 			sz = strcspn(s, ", ");
277 			if (sz > sizeof sl->suff)
278 				errx(2, "suffix too long");
279 			sl->len = sz;
280 			memcpy(sl->suff, s, sz);
281 		}
282 	}
283 
284 	dependfile = open(filename, aflag, 0666);
285 	if (dependfile == -1)
286 		err(EXIT_FAILURE, "unable to %s to file %s\n",
287 		    aflag & O_TRUNC ? "write" : "append", filename);
288 
289 	while (dflag == 2 || *argv != NULL) {
290 		if (dflag) {
291 			if (dflag == 2) {
292 				fname = read_fname();
293 				if (fname == NULL)
294 					break;
295 			} else
296 				fname = *argv++;
297 			fd = open(fname, O_RDONLY, 0);
298 			if (fd == -1) {
299 				if (!qflag)
300 					warn("ignoring %s", fname);
301 				continue;
302 			}
303 		} else {
304 			fd = run_cc(argc, argv, &fname);
305 			/* consume all args... */
306 			argv += argc;
307 		}
308 
309 		sz = lseek(fd, 0, SEEK_END);
310 		if (sz == 0) {
311 			close(fd);
312 			continue;
313 		}
314 		buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
315 		close(fd);
316 
317 		if (buf == MAP_FAILED)
318 			err(EXIT_FAILURE, "unable to mmap file %s", fname);
319 		lim = buf + sz - 1;
320 
321 		/* Remove leading "./" from filenames */
322 		for (ptr = buf; ptr < lim; ptr++) {
323 			if (ptr[1] != '.' || ptr[2] != '/'
324 			    || !isspace((unsigned char)ptr[0]))
325 				continue;
326 			ptr[1] = ' ';
327 			ptr[2] = ' ';
328 		}
329 
330 		for (line = eol = buf; eol <= lim;) {
331 			while (eol <= lim && *eol++ != '\n')
332 				/* Find end of this line */
333 				continue;
334 			if (line == eol - 1) {
335 				/* empty line - ignore */
336 				line = eol;
337 				continue;
338 			}
339 			if (eol[-2] == '\\')
340 				/* Assemble continuation lines */
341 				continue;
342 			for (colon = line; *colon != ':'; colon++) {
343 				if (colon >= eol) {
344 					colon = NULL;
345 					break;
346 				}
347 			}
348 			if (isspace((unsigned char)*line) || colon == NULL) {
349 				/* No dependency - just transcribe line */
350 				write(dependfile, line, eol - line);
351 				line = eol;
352 				continue;
353 			}
354 			if (suff_list != NULL) {
355 				/* Find the .o: */
356 				/* First allow for any whitespace */
357 				for (suf = colon; ; suf--) {
358 					if (!isspace((unsigned char)suf[-1]))
359 						break;
360 				}
361 				/* Then look for any valid suffix */
362 				for (sl = suff_list; sl->len != 0; sl++) {
363 					if (!memcmp(suf - sl->len, sl->suff,
364 						    sl->len))
365 						break;
366 				}
367 			}
368 			if (suff_list != NULL && sl->len != 0) {
369 				suf -= sl->len;
370 				for (sl = suff_list; sl->len != 0; sl++) {
371 					if (sl != suff_list)
372 						write(dependfile, " ", 1);
373 					write(dependfile, line, suf - line);
374 					write(dependfile, sl->suff, sl->len);
375 				}
376 				write(dependfile, colon, eol - colon);
377 			} else
378 				write(dependfile, line, eol - line);
379 
380 			if (oflag)
381 				save_for_optional(colon + 1, eol);
382 			line = eol;
383 		}
384 		munmap(buf, sz);
385 	}
386 
387 	if (oflag && opt != NULL) {
388 		write(dependfile, ".OPTIONAL:", 10);
389 		width = 9;
390 		sz = write_optional(dependfile, opt, 0);
391 		/* 'depth' is about 39 for an i386 kernel */
392 		/* fprintf(stderr, "Recursion depth %d\n", sz); */
393 	}
394 	close(dependfile);
395 
396 	exit(EXIT_SUCCESS);
397 }
398 
399 
400 /*
401  * Only save each file once - the kernel .depend is 3MB and there is
402  * no point doubling its size.
403  * The data seems to be 'random enough' so the simple binary tree
404  * only has a reasonable depth.
405  */
406 static void
407 save_for_optional(const char *start, const char *limit)
408 {
409 	opt_t **l, *n;
410 	const char *name, *end;
411 	int c;
412 
413 	while (start < limit && strchr(" \t\n\\", *start))
414 		start++;
415 	for (name = start; ; name = end) {
416 		while (name < limit && strchr(" \t\n\\", *name))
417 			name++;
418 		for (end = name; end < limit && !strchr(" \t\n\\", *end);)
419 			end++;
420 		if (name >= limit)
421 			break;
422 		if (end[-1] == 'c' && end[-2] == '.' && name == start)
423 			/* ignore dependency on the files own .c */
424 			continue;
425 		for (l = &opt;;) {
426 			n = *l;
427 			if (n == NULL) {
428 				n = malloc(sizeof *n + (end - name));
429 				n->left = n->right = 0;
430 				n->len = end - name;
431 				n->count = 1;
432 				n->name[0] = ' ';
433 				memcpy(n->name + 1, name, end - name);
434 				*l = n;
435 				break;
436 			}
437 			c = (end - name) - n->len;
438 			if (c == 0)
439 				c = memcmp(n->name + 1, name, (end - name));
440 			if (c == 0) {
441 				/* Duplicate */
442 				n->count++;
443 				break;
444 			}
445 			if (c < 0)
446 				l = &n->left;
447 			else
448 				l = &n->right;
449 		}
450 	}
451 }
452 
453 static int
454 write_optional(int fd, opt_t *node, int depth)
455 {
456 	int d1 = ++depth;
457 
458 	if (node->left)
459 		d1 = write_optional(fd, node->left, d1);
460 	if (width > 76 - node->len) {
461 		write(fd, " \\\n ", 4);
462 		width = 1;
463 	}
464 	width += 1 + node->len;
465 	write(fd, node->name, 1 + node->len);
466 	if (node->right)
467 		depth = write_optional(fd, node->right, depth);
468 	return d1 > depth ? d1 : depth;
469 }
470