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