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