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