tools/llvm: Do not build with symbols
[minix3.git] / usr.bin / make / main.c
blob3f5a7493658f4cf99694f955bdd951fdc09b4f7e
1 /* $NetBSD: main.c,v 1.225 2013/09/14 15:09:34 matt Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.225 2013/09/14 15:09:34 matt Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
77 The Regents of the University of California. All rights reserved.");
78 #endif /* not lint */
80 #ifndef lint
81 #if 0
82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94";
83 #else
84 __RCSID("$NetBSD: main.c,v 1.225 2013/09/14 15:09:34 matt Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
94 * Utility functions defined in this file:
95 * Main_ParseArgLine Takes a line of arguments, breaks them and
96 * treats them as if they were given when first
97 * invoked. Used by the parse module to implement
98 * the .MFLAGS target.
100 * Error Print a tagged error message. The global
101 * MAKE variable must have been defined. This
102 * takes a format string and two optional
103 * arguments for it.
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/stat.h>
121 #ifdef MAKE_NATIVE
122 #include <sys/sysctl.h>
123 #endif
124 #include <sys/utsname.h>
125 #include <sys/wait.h>
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <signal.h>
130 #include <stdarg.h>
131 #include <stdio.h>
132 #include <stdlib.h>
133 #include <time.h>
134 #include <ctype.h>
136 #include "make.h"
137 #include "hash.h"
138 #include "dir.h"
139 #include "job.h"
140 #include "pathnames.h"
141 #include "trace.h"
143 #ifdef USE_IOVEC
144 #include <sys/uio.h>
145 #endif
147 #ifndef DEFMAXLOCAL
148 #define DEFMAXLOCAL DEFMAXJOBS
149 #endif /* DEFMAXLOCAL */
151 Lst create; /* Targets to be made */
152 time_t now; /* Time at start of make */
153 GNode *DEFAULT; /* .DEFAULT node */
154 Boolean allPrecious; /* .PRECIOUS given on line by itself */
156 static Boolean noBuiltins; /* -r flag */
157 static Lst makefiles; /* ordered list of makefiles to read */
158 static Boolean printVars; /* print value of one or more vars */
159 static Lst variables; /* list of variables to print */
160 int maxJobs; /* -j argument */
161 static int maxJobTokens; /* -j argument */
162 Boolean compatMake; /* -B argument */
163 int debug; /* -d argument */
164 Boolean debugVflag; /* -dV */
165 Boolean noExecute; /* -n flag */
166 Boolean noRecursiveExecute; /* -N flag */
167 Boolean keepgoing; /* -k flag */
168 Boolean queryFlag; /* -q flag */
169 Boolean touchFlag; /* -t flag */
170 Boolean enterFlag; /* -w flag */
171 Boolean ignoreErrors; /* -i flag */
172 Boolean beSilent; /* -s flag */
173 Boolean oldVars; /* variable substitution style */
174 Boolean checkEnvFirst; /* -e flag */
175 Boolean parseWarnFatal; /* -W flag */
176 Boolean jobServer; /* -J flag */
177 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
178 Boolean varNoExportEnv; /* -X flag */
179 Boolean doing_depend; /* Set while reading .depend */
180 static Boolean jobsRunning; /* TRUE if the jobs might be running */
181 static const char * tracefile;
182 static void MainParseArgs(int, char **);
183 static int ReadMakefile(const void *, const void *);
184 static void usage(void) MAKE_ATTR_DEAD;
186 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
187 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
188 char curdir[MAXPATHLEN + 1]; /* Startup directory */
189 char *progname; /* the program name */
190 char *makeDependfile;
191 pid_t myPid;
192 int makelevel;
194 Boolean forceJobs = FALSE;
196 extern Lst parseIncPath;
199 * For compatibility with the POSIX version of MAKEFLAGS that includes
200 * all the options with out -, convert flags to -f -l -a -g -s.
202 static char *
203 explode(const char *flags)
205 size_t len;
206 char *nf, *st;
207 const char *f;
209 if (flags == NULL)
210 return NULL;
212 for (f = flags; *f; f++)
213 if (!isalpha((unsigned char)*f))
214 break;
216 if (*f)
217 return bmake_strdup(flags);
219 len = strlen(flags);
220 st = nf = bmake_malloc(len * 3 + 1);
221 while (*flags) {
222 *nf++ = '-';
223 *nf++ = *flags++;
224 *nf++ = ' ';
226 *nf = '\0';
227 return st;
230 static void
231 parse_debug_options(const char *argvalue)
233 const char *modules;
234 const char *mode;
235 char *fname;
236 int len;
238 for (modules = argvalue; *modules; ++modules) {
239 switch (*modules) {
240 case 'A':
241 debug = ~0;
242 break;
243 case 'a':
244 debug |= DEBUG_ARCH;
245 break;
246 case 'C':
247 debug |= DEBUG_CWD;
248 break;
249 case 'c':
250 debug |= DEBUG_COND;
251 break;
252 case 'd':
253 debug |= DEBUG_DIR;
254 break;
255 case 'e':
256 debug |= DEBUG_ERROR;
257 break;
258 case 'f':
259 debug |= DEBUG_FOR;
260 break;
261 case 'g':
262 if (modules[1] == '1') {
263 debug |= DEBUG_GRAPH1;
264 ++modules;
266 else if (modules[1] == '2') {
267 debug |= DEBUG_GRAPH2;
268 ++modules;
270 else if (modules[1] == '3') {
271 debug |= DEBUG_GRAPH3;
272 ++modules;
274 break;
275 case 'j':
276 debug |= DEBUG_JOB;
277 break;
278 case 'l':
279 debug |= DEBUG_LOUD;
280 break;
281 case 'M':
282 debug |= DEBUG_META;
283 break;
284 case 'm':
285 debug |= DEBUG_MAKE;
286 break;
287 case 'n':
288 debug |= DEBUG_SCRIPT;
289 break;
290 case 'p':
291 debug |= DEBUG_PARSE;
292 break;
293 case 's':
294 debug |= DEBUG_SUFF;
295 break;
296 case 't':
297 debug |= DEBUG_TARG;
298 break;
299 case 'V':
300 debugVflag = TRUE;
301 break;
302 case 'v':
303 debug |= DEBUG_VAR;
304 break;
305 case 'x':
306 debug |= DEBUG_SHELL;
307 break;
308 case 'F':
309 if (debug_file != stdout && debug_file != stderr)
310 fclose(debug_file);
311 if (*++modules == '+') {
312 modules++;
313 mode = "a";
314 } else
315 mode = "w";
316 if (strcmp(modules, "stdout") == 0) {
317 debug_file = stdout;
318 goto debug_setbuf;
320 if (strcmp(modules, "stderr") == 0) {
321 debug_file = stderr;
322 goto debug_setbuf;
324 len = strlen(modules);
325 fname = malloc(len + 20);
326 memcpy(fname, modules, len + 1);
327 /* Let the filename be modified by the pid */
328 if (strcmp(fname + len - 3, ".%d") == 0)
329 snprintf(fname + len - 2, 20, "%d", getpid());
330 debug_file = fopen(fname, mode);
331 if (!debug_file) {
332 fprintf(stderr, "Cannot open debug file %s\n",
333 fname);
334 usage();
336 free(fname);
337 goto debug_setbuf;
338 default:
339 (void)fprintf(stderr,
340 "%s: illegal argument to d option -- %c\n",
341 progname, *modules);
342 usage();
345 debug_setbuf:
347 * Make the debug_file unbuffered, and make
348 * stdout line buffered (unless debugfile == stdout).
350 setvbuf(debug_file, NULL, _IONBF, 0);
351 if (debug_file != stdout) {
352 setvbuf(stdout, NULL, _IOLBF, 0);
357 * MainParseArgs --
358 * Parse a given argument vector. Called from main() and from
359 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
361 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
363 * Results:
364 * None
366 * Side Effects:
367 * Various global and local flags will be set depending on the flags
368 * given
370 static void
371 MainParseArgs(int argc, char **argv)
373 char *p;
374 int c = '?';
375 int arginc;
376 char *argvalue;
377 const char *getopt_def;
378 char *optscan;
379 Boolean inOption, dashDash = FALSE;
380 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
382 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstw"
383 /* Can't actually use getopt(3) because rescanning is not portable */
385 getopt_def = OPTFLAGS;
386 rearg:
387 inOption = FALSE;
388 optscan = NULL;
389 while(argc > 1) {
390 char *getopt_spec;
391 if(!inOption)
392 optscan = argv[1];
393 c = *optscan++;
394 arginc = 0;
395 if(inOption) {
396 if(c == '\0') {
397 ++argv;
398 --argc;
399 inOption = FALSE;
400 continue;
402 } else {
403 if (c != '-' || dashDash)
404 break;
405 inOption = TRUE;
406 c = *optscan++;
408 /* '-' found at some earlier point */
409 getopt_spec = strchr(getopt_def, c);
410 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
411 /* -<something> found, and <something> should have an arg */
412 inOption = FALSE;
413 arginc = 1;
414 argvalue = optscan;
415 if(*argvalue == '\0') {
416 if (argc < 3)
417 goto noarg;
418 argvalue = argv[2];
419 arginc = 2;
421 } else {
422 argvalue = NULL;
424 switch(c) {
425 case '\0':
426 arginc = 1;
427 inOption = FALSE;
428 break;
429 case 'B':
430 compatMake = TRUE;
431 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
432 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
433 break;
434 case 'C':
435 if (chdir(argvalue) == -1) {
436 (void)fprintf(stderr,
437 "%s: chdir %s: %s\n",
438 progname, argvalue,
439 strerror(errno));
440 exit(1);
442 if (getcwd(curdir, MAXPATHLEN) == NULL) {
443 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
444 exit(2);
446 ignorePWD = TRUE;
447 break;
448 case 'D':
449 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
450 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
451 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
452 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
453 break;
454 case 'I':
455 if (argvalue == NULL) goto noarg;
456 Parse_AddIncludeDir(argvalue);
457 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
458 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
459 break;
460 case 'J':
461 if (argvalue == NULL) goto noarg;
462 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
463 (void)fprintf(stderr,
464 "%s: internal error -- J option malformed (%s)\n",
465 progname, argvalue);
466 usage();
468 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
469 (fcntl(jp_1, F_GETFD, 0) < 0)) {
470 #if 0
471 (void)fprintf(stderr,
472 "%s: ###### warning -- J descriptors were closed!\n",
473 progname);
474 exit(2);
475 #endif
476 jp_0 = -1;
477 jp_1 = -1;
478 compatMake = TRUE;
479 } else {
480 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
481 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
482 jobServer = TRUE;
484 break;
485 case 'N':
486 noExecute = TRUE;
487 noRecursiveExecute = TRUE;
488 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
489 break;
490 case 'S':
491 keepgoing = FALSE;
492 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
493 break;
494 case 'T':
495 if (argvalue == NULL) goto noarg;
496 tracefile = bmake_strdup(argvalue);
497 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
498 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
499 break;
500 case 'V':
501 if (argvalue == NULL) goto noarg;
502 printVars = TRUE;
503 (void)Lst_AtEnd(variables, argvalue);
504 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
505 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
506 break;
507 case 'W':
508 parseWarnFatal = TRUE;
509 break;
510 case 'X':
511 varNoExportEnv = TRUE;
512 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
513 break;
514 case 'd':
515 if (argvalue == NULL) goto noarg;
516 /* If '-d-opts' don't pass to children */
517 if (argvalue[0] == '-')
518 argvalue++;
519 else {
520 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
521 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
523 parse_debug_options(argvalue);
524 break;
525 case 'e':
526 checkEnvFirst = TRUE;
527 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
528 break;
529 case 'f':
530 if (argvalue == NULL) goto noarg;
531 (void)Lst_AtEnd(makefiles, argvalue);
532 break;
533 case 'i':
534 ignoreErrors = TRUE;
535 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
536 break;
537 case 'j':
538 if (argvalue == NULL) goto noarg;
539 forceJobs = TRUE;
540 maxJobs = strtol(argvalue, &p, 0);
541 if (*p != '\0' || maxJobs < 1) {
542 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
543 progname);
544 exit(1);
546 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
547 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
548 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
549 maxJobTokens = maxJobs;
550 break;
551 case 'k':
552 keepgoing = TRUE;
553 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
554 break;
555 case 'm':
556 if (argvalue == NULL) goto noarg;
557 /* look for magic parent directory search string */
558 if (strncmp(".../", argvalue, 4) == 0) {
559 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
560 found_path, sizeof(found_path)))
561 break; /* nothing doing */
562 (void)Dir_AddDir(sysIncPath, found_path);
563 } else {
564 (void)Dir_AddDir(sysIncPath, argvalue);
566 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
567 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
568 break;
569 case 'n':
570 noExecute = TRUE;
571 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
572 break;
573 case 'q':
574 queryFlag = TRUE;
575 /* Kind of nonsensical, wot? */
576 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
577 break;
578 case 'r':
579 noBuiltins = TRUE;
580 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
581 break;
582 case 's':
583 beSilent = TRUE;
584 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
585 break;
586 case 't':
587 touchFlag = TRUE;
588 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
589 break;
590 case 'w':
591 enterFlag = TRUE;
592 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
593 break;
594 case '-':
595 dashDash = TRUE;
596 break;
597 default:
598 case '?':
599 usage();
601 argv += arginc;
602 argc -= arginc;
605 oldVars = TRUE;
608 * See if the rest of the arguments are variable assignments and
609 * perform them if so. Else take them to be targets and stuff them
610 * on the end of the "create" list.
612 for (; argc > 1; ++argv, --argc)
613 if (Parse_IsVar(argv[1])) {
614 Parse_DoVar(argv[1], VAR_CMD);
615 } else {
616 if (!*argv[1])
617 Punt("illegal (null) argument.");
618 if (*argv[1] == '-' && !dashDash)
619 goto rearg;
620 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
623 return;
624 noarg:
625 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
626 progname, c);
627 usage();
631 * Main_ParseArgLine --
632 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
633 * is encountered and by main() when reading the .MAKEFLAGS envariable.
634 * Takes a line of arguments and breaks it into its
635 * component words and passes those words and the number of them to the
636 * MainParseArgs function.
637 * The line should have all its leading whitespace removed.
639 * Input:
640 * line Line to fracture
642 * Results:
643 * None
645 * Side Effects:
646 * Only those that come from the various arguments.
648 void
649 Main_ParseArgLine(const char *line)
651 char **argv; /* Manufactured argument vector */
652 int argc; /* Number of arguments in argv */
653 char *args; /* Space used by the args */
654 char *buf, *p1;
655 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
656 size_t len;
658 if (line == NULL)
659 return;
660 for (; *line == ' '; ++line)
661 continue;
662 if (!*line)
663 return;
665 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
666 (void)snprintf(buf, len, "%s %s", argv0, line);
667 if (p1)
668 free(p1);
670 argv = brk_string(buf, &argc, TRUE, &args);
671 if (argv == NULL) {
672 Error("Unterminated quoted string [%s]", buf);
673 free(buf);
674 return;
676 free(buf);
677 MainParseArgs(argc, argv);
679 free(args);
680 free(argv);
683 Boolean
684 Main_SetObjdir(const char *path)
686 struct stat sb;
687 char *p = NULL;
688 char buf[MAXPATHLEN + 1];
689 Boolean rc = FALSE;
691 /* expand variable substitutions */
692 if (strchr(path, '$') != 0) {
693 snprintf(buf, MAXPATHLEN, "%s", path);
694 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
697 if (path[0] != '/') {
698 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
699 path = buf;
702 /* look for the directory and try to chdir there */
703 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
704 if (chdir(path)) {
705 (void)fprintf(stderr, "make warning: %s: %s.\n",
706 path, strerror(errno));
707 } else {
708 strncpy(objdir, path, MAXPATHLEN);
709 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
710 setenv("PWD", objdir, 1);
711 Dir_InitDot();
712 rc = TRUE;
716 if (p)
717 free(p);
718 return rc;
722 * ReadAllMakefiles --
723 * wrapper around ReadMakefile() to read all.
725 * Results:
726 * TRUE if ok, FALSE on error
728 static int
729 ReadAllMakefiles(const void *p, const void *q)
731 return (ReadMakefile(p, q) == 0);
735 str2Lst_Append(Lst lp, char *str, const char *sep)
737 char *cp;
738 int n;
740 if (!sep)
741 sep = " \t";
743 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
744 (void)Lst_AtEnd(lp, cp);
745 n++;
747 return (n);
750 #ifdef SIGINFO
751 /*ARGSUSED*/
752 static void
753 siginfo(int signo MAKE_ATTR_UNUSED)
755 char dir[MAXPATHLEN];
756 char str[2 * MAXPATHLEN];
757 int len;
758 if (getcwd(dir, sizeof(dir)) == NULL)
759 return;
760 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
761 if (len > 0)
762 (void)write(STDERR_FILENO, str, (size_t)len);
764 #endif
767 * Allow makefiles some control over the mode we run in.
769 void
770 MakeMode(const char *mode)
772 char *mp = NULL;
774 if (!mode)
775 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}", VAR_GLOBAL, 0);
777 if (mode && *mode) {
778 if (strstr(mode, "compat")) {
779 compatMake = TRUE;
780 forceJobs = FALSE;
782 #if USE_META
783 if (strstr(mode, "meta"))
784 meta_mode_init(mode);
785 #endif
787 if (mp)
788 free(mp);
792 * main --
793 * The main function, for obvious reasons. Initializes variables
794 * and a few modules, then parses the arguments give it in the
795 * environment and on the command line. Reads the system makefile
796 * followed by either Makefile, makefile or the file given by the
797 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
798 * flags it has received by then uses either the Make or the Compat
799 * module to create the initial list of targets.
801 * Results:
802 * If -q was given, exits -1 if anything was out-of-date. Else it exits
803 * 0.
805 * Side Effects:
806 * The program exits when done. Targets are created. etc. etc. etc.
809 main(int argc, char **argv)
811 Lst targs; /* target nodes to create -- passed to Make_Init */
812 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
813 struct stat sb, sa;
814 char *p1, *path;
815 char mdpath[MAXPATHLEN];
816 const char *machine = getenv("MACHINE");
817 const char *machine_arch = getenv("MACHINE_ARCH");
818 char *syspath = getenv("MAKESYSPATH");
819 Lst sysMkPath; /* Path of sys.mk */
820 char *cp = NULL, *start;
821 /* avoid faults on read-only strings */
822 static char defsyspath[] = _PATH_DEFSYSPATH;
823 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
824 struct timeval rightnow; /* to initialize random seed */
825 struct utsname utsname;
827 /* default to writing debug to stderr */
828 debug_file = stderr;
830 #ifdef SIGINFO
831 (void)bmake_signal(SIGINFO, siginfo);
832 #endif
834 * Set the seed to produce a different random sequence
835 * on each program execution.
837 gettimeofday(&rightnow, NULL);
838 srandom(rightnow.tv_sec + rightnow.tv_usec);
840 if ((progname = strrchr(argv[0], '/')) != NULL)
841 progname++;
842 else
843 progname = argv[0];
844 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
846 * get rid of resource limit on file descriptors
849 struct rlimit rl;
850 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
851 rl.rlim_cur != rl.rlim_max) {
852 rl.rlim_cur = rl.rlim_max;
853 (void)setrlimit(RLIMIT_NOFILE, &rl);
856 #endif
858 if (uname(&utsname) == -1) {
859 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
860 strerror(errno));
861 exit(2);
865 * Get the name of this type of MACHINE from utsname
866 * so we can share an executable for similar machines.
867 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
869 * Note that both MACHINE and MACHINE_ARCH are decided at
870 * run-time.
872 if (!machine) {
873 #ifdef MAKE_NATIVE
874 machine = utsname.machine;
875 #else
876 #ifdef MAKE_MACHINE
877 machine = MAKE_MACHINE;
878 #else
879 machine = "unknown";
880 #endif
881 #endif
884 if (!machine_arch) {
885 #if defined(MAKE_NATIVE) && !defined(__minix)
886 static char machine_arch_buf[sizeof(utsname.machine)];
887 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
888 size_t len = sizeof(machine_arch_buf);
890 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
891 &len, NULL, 0) < 0) {
892 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
893 strerror(errno));
894 exit(2);
897 machine_arch = machine_arch_buf;
898 #else
899 #ifndef MACHINE_ARCH
900 #ifdef MAKE_MACHINE_ARCH
901 machine_arch = MAKE_MACHINE_ARCH;
902 #else
903 machine_arch = "unknown";
904 #endif
905 #else
906 machine_arch = MACHINE_ARCH;
907 #endif
908 #endif
911 myPid = getpid(); /* remember this for vFork() */
914 * Just in case MAKEOBJDIR wants us to do something tricky.
916 Var_Init(); /* Initialize the lists of variables for
917 * parsing arguments */
918 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
919 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
920 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
921 #ifdef MAKE_VERSION
922 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
923 #endif
924 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
926 * This is the traditional preference for makefiles.
928 #ifndef MAKEFILE_PREFERENCE_LIST
929 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
930 #endif
931 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
932 VAR_GLOBAL, 0);
933 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
935 create = Lst_Init(FALSE);
936 makefiles = Lst_Init(FALSE);
937 printVars = FALSE;
938 debugVflag = FALSE;
939 variables = Lst_Init(FALSE);
940 beSilent = FALSE; /* Print commands as executed */
941 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
942 noExecute = FALSE; /* Execute all commands */
943 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
944 keepgoing = FALSE; /* Stop on error */
945 allPrecious = FALSE; /* Remove targets when interrupted */
946 queryFlag = FALSE; /* This is not just a check-run */
947 noBuiltins = FALSE; /* Read the built-in rules */
948 touchFlag = FALSE; /* Actually update targets */
949 debug = 0; /* No debug verbosity, please. */
950 jobsRunning = FALSE;
952 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
953 maxJobTokens = maxJobs;
954 compatMake = FALSE; /* No compat mode */
955 ignorePWD = FALSE;
958 * Initialize the parsing, directory and variable modules to prepare
959 * for the reading of inclusion paths and variable settings on the
960 * command line
964 * Initialize various variables.
965 * MAKE also gets this name, for compatibility
966 * .MAKEFLAGS gets set to the empty string just in case.
967 * MFLAGS also gets initialized empty, for compatibility.
969 Parse_Init();
970 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
972 * Leave alone if it is an absolute path, or if it does
973 * not contain a '/' in which case we need to find it in
974 * the path, like execvp(3) and the shells do.
976 p1 = argv[0];
977 } else {
979 * A relative path, canonicalize it.
981 p1 = realpath(argv[0], mdpath);
982 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
983 p1 = argv[0]; /* realpath failed */
986 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
987 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
988 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
989 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
990 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
991 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
992 /* some makefiles need to know this */
993 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
996 * Set some other useful macros
999 char tmp[64], *ep;
1001 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1002 if (makelevel < 0)
1003 makelevel = 0;
1004 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1005 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
1006 snprintf(tmp, sizeof(tmp), "%u", myPid);
1007 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
1008 snprintf(tmp, sizeof(tmp), "%u", getppid());
1009 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
1011 if (makelevel > 0) {
1012 char pn[1024];
1013 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1014 progname = bmake_strdup(pn);
1017 #ifdef USE_META
1018 meta_init();
1019 #endif
1021 * First snag any flags out of the MAKE environment variable.
1022 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1023 * in a different format).
1025 #ifdef POSIX
1026 p1 = explode(getenv("MAKEFLAGS"));
1027 Main_ParseArgLine(p1);
1028 free(p1);
1029 #else
1030 Main_ParseArgLine(getenv("MAKE"));
1031 #endif
1034 * Find where we are (now).
1035 * We take care of PWD for the automounter below...
1037 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1038 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1039 progname, strerror(errno));
1040 exit(2);
1043 MainParseArgs(argc, argv);
1045 if (enterFlag)
1046 printf("%s: Entering directory `%s'\n", progname, curdir);
1049 * Verify that cwd is sane.
1051 if (stat(curdir, &sa) == -1) {
1052 (void)fprintf(stderr, "%s: %s: %s.\n",
1053 progname, curdir, strerror(errno));
1054 exit(2);
1058 * All this code is so that we know where we are when we start up
1059 * on a different machine with pmake.
1060 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1061 * since the value of curdir can vary depending on how we got
1062 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1063 * or via subdir.mk in which case its likely a shell which does
1064 * not provide it.
1065 * So, to stop it breaking this case only, we ignore PWD if
1066 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1068 #ifndef NO_PWD_OVERRIDE
1069 if (!ignorePWD) {
1070 char *pwd;
1072 if ((pwd = getenv("PWD")) != NULL &&
1073 getenv("MAKEOBJDIRPREFIX") == NULL) {
1074 const char *makeobjdir = getenv("MAKEOBJDIR");
1076 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1077 if (stat(pwd, &sb) == 0 &&
1078 sa.st_ino == sb.st_ino &&
1079 sa.st_dev == sb.st_dev)
1080 (void)strncpy(curdir, pwd, MAXPATHLEN);
1084 #endif
1085 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1088 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1089 * MAKEOBJDIR is set in the environment, try only that value
1090 * and fall back to .CURDIR if it does not exist.
1092 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1093 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1094 * of these paths exist, just use .CURDIR.
1096 Dir_Init(curdir);
1097 (void)Main_SetObjdir(curdir);
1099 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1100 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1101 (void)Main_SetObjdir(mdpath);
1102 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1103 (void)Main_SetObjdir(path);
1104 } else {
1105 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1106 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1107 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1108 _PATH_OBJDIRPREFIX, curdir);
1109 (void)Main_SetObjdir(mdpath);
1114 * Be compatible if user did not specify -j and did not explicitly
1115 * turned compatibility on
1117 if (!compatMake && !forceJobs) {
1118 compatMake = TRUE;
1122 * Initialize archive, target and suffix modules in preparation for
1123 * parsing the makefile(s)
1125 Arch_Init();
1126 Targ_Init();
1127 Suff_Init();
1128 Trace_Init(tracefile);
1130 DEFAULT = NULL;
1131 (void)time(&now);
1133 Trace_Log(MAKESTART, NULL);
1136 * Set up the .TARGETS variable to contain the list of targets to be
1137 * created. If none specified, make the variable empty -- the parser
1138 * will fill the thing in with the default or .MAIN target.
1140 if (!Lst_IsEmpty(create)) {
1141 LstNode ln;
1143 for (ln = Lst_First(create); ln != NULL;
1144 ln = Lst_Succ(ln)) {
1145 char *name = (char *)Lst_Datum(ln);
1147 Var_Append(".TARGETS", name, VAR_GLOBAL);
1149 } else
1150 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1154 * If no user-supplied system path was given (through the -m option)
1155 * add the directories from the DEFSYSPATH (more than one may be given
1156 * as dir1:...:dirn) to the system include path.
1158 if (syspath == NULL || *syspath == '\0')
1159 syspath = defsyspath;
1160 else
1161 syspath = bmake_strdup(syspath);
1163 for (start = syspath; *start != '\0'; start = cp) {
1164 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1165 continue;
1166 if (*cp == ':') {
1167 *cp++ = '\0';
1169 /* look for magic parent directory search string */
1170 if (strncmp(".../", start, 4) != 0) {
1171 (void)Dir_AddDir(defIncPath, start);
1172 } else {
1173 if (Dir_FindHereOrAbove(curdir, start+4,
1174 found_path, sizeof(found_path))) {
1175 (void)Dir_AddDir(defIncPath, found_path);
1179 if (syspath != defsyspath)
1180 free(syspath);
1183 * Read in the built-in rules first, followed by the specified
1184 * makefile, if it was (makefile != NULL), or the default
1185 * makefile and Makefile, in that order, if it wasn't.
1187 if (!noBuiltins) {
1188 LstNode ln;
1190 sysMkPath = Lst_Init(FALSE);
1191 Dir_Expand(_PATH_DEFSYSMK,
1192 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1193 sysMkPath);
1194 if (Lst_IsEmpty(sysMkPath))
1195 Fatal("%s: no system rules (%s).", progname,
1196 _PATH_DEFSYSMK);
1197 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1198 if (ln == NULL)
1199 Fatal("%s: cannot open %s.", progname,
1200 (char *)Lst_Datum(ln));
1203 if (!Lst_IsEmpty(makefiles)) {
1204 LstNode ln;
1206 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1207 if (ln != NULL)
1208 Fatal("%s: cannot open %s.", progname,
1209 (char *)Lst_Datum(ln));
1210 } else {
1211 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1212 VAR_CMD, 0);
1213 if (p1) {
1214 (void)str2Lst_Append(makefiles, p1, NULL);
1215 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1216 free(p1);
1220 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1221 if (!noBuiltins || !printVars) {
1222 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1223 VAR_CMD, 0);
1224 doing_depend = TRUE;
1225 (void)ReadMakefile(makeDependfile, NULL);
1226 doing_depend = FALSE;
1229 MakeMode(NULL);
1231 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1232 if (p1)
1233 free(p1);
1235 if (!compatMake)
1236 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1237 if (DEBUG(JOB))
1238 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1239 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1241 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1245 * For compatibility, look at the directories in the VPATH variable
1246 * and add them to the search path, if the variable is defined. The
1247 * variable's value is in the same format as the PATH envariable, i.e.
1248 * <directory>:<directory>:<directory>...
1250 if (Var_Exists("VPATH", VAR_CMD)) {
1251 char *vpath, savec;
1253 * GCC stores string constants in read-only memory, but
1254 * Var_Subst will want to write this thing, so store it
1255 * in an array
1257 static char VPATH[] = "${VPATH}";
1259 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1260 path = vpath;
1261 do {
1262 /* skip to end of directory */
1263 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1264 continue;
1265 /* Save terminator character so know when to stop */
1266 savec = *cp;
1267 *cp = '\0';
1268 /* Add directory to search path */
1269 (void)Dir_AddDir(dirSearchPath, path);
1270 *cp = savec;
1271 path = cp + 1;
1272 } while (savec == ':');
1273 free(vpath);
1277 * Now that all search paths have been read for suffixes et al, it's
1278 * time to add the default search path to their lists...
1280 Suff_DoPaths();
1283 * Propagate attributes through :: dependency lists.
1285 Targ_Propagate();
1287 /* print the initial graph, if the user requested it */
1288 if (DEBUG(GRAPH1))
1289 Targ_PrintGraph(1);
1291 /* print the values of any variables requested by the user */
1292 if (printVars) {
1293 LstNode ln;
1294 Boolean expandVars;
1296 if (debugVflag)
1297 expandVars = FALSE;
1298 else
1299 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1300 for (ln = Lst_First(variables); ln != NULL;
1301 ln = Lst_Succ(ln)) {
1302 char *var = (char *)Lst_Datum(ln);
1303 char *value;
1305 if (strchr(var, '$')) {
1306 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1307 } else if (expandVars) {
1308 char tmp[128];
1310 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1311 Fatal("%s: variable name too big: %s",
1312 progname, var);
1313 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1314 } else {
1315 value = Var_Value(var, VAR_GLOBAL, &p1);
1317 printf("%s\n", value ? value : "");
1318 if (p1)
1319 free(p1);
1321 } else {
1323 * Have now read the entire graph and need to make a list of
1324 * targets to create. If none was given on the command line,
1325 * we consult the parsing module to find the main target(s)
1326 * to create.
1328 if (Lst_IsEmpty(create))
1329 targs = Parse_MainName();
1330 else
1331 targs = Targ_FindList(create, TARG_CREATE);
1333 if (!compatMake) {
1335 * Initialize job module before traversing the graph
1336 * now that any .BEGIN and .END targets have been read.
1337 * This is done only if the -q flag wasn't given
1338 * (to prevent the .BEGIN from being executed should
1339 * it exist).
1341 if (!queryFlag) {
1342 Job_Init();
1343 jobsRunning = TRUE;
1346 /* Traverse the graph, checking on all the targets */
1347 outOfDate = Make_Run(targs);
1348 } else {
1350 * Compat_Init will take care of creating all the
1351 * targets as well as initializing the module.
1353 Compat_Run(targs);
1357 #ifdef CLEANUP
1358 Lst_Destroy(targs, NULL);
1359 Lst_Destroy(variables, NULL);
1360 Lst_Destroy(makefiles, NULL);
1361 Lst_Destroy(create, (FreeProc *)free);
1362 #endif
1364 /* print the graph now it's been processed if the user requested it */
1365 if (DEBUG(GRAPH2))
1366 Targ_PrintGraph(2);
1368 Trace_Log(MAKEEND, 0);
1370 if (enterFlag)
1371 printf("%s: Leaving directory `%s'\n", progname, curdir);
1373 Suff_End();
1374 Targ_End();
1375 Arch_End();
1376 Var_End();
1377 Parse_End();
1378 Dir_End();
1379 Job_End();
1380 Trace_End();
1382 return outOfDate ? 1 : 0;
1386 * ReadMakefile --
1387 * Open and parse the given makefile.
1389 * Results:
1390 * 0 if ok. -1 if couldn't open file.
1392 * Side Effects:
1393 * lots
1395 static int
1396 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1398 const char *fname = p; /* makefile to read */
1399 int fd;
1400 size_t len = MAXPATHLEN;
1401 char *name, *path = bmake_malloc(len);
1403 if (!strcmp(fname, "-")) {
1404 Parse_File(NULL /*stdin*/, -1);
1405 Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1406 } else {
1407 /* if we've chdir'd, rebuild the path name */
1408 if (strcmp(curdir, objdir) && *fname != '/') {
1409 size_t plen = strlen(curdir) + strlen(fname) + 2;
1410 if (len < plen)
1411 path = bmake_realloc(path, len = 2 * plen);
1413 (void)snprintf(path, len, "%s/%s", curdir, fname);
1414 fd = open(path, O_RDONLY);
1415 if (fd != -1) {
1416 fname = path;
1417 goto found;
1420 /* If curdir failed, try objdir (ala .depend) */
1421 plen = strlen(objdir) + strlen(fname) + 2;
1422 if (len < plen)
1423 path = bmake_realloc(path, len = 2 * plen);
1424 (void)snprintf(path, len, "%s/%s", objdir, fname);
1425 fd = open(path, O_RDONLY);
1426 if (fd != -1) {
1427 fname = path;
1428 goto found;
1430 } else {
1431 fd = open(fname, O_RDONLY);
1432 if (fd != -1)
1433 goto found;
1435 /* look in -I and system include directories. */
1436 name = Dir_FindFile(fname, parseIncPath);
1437 if (!name)
1438 name = Dir_FindFile(fname,
1439 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1440 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1441 if (name)
1442 free(name);
1443 free(path);
1444 return(-1);
1446 fname = name;
1448 * set the MAKEFILE variable desired by System V fans -- the
1449 * placement of the setting here means it gets set to the last
1450 * makefile specified, as it is set by SysV make.
1452 found:
1453 if (!doing_depend)
1454 Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1455 Parse_File(fname, fd);
1457 free(path);
1458 return(0);
1464 * Cmd_Exec --
1465 * Execute the command in cmd, and return the output of that command
1466 * in a string.
1468 * Results:
1469 * A string containing the output of the command, or the empty string
1470 * If errnum is not NULL, it contains the reason for the command failure
1472 * Side Effects:
1473 * The string must be freed by the caller.
1475 char *
1476 Cmd_Exec(const char *cmd, const char **errnum)
1478 const char *args[4]; /* Args for invoking the shell */
1479 int fds[2]; /* Pipe streams */
1480 int cpid; /* Child PID */
1481 int pid; /* PID from wait() */
1482 char *res; /* result */
1483 int status; /* command exit status */
1484 Buffer buf; /* buffer to store the result */
1485 char *cp;
1486 int cc;
1489 *errnum = NULL;
1491 if (!shellName)
1492 Shell_Init();
1494 * Set up arguments for shell
1496 args[0] = shellName;
1497 args[1] = "-c";
1498 args[2] = cmd;
1499 args[3] = NULL;
1502 * Open a pipe for fetching its output
1504 if (pipe(fds) == -1) {
1505 *errnum = "Couldn't create pipe for \"%s\"";
1506 goto bad;
1510 * Fork
1512 switch (cpid = vFork()) {
1513 case 0:
1515 * Close input side of pipe
1517 (void)close(fds[0]);
1520 * Duplicate the output stream to the shell's output, then
1521 * shut the extra thing down. Note we don't fetch the error
1522 * stream...why not? Why?
1524 (void)dup2(fds[1], 1);
1525 (void)close(fds[1]);
1527 Var_ExportVars();
1529 (void)execv(shellPath, UNCONST(args));
1530 _exit(1);
1531 /*NOTREACHED*/
1533 case -1:
1534 *errnum = "Couldn't exec \"%s\"";
1535 goto bad;
1537 default:
1539 * No need for the writing half
1541 (void)close(fds[1]);
1543 Buf_Init(&buf, 0);
1545 do {
1546 char result[BUFSIZ];
1547 cc = read(fds[0], result, sizeof(result));
1548 if (cc > 0)
1549 Buf_AddBytes(&buf, cc, result);
1551 while (cc > 0 || (cc == -1 && errno == EINTR));
1554 * Close the input side of the pipe.
1556 (void)close(fds[0]);
1559 * Wait for the process to exit.
1561 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1562 JobReapChild(pid, status, FALSE);
1563 continue;
1565 cc = Buf_Size(&buf);
1566 res = Buf_Destroy(&buf, FALSE);
1568 if (cc == 0)
1569 *errnum = "Couldn't read shell's output for \"%s\"";
1571 if (WIFSIGNALED(status))
1572 *errnum = "\"%s\" exited on a signal";
1573 else if (WEXITSTATUS(status) != 0)
1574 *errnum = "\"%s\" returned non-zero status";
1577 * Null-terminate the result, convert newlines to spaces and
1578 * install it in the variable.
1580 res[cc] = '\0';
1581 cp = &res[cc];
1583 if (cc > 0 && *--cp == '\n') {
1585 * A final newline is just stripped
1587 *cp-- = '\0';
1589 while (cp >= res) {
1590 if (*cp == '\n') {
1591 *cp = ' ';
1593 cp--;
1595 break;
1597 return res;
1598 bad:
1599 res = bmake_malloc(1);
1600 *res = '\0';
1601 return res;
1605 * Error --
1606 * Print an error message given its format.
1608 * Results:
1609 * None.
1611 * Side Effects:
1612 * The message is printed.
1614 /* VARARGS */
1615 void
1616 Error(const char *fmt, ...)
1618 va_list ap;
1619 FILE *err_file;
1621 err_file = debug_file;
1622 if (err_file == stdout)
1623 err_file = stderr;
1624 (void)fflush(stdout);
1625 for (;;) {
1626 va_start(ap, fmt);
1627 fprintf(err_file, "%s: ", progname);
1628 (void)vfprintf(err_file, fmt, ap);
1629 va_end(ap);
1630 (void)fprintf(err_file, "\n");
1631 (void)fflush(err_file);
1632 if (err_file == stderr)
1633 break;
1634 err_file = stderr;
1639 * Fatal --
1640 * Produce a Fatal error message. If jobs are running, waits for them
1641 * to finish.
1643 * Results:
1644 * None
1646 * Side Effects:
1647 * The program exits
1649 /* VARARGS */
1650 void
1651 Fatal(const char *fmt, ...)
1653 va_list ap;
1655 va_start(ap, fmt);
1656 if (jobsRunning)
1657 Job_Wait();
1659 (void)fflush(stdout);
1660 (void)vfprintf(stderr, fmt, ap);
1661 va_end(ap);
1662 (void)fprintf(stderr, "\n");
1663 (void)fflush(stderr);
1665 PrintOnError(NULL, NULL);
1667 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1668 Targ_PrintGraph(2);
1669 Trace_Log(MAKEERROR, 0);
1670 exit(2); /* Not 1 so -q can distinguish error */
1674 * Punt --
1675 * Major exception once jobs are being created. Kills all jobs, prints
1676 * a message and exits.
1678 * Results:
1679 * None
1681 * Side Effects:
1682 * All children are killed indiscriminately and the program Lib_Exits
1684 /* VARARGS */
1685 void
1686 Punt(const char *fmt, ...)
1688 va_list ap;
1690 va_start(ap, fmt);
1691 (void)fflush(stdout);
1692 (void)fprintf(stderr, "%s: ", progname);
1693 (void)vfprintf(stderr, fmt, ap);
1694 va_end(ap);
1695 (void)fprintf(stderr, "\n");
1696 (void)fflush(stderr);
1698 PrintOnError(NULL, NULL);
1700 DieHorribly();
1704 * DieHorribly --
1705 * Exit without giving a message.
1707 * Results:
1708 * None
1710 * Side Effects:
1711 * A big one...
1713 void
1714 DieHorribly(void)
1716 if (jobsRunning)
1717 Job_AbortAll();
1718 if (DEBUG(GRAPH2))
1719 Targ_PrintGraph(2);
1720 Trace_Log(MAKEERROR, 0);
1721 exit(2); /* Not 1, so -q can distinguish error */
1725 * Finish --
1726 * Called when aborting due to errors in child shell to signal
1727 * abnormal exit.
1729 * Results:
1730 * None
1732 * Side Effects:
1733 * The program exits
1735 void
1736 Finish(int errors)
1737 /* number of errors encountered in Make_Make */
1739 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1743 * eunlink --
1744 * Remove a file carefully, avoiding directories.
1747 eunlink(const char *file)
1749 struct stat st;
1751 if (lstat(file, &st) == -1)
1752 return -1;
1754 if (S_ISDIR(st.st_mode)) {
1755 errno = EISDIR;
1756 return -1;
1758 return unlink(file);
1762 * execError --
1763 * Print why exec failed, avoiding stdio.
1765 void
1766 execError(const char *af, const char *av)
1768 #ifdef USE_IOVEC
1769 int i = 0;
1770 struct iovec iov[8];
1771 #define IOADD(s) \
1772 (void)(iov[i].iov_base = UNCONST(s), \
1773 iov[i].iov_len = strlen(iov[i].iov_base), \
1774 i++)
1775 #else
1776 #define IOADD(void)write(2, s, strlen(s))
1777 #endif
1779 IOADD(progname);
1780 IOADD(": ");
1781 IOADD(af);
1782 IOADD("(");
1783 IOADD(av);
1784 IOADD(") failed (");
1785 IOADD(strerror(errno));
1786 IOADD(")\n");
1788 #ifdef USE_IOVEC
1789 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1790 continue;
1791 #endif
1795 * usage --
1796 * exit with usage message
1798 static void
1799 usage(void)
1801 char *p;
1802 if ((p = strchr(progname, '[')) != NULL)
1803 *p = '\0';
1805 (void)fprintf(stderr,
1806 "usage: %s [-BeikNnqrstWwX] \n\
1807 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1808 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1809 [-V variable] [variable=value] [target ...]\n", progname);
1810 exit(2);
1815 PrintAddr(void *a, void *b)
1817 printf("%lx ", (unsigned long) a);
1818 return b ? 0 : 0;
1823 void
1824 PrintOnError(GNode *gn, const char *s)
1826 static GNode *en = NULL;
1827 char tmp[64];
1828 char *cp;
1830 if (s)
1831 printf("%s", s);
1833 printf("\n%s: stopped in %s\n", progname, curdir);
1835 if (en)
1836 return; /* we've been here! */
1837 if (gn) {
1839 * We can print this even if there is no .ERROR target.
1841 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1843 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1844 sizeof(tmp) - 1);
1845 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1846 if (cp) {
1847 if (*cp)
1848 printf("%s", cp);
1849 free(cp);
1852 * Finally, see if there is a .ERROR target, and run it if so.
1854 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1855 if (en) {
1856 en->type |= OP_SPECIAL;
1857 Compat_Make(en, en);
1861 void
1862 Main_ExportMAKEFLAGS(Boolean first)
1864 static int once = 1;
1865 char tmp[64];
1866 char *s;
1868 if (once != first)
1869 return;
1870 once = 0;
1872 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1873 sizeof(tmp));
1874 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1875 if (s && *s) {
1876 #ifdef POSIX
1877 setenv("MAKEFLAGS", s, 1);
1878 #else
1879 setenv("MAKE", s, 1);
1880 #endif
1884 char *
1885 getTmpdir(void)
1887 static char *tmpdir = NULL;
1889 if (!tmpdir) {
1890 struct stat st;
1893 * Honor $TMPDIR but only if it is valid.
1894 * Ensure it ends with /.
1896 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1897 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1898 free(tmpdir);
1899 tmpdir = bmake_strdup(_PATH_TMP);
1902 return tmpdir;
1906 * Create and open a temp file using "pattern".
1907 * If "fnamep" is provided set it to a copy of the filename created.
1908 * Otherwise unlink the file once open.
1911 mkTempFile(const char *pattern, char **fnamep)
1913 static char *tmpdir = NULL;
1914 char tfile[MAXPATHLEN];
1915 int fd;
1917 if (!pattern)
1918 pattern = TMPPAT;
1919 if (!tmpdir)
1920 tmpdir = getTmpdir();
1921 if (pattern[0] == '/') {
1922 snprintf(tfile, sizeof(tfile), "%s", pattern);
1923 } else {
1924 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1926 if ((fd = mkstemp(tfile)) < 0)
1927 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1928 if (fnamep) {
1929 *fnamep = bmake_strdup(tfile);
1930 } else {
1931 unlink(tfile); /* we just want the descriptor */
1933 return fd;
1938 * Return a Boolean based on setting of a knob.
1940 * If the knob is not set, the supplied default is the return value.
1941 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1942 * is FALSE, otherwise TRUE.
1944 Boolean
1945 getBoolean(const char *name, Boolean bf)
1947 char tmp[64];
1948 char *cp;
1950 if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1951 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1953 if (cp) {
1954 switch(*cp) {
1955 case '\0': /* not set - the default wins */
1956 break;
1957 case '0':
1958 case 'f':
1959 case 'n':
1960 bf = FALSE;
1961 break;
1962 case 'o':
1963 switch (cp[1]) {
1964 case 'f':
1965 bf = FALSE;
1966 break;
1967 default:
1968 bf = TRUE;
1969 break;
1971 break;
1972 default:
1973 bf = TRUE;
1974 break;
1976 free(cp);
1979 return (bf);