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