xref: /minix3/usr.bin/mkdep/mkdep.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /* $NetBSD: mkdep.c,v 1.44 2015/06/16 22:54:10 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.44 2015/06/16 22:54:10 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 
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 static int verbose;
78 
79 #define DEFAULT_PATH		_PATH_DEFPATH
80 #define DEFAULT_FILENAME	".depend"
81 
82 static void save_for_optional(const char *, const char *);
83 static size_t write_optional(int, opt_t *, size_t);
84 
85 static inline void *
deconst(const void * p)86 deconst(const void *p)
87 {
88 	return (const char *)p - (const char *)0 + (char *)0;
89 }
90 
91 __dead static void
usage(void)92 usage(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 
101 static int
run_cc(int argc,char ** argv,const char ** fname)102 run_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 
168 static const char *
read_fname(void)169 read_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 
195 static struct option longopt[] = {
196 	{ "sysroot", 1, NULL, 'R' },
197 	{ NULL, 0, NULL, '\0' },
198 };
199 
200 static void
addsuff(suff_list_t ** l,const char * s,size_t len)201 addsuff(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 
216 int
main(int argc,char ** argv)217 main(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 #if !defined(__minix)
232 	size_t nr;
233 #else
234 	/* triggers a 'may be used uninitialized', when compiled with gcc,
235 	 * asserts off, and -Os. */
236 	slen = 0;
237 #endif /* !defined(__minix) */
238 
239 	suf = NULL;		/* XXXGCC -Wuninitialized [sun2] */
240 	sl = NULL;		/* XXXGCC -Wuninitialized [sun2] */
241 
242 	setlocale(LC_ALL, "");
243 	setprogname(argv[0]);
244 
245 	aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
246 	dflag = 0;
247 	iflag = 0;
248 	oflag = 0;
249 	qflag = 0;
250 	filename = DEFAULT_FILENAME;
251 	dependfile = -1;
252 
253 	opterr = 0;	/* stop getopt() bleating about errors. */
254 	for (;;) {
255 		ok_ind = optind;
256 		ch = getopt_long(argc, argv, "aDdf:ioP:pqRs:v", longopt, NULL);
257 		switch (ch) {
258 		case -1:
259 			ok_ind = optind;
260 			break;
261 		case 'a':	/* Append to output file */
262 			aflag &= ~O_TRUNC;
263 			continue;
264 		case 'D':	/* Process *.d files (don't run cc -M) */
265 			dflag = 2;	/* Read names from stdin */
266 			opterr = 1;
267 			continue;
268 		case 'd':	/* Process *.d files (don't run cc -M) */
269 			dflag = 1;
270 			opterr = 1;
271 			continue;
272 		case 'f':	/* Name of output file */
273 			filename = optarg;
274 			continue;
275 		case 'i':
276 			iflag = 1;
277 			continue;
278 		case 'o':	/* Mark dependent files .OPTIONAL */
279 			oflag = 1;
280 			continue;
281 		case 'P':	/* Prefix for each target filename */
282 			prefix = optarg;
283 			continue;
284 		case 'p':	/* Program mode (x.o: -> x:) */
285 			suffixes = "";
286 			continue;
287 		case 'q':	/* Quiet */
288 			qflag = 1;
289 			continue;
290 		case 'R':
291 			/* sysroot = optarg */
292 			continue;
293 		case 's':	/* Suffix list */
294 			suffixes = optarg;
295 			continue;
296 		case 'v':
297 			verbose = 1;
298 			continue;
299 		default:
300 			if (dflag)
301 				usage();
302 			/* Unknown arguments are passed to "${CC} -M" */
303 			break;
304 		}
305 		break;
306 	}
307 
308 	argc -= ok_ind;
309 	argv += ok_ind;
310 	if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
311 		usage();
312 
313 	if (suffixes != NULL) {
314 		if (*suffixes) {
315 			for (s = suffixes; (sz = strcspn(s, ", ")) != 0;) {
316 				addsuff(&suff_list, s, sz);
317 				s += sz;
318 				while (*s && strchr(", ", *s))
319 					s++;
320 			}
321 		} else
322 			addsuff(&suff_list, "", 0);
323 	}
324 
325 	dependfile = open(filename, aflag, 0666);
326 	if (dependfile == -1)
327 		goto wrerror;
328 
329 	while (dflag == 2 || *argv != NULL) {
330 		if (dflag) {
331 			if (dflag == 2) {
332 				fname = read_fname();
333 				if (fname == NULL)
334 					break;
335 			} else
336 				fname = *argv++;
337 			if (iflag) {
338 				if (dprintf(dependfile, ".-include \"%s\"\n",
339 				    fname) < 0)
340 					goto wrerror;
341 				continue;
342 			}
343 			fd = open(fname, O_RDONLY, 0);
344 			if (fd == -1) {
345 				if (!qflag)
346 					warn("ignoring %s", fname);
347 				continue;
348 			}
349 		} else {
350 			fd = run_cc(argc, argv, &fname);
351 			/* consume all args... */
352 			argv += argc;
353 		}
354 
355 		sz = lseek(fd, 0, SEEK_END);
356 		if (sz == 0) {
357 			close(fd);
358 			continue;
359 		}
360 		buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
361 		close(fd);
362 
363 		if (buf == MAP_FAILED)
364 			err(EXIT_FAILURE, "unable to mmap file %s", fname);
365 		lim = buf + sz - 1;
366 
367 		/* Remove leading "./" from filenames */
368 		for (ptr = buf; ptr < lim; ptr++) {
369 			if (ptr[1] != '.' || ptr[2] != '/'
370 			    || !isspace((unsigned char)ptr[0]))
371 				continue;
372 			ptr[1] = ' ';
373 			ptr[2] = ' ';
374 		}
375 
376 		for (line = eol = buf; eol <= lim;) {
377 			while (eol <= lim && *eol++ != '\n')
378 				/* Find end of this line */
379 				continue;
380 			if (line == eol - 1) {
381 				/* empty line - ignore */
382 				line = eol;
383 				continue;
384 			}
385 			if (eol[-2] == '\\')
386 				/* Assemble continuation lines */
387 				continue;
388 			for (colon = line; *colon != ':'; colon++) {
389 				if (colon >= eol) {
390 					colon = NULL;
391 					break;
392 				}
393 			}
394 			if (isspace((unsigned char)*line) || colon == NULL) {
395 				/* No dependency - just transcribe line */
396 				if (write(dependfile, line, eol - line) < 0)
397 					goto wrerror;
398 				line = eol;
399 				continue;
400 			}
401 			if (suff_list != NULL) {
402 				/* Find the .o: */
403 				/* First allow for any whitespace */
404 				for (suf = colon; suf > buf; suf--) {
405 					if (!isspace((unsigned char)suf[-1]))
406 						break;
407 				}
408 				if (suf == buf)
409 					errx(EXIT_FAILURE,
410 					    "Corrupted file `%s'", fname);
411 				/* Then look for any valid suffix */
412 				for (sl = suff_list; sl != NULL;
413 				    sl = sl->next) {
414 					if (sl->len && buf <= suf - sl->len &&
415 					    !memcmp(suf - sl->len, sl->suff,
416 						    sl->len))
417 						break;
418 				}
419 				/*
420 				 * Not found, check for .o, since the
421 				 * original file will have it.
422 				 */
423 				if (sl == NULL) {
424 					if (memcmp(suf - 2, ".o", 2) == 0)
425 						slen = 2;
426 					else
427 						slen = 0;
428 				} else
429 					slen = sl->len;
430 			}
431 			if (suff_list != NULL && slen != 0) {
432 				suf -= slen;
433 				for (sl = suff_list; sl != NULL; sl = sl->next)
434 				{
435 					if (sl != suff_list)
436 						if (write(dependfile, " ", 1)
437 						    < 0)
438 							goto wrerror;
439 					if (prefix != NULL)
440 						if (write(dependfile, prefix,
441 						    strlen(prefix)) < 0)
442 							goto wrerror;
443 					if (write(dependfile, line,
444 					    suf - line) < 0)
445 						goto wrerror;
446 					if (write(dependfile, sl->suff,
447 					    sl->len) < 0)
448 						goto wrerror;
449 				}
450 				if (write(dependfile, colon, eol - colon) < 0)
451 					goto wrerror;
452 			} else {
453 				if (prefix != NULL)
454 					if (write(dependfile, prefix,
455 					    strlen(prefix)) < 0)
456 						goto wrerror;
457 				if (write(dependfile, line, eol - line) < 0)
458 					goto wrerror;
459 			}
460 
461 			if (oflag)
462 				save_for_optional(colon + 1, eol);
463 			line = eol;
464 		}
465 		munmap(buf, sz);
466 	}
467 
468 	if (oflag && opt != NULL) {
469 		if (write(dependfile, ".OPTIONAL:", 10) < 0)
470 			goto wrerror;
471 		width = 9;
472 		sz = write_optional(dependfile, opt, 0);
473 		if (sz == (size_t)-1)
474 			goto wrerror;
475 		/* 'depth' is about 39 for an i386 kernel */
476 		/* fprintf(stderr, "Recursion depth %d\n", sz); */
477 	}
478 	close(dependfile);
479 
480 	exit(EXIT_SUCCESS);
481 wrerror:
482 	err(EXIT_FAILURE, "unable to %s to file %s",
483 	    aflag & O_TRUNC ? "write" : "append", filename);
484 }
485 
486 
487 /*
488  * Only save each file once - the kernel .depend is 3MB and there is
489  * no point doubling its size.
490  * The data seems to be 'random enough' so the simple binary tree
491  * only has a reasonable depth.
492  */
493 static void
save_for_optional(const char * start,const char * limit)494 save_for_optional(const char *start, const char *limit)
495 {
496 	opt_t **l, *n;
497 	const char *name, *end;
498 	int c;
499 
500 	while (start < limit && strchr(" \t\n\\", *start))
501 		start++;
502 	for (name = start; ; name = end) {
503 		while (name < limit && strchr(" \t\n\\", *name))
504 			name++;
505 		for (end = name; end < limit && !strchr(" \t\n\\", *end);)
506 			end++;
507 		if (name >= limit)
508 			break;
509 		if (end[-1] == 'c' && end[-2] == '.' && name == start)
510 			/* ignore dependency on the files own .c */
511 			continue;
512 		for (l = &opt;;) {
513 			n = *l;
514 			if (n == NULL) {
515 				n = malloc(sizeof *n + (end - name));
516 				n->left = n->right = 0;
517 				n->len = end - name;
518 				n->count = 1;
519 				n->name[0] = ' ';
520 				memcpy(n->name + 1, name, end - name);
521 				*l = n;
522 				break;
523 			}
524 			c = (end - name) - n->len;
525 			if (c == 0)
526 				c = memcmp(n->name + 1, name, (end - name));
527 			if (c == 0) {
528 				/* Duplicate */
529 				n->count++;
530 				break;
531 			}
532 			if (c < 0)
533 				l = &n->left;
534 			else
535 				l = &n->right;
536 		}
537 	}
538 }
539 
540 static size_t
write_optional(int fd,opt_t * node,size_t depth)541 write_optional(int fd, opt_t *node, size_t depth)
542 {
543 	size_t d1 = ++depth;
544 
545 	if (node->left)
546 		d1 = write_optional(fd, node->left, d1);
547 	if (width > 76 - node->len) {
548 		if (write(fd, " \\\n ", 4) < 0)
549 			return (size_t)-1;
550 		width = 1;
551 	}
552 	width += 1 + node->len;
553 	if (write(fd, node->name, 1 + node->len) < 0)
554 		return (size_t)-1;
555 	if (node->right)
556 		depth = write_optional(fd, node->right, depth);
557 	return d1 > depth ? d1 : depth;
558 }
559