mkdep.c revision 1.43
1/* $NetBSD: mkdep.c,v 1.43 2013/03/05 21:57:47 christos 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.43 2013/03/05 21:57:47 christos 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
59typedef struct opt opt_t;
60struct opt {
61	opt_t	*left;
62	opt_t	*right;
63	int	len;
64	int	count;
65	char	name[4];
66};
67
68typedef 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 */
75static opt_t *opt;
76static int width;
77static int verbose;
78
79#define DEFAULT_PATH		_PATH_DEFPATH
80#define DEFAULT_FILENAME	".depend"
81
82static void save_for_optional(const char *, const char *);
83static size_t write_optional(int, opt_t *, size_t);
84
85static inline void *
86deconst(const void *p)
87{
88	return (const char *)p - (const char *)0 + (char *)0;
89}
90
91__dead static void
92usage(void)
93{
94	(void)fprintf(stderr,
95	    "usage: %s [-aDdiopqv] [-f file] [-P prefix] [-s suffixes] "
96	    "-- [flags] file ...\n",
97	    getprogname());
98	exit(EXIT_FAILURE);
99}
100
101static int
102run_cc(int argc, char **argv, const char **fname)
103{
104	const char *CC, *tmpdir;
105	char * volatile pathname;
106	static char tmpfilename[MAXPATHLEN];
107	char **args;
108	int tmpfd;
109	pid_t pid, cpid;
110	int status;
111
112	if ((CC = getenv("CC")) == NULL)
113		CC = DEFAULT_CC;
114	if ((pathname = findcc(CC)) == NULL)
115		if (!setenv("PATH", DEFAULT_PATH, 1))
116			pathname = findcc(CC);
117	if (pathname == NULL)
118		err(EXIT_FAILURE, "%s: not found", CC);
119	if ((args = malloc((argc + 3) * sizeof(char *))) == NULL)
120		err(EXIT_FAILURE, "malloc");
121
122	args[0] = deconst(CC);
123	args[1] = deconst("-M");
124	(void)memcpy(&args[2], argv, (argc + 1) * sizeof(char *));
125
126	if ((tmpdir = getenv("TMPDIR")) == NULL)
127		tmpdir = _PATH_TMP;
128	(void)snprintf(tmpfilename, sizeof (tmpfilename), "%s/%s", tmpdir,
129	    "mkdepXXXXXX");
130	if ((tmpfd = mkstemp(tmpfilename)) < 0)
131		err(EXIT_FAILURE,  "Unable to create temporary file %s",
132		    tmpfilename);
133	(void)unlink(tmpfilename);
134	*fname = tmpfilename;
135
136	if (verbose) {
137		char **a;
138		for (a = args; *a; a++)
139			printf("%s ", *a);
140		printf("\n");
141	}
142
143	switch (cpid = vfork()) {
144	case 0:
145		(void)dup2(tmpfd, STDOUT_FILENO);
146		(void)close(tmpfd);
147
148		(void)execv(pathname, args);
149		_exit(EXIT_FAILURE);
150		/* NOTREACHED */
151
152	case -1:
153		err(EXIT_FAILURE, "unable to fork");
154	}
155
156	free(pathname);
157	free(args);
158
159	while (((pid = wait(&status)) != cpid) && (pid >= 0))
160		continue;
161
162	if (status)
163		errx(EXIT_FAILURE, "compile failed.");
164
165	return tmpfd;
166}
167
168static const char *
169read_fname(void)
170{
171	static char *fbuf;
172	static int fbuflen;
173	int len, ch;
174
175	for (len = 0; (ch = getchar()) != EOF; len++) {
176		if (isspace(ch)) {
177			if (len != 0)
178				break;
179			len--;
180			continue;
181		}
182		if (len >= fbuflen - 1) {
183			fbuf = realloc(fbuf, fbuflen += 32);
184			if (fbuf == NULL)
185				err(EXIT_FAILURE, "no memory");
186		}
187		fbuf[len] = ch;
188	}
189	if (len == 0)
190		return NULL;
191	fbuf[len] = 0;
192	return fbuf;
193}
194
195static struct option longopt[] = {
196	{ "sysroot", 1, NULL, 'R' },
197	{ NULL, 0, NULL, '\0' },
198};
199
200static void
201addsuff(suff_list_t **l, const char *s, size_t len)
202{
203	suff_list_t *p = calloc(1, sizeof(*p));
204	if (p == NULL)
205		err(1, "calloc");
206	p->suff = malloc(len + 1);
207	if (p->suff == NULL)
208		err(1, "malloc");
209	memcpy(p->suff, s, len);
210	p->suff[len] = '\0';
211	p->len = len;
212	p->next = *l;
213	*l = p;
214}
215
216int
217main(int argc, char **argv)
218{
219	int 	aflag, dflag, iflag, oflag, qflag;
220	const char *filename;
221	int	dependfile;
222	char	*buf, *lim, *ptr, *line, *suf, *colon, *eol;
223	int	ok_ind, ch;
224	size_t	sz;
225	int	fd;
226	size_t  slen;
227	const char *fname;
228	const char *prefix = NULL;
229	const char *suffixes = NULL, *s;
230	suff_list_t *suff_list = NULL, *sl;
231
232	suf = NULL;		/* XXXGCC -Wuninitialized [sun2] */
233	sl = NULL;		/* XXXGCC -Wuninitialized [sun2] */
234
235	setlocale(LC_ALL, "");
236	setprogname(argv[0]);
237
238	aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
239	dflag = 0;
240	iflag = 0;
241	oflag = 0;
242	qflag = 0;
243	filename = DEFAULT_FILENAME;
244	dependfile = -1;
245
246	opterr = 0;	/* stop getopt() bleating about errors. */
247	for (;;) {
248		ok_ind = optind;
249		ch = getopt_long(argc, argv, "aDdf:ioP:pqRs:v", longopt, NULL);
250		switch (ch) {
251		case -1:
252			ok_ind = optind;
253			break;
254		case 'a':	/* Append to output file */
255			aflag &= ~O_TRUNC;
256			continue;
257		case 'D':	/* Process *.d files (don't run cc -M) */
258			dflag = 2;	/* Read names from stdin */
259			opterr = 1;
260			continue;
261		case 'd':	/* Process *.d files (don't run cc -M) */
262			dflag = 1;
263			opterr = 1;
264			continue;
265		case 'f':	/* Name of output file */
266			filename = optarg;
267			continue;
268		case 'i':
269			iflag = 1;
270			continue;
271		case 'o':	/* Mark dependent files .OPTIONAL */
272			oflag = 1;
273			continue;
274		case 'P':	/* Prefix for each target filename */
275			prefix = optarg;
276			continue;
277		case 'p':	/* Program mode (x.o: -> x:) */
278			suffixes = "";
279			continue;
280		case 'q':	/* Quiet */
281			qflag = 1;
282			continue;
283		case 'R':
284			/* sysroot = optarg */
285			continue;
286		case 's':	/* Suffix list */
287			suffixes = optarg;
288			continue;
289		case 'v':
290			verbose = 1;
291			continue;
292		default:
293			if (dflag)
294				usage();
295			/* Unknown arguments are passed to "${CC} -M" */
296			break;
297		}
298		break;
299	}
300
301	argc -= ok_ind;
302	argv += ok_ind;
303	if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
304		usage();
305
306	if (suffixes != NULL) {
307		if (*suffixes) {
308			for (s = suffixes; (sz = strcspn(s, ", ")) != 0;) {
309				addsuff(&suff_list, s, sz);
310				s += sz;
311				while (*s && strchr(", ", *s))
312					s++;
313			}
314		} else
315			addsuff(&suff_list, "", 0);
316	}
317
318	dependfile = open(filename, aflag, 0666);
319	if (dependfile == -1)
320		goto wrerror;
321
322	while (dflag == 2 || *argv != NULL) {
323		if (dflag) {
324			if (dflag == 2) {
325				fname = read_fname();
326				if (fname == NULL)
327					break;
328			} else
329				fname = *argv++;
330			if (iflag) {
331				if (dprintf(dependfile, ".-include \"%s\"\n",
332				    fname) < 0)
333					goto wrerror;
334				continue;
335			}
336			fd = open(fname, O_RDONLY, 0);
337			if (fd == -1) {
338				if (!qflag)
339					warn("ignoring %s", fname);
340				continue;
341			}
342		} else {
343			fd = run_cc(argc, argv, &fname);
344			/* consume all args... */
345			argv += argc;
346		}
347
348		sz = lseek(fd, 0, SEEK_END);
349		if (sz == 0) {
350			close(fd);
351			continue;
352		}
353		buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
354		close(fd);
355
356		if (buf == MAP_FAILED)
357			err(EXIT_FAILURE, "unable to mmap file %s", fname);
358		lim = buf + sz - 1;
359
360		/* Remove leading "./" from filenames */
361		for (ptr = buf; ptr < lim; ptr++) {
362			if (ptr[1] != '.' || ptr[2] != '/'
363			    || !isspace((unsigned char)ptr[0]))
364				continue;
365			ptr[1] = ' ';
366			ptr[2] = ' ';
367		}
368
369		for (line = eol = buf; eol <= lim;) {
370			while (eol <= lim && *eol++ != '\n')
371				/* Find end of this line */
372				continue;
373			if (line == eol - 1) {
374				/* empty line - ignore */
375				line = eol;
376				continue;
377			}
378			if (eol[-2] == '\\')
379				/* Assemble continuation lines */
380				continue;
381			for (colon = line; *colon != ':'; colon++) {
382				if (colon >= eol) {
383					colon = NULL;
384					break;
385				}
386			}
387			if (isspace((unsigned char)*line) || colon == NULL) {
388				/* No dependency - just transcribe line */
389				if (write(dependfile, line, eol - line) < 0)
390					goto wrerror;
391				line = eol;
392				continue;
393			}
394			if (suff_list != NULL) {
395				/* Find the .o: */
396				/* First allow for any whitespace */
397				for (suf = colon; suf > buf; suf--) {
398					if (!isspace((unsigned char)suf[-1]))
399						break;
400				}
401				if (suf == buf)
402					errx(EXIT_FAILURE,
403					    "Corrupted file `%s'", fname);
404				/* Then look for any valid suffix */
405				for (sl = suff_list; sl != NULL;
406				    sl = sl->next) {
407					if (sl->len && buf <= suf - sl->len &&
408					    !memcmp(suf - sl->len, sl->suff,
409						    sl->len))
410						break;
411				}
412				/*
413				 * Not found, check for .o, since the
414				 * original file will have it.
415				 */
416				if (sl == NULL) {
417					if (memcmp(suf - 2, ".o", 2) == 0)
418						slen = 2;
419					else
420						slen = 0;
421				} else
422					slen = sl->len;
423			}
424			if (suff_list != NULL && slen != 0) {
425				suf -= slen;
426				for (sl = suff_list; sl != NULL; sl = sl->next)
427				{
428					if (sl != suff_list)
429						if (write(dependfile, " ", 1)
430						    < 0)
431							goto wrerror;
432					if (prefix != NULL)
433						if (write(dependfile, prefix,
434						    strlen(prefix)) < 0)
435							goto wrerror;
436					if (write(dependfile, line,
437					    suf - line) < 0)
438						goto wrerror;
439					if (write(dependfile, sl->suff,
440					    sl->len) < 0)
441						goto wrerror;
442				}
443				if (write(dependfile, colon, eol - colon) < 0)
444					goto wrerror;
445			} else {
446				if (prefix != NULL)
447					if (write(dependfile, prefix,
448					    strlen(prefix)) < 0)
449						goto wrerror;
450				if (write(dependfile, line, eol - line) < 0)
451					goto wrerror;
452			}
453
454			if (oflag)
455				save_for_optional(colon + 1, eol);
456			line = eol;
457		}
458		munmap(buf, sz);
459	}
460
461	if (oflag && opt != NULL) {
462		if (write(dependfile, ".OPTIONAL:", 10) < 0)
463			goto wrerror;
464		width = 9;
465		sz = write_optional(dependfile, opt, 0);
466		if (sz == (size_t)-1)
467			goto wrerror;
468		/* 'depth' is about 39 for an i386 kernel */
469		/* fprintf(stderr, "Recursion depth %d\n", sz); */
470	}
471	close(dependfile);
472
473	exit(EXIT_SUCCESS);
474wrerror:
475	err(EXIT_FAILURE, "unable to %s to file %s\n",
476	    aflag & O_TRUNC ? "write" : "append", filename);
477}
478
479
480/*
481 * Only save each file once - the kernel .depend is 3MB and there is
482 * no point doubling its size.
483 * The data seems to be 'random enough' so the simple binary tree
484 * only has a reasonable depth.
485 */
486static void
487save_for_optional(const char *start, const char *limit)
488{
489	opt_t **l, *n;
490	const char *name, *end;
491	int c;
492
493	while (start < limit && strchr(" \t\n\\", *start))
494		start++;
495	for (name = start; ; name = end) {
496		while (name < limit && strchr(" \t\n\\", *name))
497			name++;
498		for (end = name; end < limit && !strchr(" \t\n\\", *end);)
499			end++;
500		if (name >= limit)
501			break;
502		if (end[-1] == 'c' && end[-2] == '.' && name == start)
503			/* ignore dependency on the files own .c */
504			continue;
505		for (l = &opt;;) {
506			n = *l;
507			if (n == NULL) {
508				n = malloc(sizeof *n + (end - name));
509				n->left = n->right = 0;
510				n->len = end - name;
511				n->count = 1;
512				n->name[0] = ' ';
513				memcpy(n->name + 1, name, end - name);
514				*l = n;
515				break;
516			}
517			c = (end - name) - n->len;
518			if (c == 0)
519				c = memcmp(n->name + 1, name, (end - name));
520			if (c == 0) {
521				/* Duplicate */
522				n->count++;
523				break;
524			}
525			if (c < 0)
526				l = &n->left;
527			else
528				l = &n->right;
529		}
530	}
531}
532
533static size_t
534write_optional(int fd, opt_t *node, size_t depth)
535{
536	size_t d1 = ++depth;
537
538	if (node->left)
539		d1 = write_optional(fd, node->left, d1);
540	if (width > 76 - node->len) {
541		if (write(fd, " \\\n ", 4) < 0)
542			return (size_t)-1;
543		width = 1;
544	}
545	width += 1 + node->len;
546	if (write(fd, node->name, 1 + node->len) < 0)
547		return (size_t)-1;
548	if (node->right)
549		depth = write_optional(fd, node->right, depth);
550	return d1 > depth ? d1 : depth;
551}
552