worldstone: add -s for statistical profiling
[minix.git] / usr.bin / mkdep / mkdep.c
blobc7c88da2cc49f54fb22844ac493f09dbd51f8177
1 /* $NetBSD: mkdep.c,v 1.35 2010/05/26 18:07:34 christos Exp $ */
3 /*-
4 * Copyright (c) 1999 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Matthias Scheler.
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.
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.
32 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
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.35 2010/05/26 18:07:34 christos Exp $");
41 #endif /* not lint */
43 #ifndef __minix
44 #include <sys/mman.h>
45 #endif
46 #include <sys/param.h>
47 #include <sys/wait.h>
48 #include <ctype.h>
49 #include <err.h>
50 #include <fcntl.h>
51 #include <locale.h>
52 #include <paths.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
58 #include "findcc.h"
60 typedef struct opt opt_t;
61 struct opt {
62 opt_t *left;
63 opt_t *right;
64 int len;
65 int count;
66 char name[4];
69 typedef struct {
70 size_t len;
71 char suff[12];
72 } suff_list_t;
74 /* tree of includes for -o processing */
75 opt_t *opt;
76 int width;
78 #define DEFAULT_PATH _PATH_DEFPATH
79 #define DEFAULT_FILENAME ".depend"
81 static void save_for_optional(const char *, const char *);
82 static int write_optional(int, opt_t *, int);
85 static inline void *
86 deconst(const void *p)
88 return (const char *)p - (const char *)0 + (char *)0;
91 static void
92 usage(void)
94 (void)fprintf(stderr,
95 "usage: %s [-aDdopq] [-f file] [-s suffixes] -- [flags] file ...\n",
96 getprogname());
97 exit(EXIT_FAILURE);
100 static int
101 run_cc(int argc, char **argv, const char **fname)
103 const char *CC, *tmpdir;
104 char * volatile pathname;
105 static char tmpfilename[MAXPATHLEN];
106 char **args;
107 int tmpfd;
108 pid_t pid, cpid;
109 int status;
111 if ((CC = getenv("CC")) == NULL)
112 CC = DEFAULT_CC;
113 if ((pathname = findcc(CC)) == NULL)
114 if (!setenv("PATH", DEFAULT_PATH, 1))
115 pathname = findcc(CC);
116 if (pathname == NULL)
117 err(EXIT_FAILURE, "%s: not found", CC);
118 if ((args = malloc((argc + 3) * sizeof(char *))) == NULL)
119 err(EXIT_FAILURE, "malloc");
121 args[0] = deconst(CC);
122 args[1] = deconst("-M");
123 (void)memcpy(&args[2], argv, (argc + 1) * sizeof(char *));
125 if ((tmpdir = getenv("TMPDIR")) == NULL)
126 tmpdir = _PATH_TMP;
127 (void)snprintf(tmpfilename, sizeof (tmpfilename), "%s/%s", tmpdir,
128 "mkdepXXXXXX");
129 if ((tmpfd = mkstemp(tmpfilename)) < 0) {
130 warn("unable to create temporary file %s", tmpfilename);
131 exit(EXIT_FAILURE);
133 (void)unlink(tmpfilename);
134 *fname = tmpfilename;
136 switch (cpid = vfork()) {
137 case 0:
138 (void)dup2(tmpfd, STDOUT_FILENO);
139 (void)close(tmpfd);
141 (void)execv(pathname, args);
142 _exit(EXIT_FAILURE);
143 /* NOTREACHED */
145 case -1:
146 err(EXIT_FAILURE, "unable to fork");
149 free(pathname);
150 free(args);
152 while (((pid = wait(&status)) != cpid) && (pid >= 0))
153 continue;
155 if (status)
156 errx(EXIT_FAILURE, "compile failed.");
158 return tmpfd;
161 static const char *
162 read_fname(void)
164 static char *fbuf;
165 static int fbuflen;
166 int len, ch;
168 for (len = 0; (ch = getchar()) != EOF; len++) {
169 if (isspace(ch)) {
170 if (len != 0)
171 break;
172 len--;
173 continue;
175 if (len >= fbuflen - 1) {
176 fbuf = realloc(fbuf, fbuflen += 32);
177 if (fbuf == NULL)
178 err(EXIT_FAILURE, "no memory");
180 fbuf[len] = ch;
182 if (len == 0)
183 return NULL;
184 fbuf[len] = 0;
185 return fbuf;
189 main(int argc, char **argv)
191 int aflag, dflag, oflag, qflag;
192 const char *filename;
193 int dependfile;
194 char *buf, *lim, *ptr, *line, *suf, *colon, *eol;
195 int ok_ind, ch;
196 size_t sz;
197 int fd;
198 size_t slen;
199 const char *fname;
200 const char *suffixes = NULL, *s;
201 suff_list_t *suff_list = NULL, *sl;
202 #ifdef __minix
203 size_t nr;
204 #endif
206 suf = NULL; /* XXXGCC -Wuninitialized [sun2] */
207 sl = NULL; /* XXXGCC -Wuninitialized [sun2] */
209 setlocale(LC_ALL, "");
210 setprogname(argv[0]);
212 aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
213 dflag = 0;
214 oflag = 0;
215 qflag = 0;
216 filename = DEFAULT_FILENAME;
217 dependfile = -1;
219 opterr = 0; /* stop getopt() bleating about errors. */
220 for (;;) {
221 ok_ind = optind;
222 ch = getopt(argc, argv, "aDdf:opqs:");
223 switch (ch) {
224 case -1:
225 ok_ind = optind;
226 break;
227 case 'a': /* Append to output file */
228 aflag &= ~O_TRUNC;
229 continue;
230 case 'D': /* Process *.d files (don't run cc -M) */
231 dflag = 2; /* Read names from stdin */
232 opterr = 1;
233 continue;
234 case 'd': /* Process *.d files (don't run cc -M) */
235 dflag = 1;
236 opterr = 1;
237 continue;
238 case 'f': /* Name of output file */
239 filename = optarg;
240 continue;
241 case 'o': /* Mark dependant files .OPTIONAL */
242 oflag = 1;
243 continue;
244 case 'p': /* Program mode (x.o: -> x:) */
245 suffixes = "";
246 continue;
247 case 'q': /* Quiet */
248 qflag = 1;
249 continue;
250 case 's': /* Suffix list */
251 suffixes = optarg;
252 continue;
253 default:
254 if (dflag)
255 usage();
256 /* Unknown arguments are passed to "${CC} -M" */
257 break;
259 break;
262 argc -= ok_ind;
263 argv += ok_ind;
264 if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
265 usage();
267 if (suffixes != NULL) {
268 /* parse list once and save names and lengths */
269 /* allocate an extra entry to mark end of list */
270 for (sz = 1, s = suffixes; *s != 0; s++)
271 if (*s == '.')
272 sz++;
273 suff_list = calloc(sz, sizeof *suff_list);
274 if (suff_list == NULL)
275 err(2, "malloc");
276 sl = suff_list;
277 for (s = suffixes; (s = strchr(s, '.')); s += sz, sl++) {
278 sz = strcspn(s, ", ");
279 if (sz > sizeof sl->suff)
280 errx(2, "suffix too long");
281 sl->len = sz;
282 memcpy(sl->suff, s, sz);
286 dependfile = open(filename, aflag, 0666);
287 if (dependfile == -1)
288 err(EXIT_FAILURE, "unable to %s to file %s\n",
289 aflag & O_TRUNC ? "write" : "append", filename);
291 while (dflag == 2 || *argv != NULL) {
292 if (dflag) {
293 if (dflag == 2) {
294 fname = read_fname();
295 if (fname == NULL)
296 break;
297 } else
298 fname = *argv++;
299 fd = open(fname, O_RDONLY, 0);
300 if (fd == -1) {
301 if (!qflag)
302 warn("ignoring %s", fname);
303 continue;
305 } else {
306 fd = run_cc(argc, argv, &fname);
307 /* consume all args... */
308 argv += argc;
311 sz = lseek(fd, 0, SEEK_END);
312 if (sz == 0) {
313 close(fd);
314 continue;
316 #ifndef __minix
317 buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
318 close(fd);
320 if (buf == MAP_FAILED)
321 err(EXIT_FAILURE, "unable to mmap file %s", fname);
322 #else
323 buf = malloc(sz);
324 if (buf == NULL)
325 err(EXIT_FAILURE, "malloc");
326 if ((nr = pread(fd, buf, sz, 0)) != sz)
327 err(EXIT_FAILURE, "read error %s", fname);
328 close(fd);
329 #endif
330 lim = buf + sz - 1;
332 /* Remove leading "./" from filenames */
333 for (ptr = buf; ptr < lim; ptr++) {
334 if (ptr[1] != '.' || ptr[2] != '/'
335 || !isspace((unsigned char)ptr[0]))
336 continue;
337 ptr[1] = ' ';
338 ptr[2] = ' ';
341 for (line = eol = buf; eol <= lim;) {
342 while (eol <= lim && *eol++ != '\n')
343 /* Find end of this line */
344 continue;
345 if (line == eol - 1) {
346 /* empty line - ignore */
347 line = eol;
348 continue;
350 if (eol[-2] == '\\')
351 /* Assemble continuation lines */
352 continue;
353 for (colon = line; *colon != ':'; colon++) {
354 if (colon >= eol) {
355 colon = NULL;
356 break;
359 if (isspace((unsigned char)*line) || colon == NULL) {
360 /* No dependency - just transcribe line */
361 write(dependfile, line, eol - line);
362 line = eol;
363 continue;
365 if (suff_list != NULL) {
366 /* Find the .o: */
367 /* First allow for any whitespace */
368 for (suf = colon; suf > buf; suf--) {
369 if (!isspace((unsigned char)suf[-1]))
370 break;
372 if (suf == buf)
373 errx(EXIT_FAILURE,
374 "Corrupted file `%s'", fname);
375 /* Then look for any valid suffix */
376 for (sl = suff_list; sl->len != 0; sl++) {
377 if (!memcmp(suf - sl->len, sl->suff,
378 sl->len))
379 break;
382 * Not found, check for .o, since the
383 * original file will have it.
385 if (sl->len == 0 && suff_list->len != 0) {
386 if (memcmp(suf - 2, ".o", 2) == 0)
387 slen = 2;
388 else
389 slen = 0;
390 } else
391 slen = sl->len;
393 if (suff_list != NULL && slen != 0) {
394 suf -= slen;
395 for (sl = suff_list; sl->len != 0; sl++) {
396 if (sl != suff_list)
397 write(dependfile, " ", 1);
398 write(dependfile, line, suf - line);
399 write(dependfile, sl->suff, sl->len);
401 write(dependfile, colon, eol - colon);
402 } else
403 write(dependfile, line, eol - line);
405 if (oflag)
406 save_for_optional(colon + 1, eol);
407 line = eol;
409 #ifndef __minix
410 munmap(buf, sz);
411 #else
412 free(buf);
413 #endif
416 if (oflag && opt != NULL) {
417 write(dependfile, ".OPTIONAL:", 10);
418 width = 9;
419 sz = write_optional(dependfile, opt, 0);
420 /* 'depth' is about 39 for an i386 kernel */
421 /* fprintf(stderr, "Recursion depth %d\n", sz); */
423 close(dependfile);
425 exit(EXIT_SUCCESS);
430 * Only save each file once - the kernel .depend is 3MB and there is
431 * no point doubling its size.
432 * The data seems to be 'random enough' so the simple binary tree
433 * only has a reasonable depth.
435 static void
436 save_for_optional(const char *start, const char *limit)
438 opt_t **l, *n;
439 const char *name, *end;
440 int c;
442 while (start < limit && strchr(" \t\n\\", *start))
443 start++;
444 for (name = start; ; name = end) {
445 while (name < limit && strchr(" \t\n\\", *name))
446 name++;
447 for (end = name; end < limit && !strchr(" \t\n\\", *end);)
448 end++;
449 if (name >= limit)
450 break;
451 if (end[-1] == 'c' && end[-2] == '.' && name == start)
452 /* ignore dependency on the files own .c */
453 continue;
454 for (l = &opt;;) {
455 n = *l;
456 if (n == NULL) {
457 n = malloc(sizeof *n + (end - name));
458 n->left = n->right = 0;
459 n->len = end - name;
460 n->count = 1;
461 n->name[0] = ' ';
462 memcpy(n->name + 1, name, end - name);
463 *l = n;
464 break;
466 c = (end - name) - n->len;
467 if (c == 0)
468 c = memcmp(n->name + 1, name, (end - name));
469 if (c == 0) {
470 /* Duplicate */
471 n->count++;
472 break;
474 if (c < 0)
475 l = &n->left;
476 else
477 l = &n->right;
482 static int
483 write_optional(int fd, opt_t *node, int depth)
485 int d1 = ++depth;
487 if (node->left)
488 d1 = write_optional(fd, node->left, d1);
489 if (width > 76 - node->len) {
490 write(fd, " \\\n ", 4);
491 width = 1;
493 width += 1 + node->len;
494 write(fd, node->name, 1 + node->len);
495 if (node->right)
496 depth = write_optional(fd, node->right, depth);
497 return d1 > depth ? d1 : depth;