ispfw.4: Remove extra .Pp
[dragonfly.git] / contrib / bmake / main.c
blob59cbe45b5d812a9cde1b60bb265dd6ab464d5e3a
1 /* $NetBSD: main.c,v 1.250 2016/08/11 19:53:17 sjg 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.250 2016/08/11 19:53:17 sjg 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.250 2016/08/11 19:53:17 sjg 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 optional arguments
103 * for it.
105 * Fatal Print an error message and exit. Also takes
106 * a format string and arguments for it.
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and arguments for it.
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 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL)
122 #include <sys/sysctl.h>
123 #endif
124 #include <sys/utsname.h>
125 #include "wait.h"
127 #include <errno.h>
128 #include <signal.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
133 #include <ctype.h>
135 #include "make.h"
136 #include "hash.h"
137 #include "dir.h"
138 #include "job.h"
139 #include "pathnames.h"
140 #include "trace.h"
142 #ifdef USE_IOVEC
143 #include <sys/uio.h>
144 #endif
146 #ifndef DEFMAXLOCAL
147 #define DEFMAXLOCAL DEFMAXJOBS
148 #endif /* DEFMAXLOCAL */
150 #ifndef __arraycount
151 # define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
152 #endif
154 Lst create; /* Targets to be made */
155 time_t now; /* Time at start of make */
156 GNode *DEFAULT; /* .DEFAULT node */
157 Boolean allPrecious; /* .PRECIOUS given on line by itself */
159 static Boolean noBuiltins; /* -r flag */
160 static Lst makefiles; /* ordered list of makefiles to read */
161 static Boolean printVars; /* print value of one or more vars */
162 static Lst variables; /* list of variables to print */
163 int maxJobs; /* -j argument */
164 static int maxJobTokens; /* -j argument */
165 Boolean compatMake; /* -B argument */
166 int debug; /* -d argument */
167 Boolean debugVflag; /* -dV */
168 Boolean noExecute; /* -n flag */
169 Boolean noRecursiveExecute; /* -N flag */
170 Boolean keepgoing; /* -k flag */
171 Boolean queryFlag; /* -q flag */
172 Boolean touchFlag; /* -t flag */
173 Boolean enterFlag; /* -w flag */
174 Boolean enterFlagObj; /* -w and objdir != srcdir */
175 Boolean ignoreErrors; /* -i flag */
176 Boolean beSilent; /* -s flag */
177 Boolean oldVars; /* variable substitution style */
178 Boolean checkEnvFirst; /* -e flag */
179 Boolean parseWarnFatal; /* -W flag */
180 Boolean jobServer; /* -J flag */
181 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
182 Boolean varNoExportEnv; /* -X flag */
183 Boolean doing_depend; /* Set while reading .depend */
184 static Boolean jobsRunning; /* TRUE if the jobs might be running */
185 static const char * tracefile;
186 static void MainParseArgs(int, char **);
187 static int ReadMakefile(const void *, const void *);
188 static void usage(void) MAKE_ATTR_DEAD;
190 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
191 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
192 char curdir[MAXPATHLEN + 1]; /* Startup directory */
193 char *progname; /* the program name */
194 char *makeDependfile;
195 pid_t myPid;
196 int makelevel;
198 Boolean forceJobs = FALSE;
201 * On some systems MACHINE is defined as something other than
202 * what we want.
204 #ifdef FORCE_MACHINE
205 # undef MACHINE
206 # define MACHINE FORCE_MACHINE
207 #endif
209 extern Lst parseIncPath;
212 * For compatibility with the POSIX version of MAKEFLAGS that includes
213 * all the options with out -, convert flags to -f -l -a -g -s.
215 static char *
216 explode(const char *flags)
218 size_t len;
219 char *nf, *st;
220 const char *f;
222 if (flags == NULL)
223 return NULL;
225 for (f = flags; *f; f++)
226 if (!isalpha((unsigned char)*f))
227 break;
229 if (*f)
230 return bmake_strdup(flags);
232 len = strlen(flags);
233 st = nf = bmake_malloc(len * 3 + 1);
234 while (*flags) {
235 *nf++ = '-';
236 *nf++ = *flags++;
237 *nf++ = ' ';
239 *nf = '\0';
240 return st;
243 static void
244 parse_debug_options(const char *argvalue)
246 const char *modules;
247 const char *mode;
248 char *fname;
249 int len;
251 for (modules = argvalue; *modules; ++modules) {
252 switch (*modules) {
253 case 'A':
254 debug = ~0;
255 break;
256 case 'a':
257 debug |= DEBUG_ARCH;
258 break;
259 case 'C':
260 debug |= DEBUG_CWD;
261 break;
262 case 'c':
263 debug |= DEBUG_COND;
264 break;
265 case 'd':
266 debug |= DEBUG_DIR;
267 break;
268 case 'e':
269 debug |= DEBUG_ERROR;
270 break;
271 case 'f':
272 debug |= DEBUG_FOR;
273 break;
274 case 'g':
275 if (modules[1] == '1') {
276 debug |= DEBUG_GRAPH1;
277 ++modules;
279 else if (modules[1] == '2') {
280 debug |= DEBUG_GRAPH2;
281 ++modules;
283 else if (modules[1] == '3') {
284 debug |= DEBUG_GRAPH3;
285 ++modules;
287 break;
288 case 'j':
289 debug |= DEBUG_JOB;
290 break;
291 case 'l':
292 debug |= DEBUG_LOUD;
293 break;
294 case 'M':
295 debug |= DEBUG_META;
296 break;
297 case 'm':
298 debug |= DEBUG_MAKE;
299 break;
300 case 'n':
301 debug |= DEBUG_SCRIPT;
302 break;
303 case 'p':
304 debug |= DEBUG_PARSE;
305 break;
306 case 's':
307 debug |= DEBUG_SUFF;
308 break;
309 case 't':
310 debug |= DEBUG_TARG;
311 break;
312 case 'V':
313 debugVflag = TRUE;
314 break;
315 case 'v':
316 debug |= DEBUG_VAR;
317 break;
318 case 'x':
319 debug |= DEBUG_SHELL;
320 break;
321 case 'F':
322 if (debug_file != stdout && debug_file != stderr)
323 fclose(debug_file);
324 if (*++modules == '+') {
325 modules++;
326 mode = "a";
327 } else
328 mode = "w";
329 if (strcmp(modules, "stdout") == 0) {
330 debug_file = stdout;
331 goto debug_setbuf;
333 if (strcmp(modules, "stderr") == 0) {
334 debug_file = stderr;
335 goto debug_setbuf;
337 len = strlen(modules);
338 fname = malloc(len + 20);
339 memcpy(fname, modules, len + 1);
340 /* Let the filename be modified by the pid */
341 if (strcmp(fname + len - 3, ".%d") == 0)
342 snprintf(fname + len - 2, 20, "%d", getpid());
343 debug_file = fopen(fname, mode);
344 if (!debug_file) {
345 fprintf(stderr, "Cannot open debug file %s\n",
346 fname);
347 usage();
349 free(fname);
350 goto debug_setbuf;
351 default:
352 (void)fprintf(stderr,
353 "%s: illegal argument to d option -- %c\n",
354 progname, *modules);
355 usage();
358 debug_setbuf:
360 * Make the debug_file unbuffered, and make
361 * stdout line buffered (unless debugfile == stdout).
363 setvbuf(debug_file, NULL, _IONBF, 0);
364 if (debug_file != stdout) {
365 setvbuf(stdout, NULL, _IOLBF, 0);
370 * MainParseArgs --
371 * Parse a given argument vector. Called from main() and from
372 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
374 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
376 * Results:
377 * None
379 * Side Effects:
380 * Various global and local flags will be set depending on the flags
381 * given
383 static void
384 MainParseArgs(int argc, char **argv)
386 char *p;
387 int c = '?';
388 int arginc;
389 char *argvalue;
390 const char *getopt_def;
391 char *optscan;
392 Boolean inOption, dashDash = FALSE;
393 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
395 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstw"
396 /* Can't actually use getopt(3) because rescanning is not portable */
398 getopt_def = OPTFLAGS;
399 rearg:
400 inOption = FALSE;
401 optscan = NULL;
402 while(argc > 1) {
403 char *getopt_spec;
404 if(!inOption)
405 optscan = argv[1];
406 c = *optscan++;
407 arginc = 0;
408 if(inOption) {
409 if(c == '\0') {
410 ++argv;
411 --argc;
412 inOption = FALSE;
413 continue;
415 } else {
416 if (c != '-' || dashDash)
417 break;
418 inOption = TRUE;
419 c = *optscan++;
421 /* '-' found at some earlier point */
422 getopt_spec = strchr(getopt_def, c);
423 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
424 /* -<something> found, and <something> should have an arg */
425 inOption = FALSE;
426 arginc = 1;
427 argvalue = optscan;
428 if(*argvalue == '\0') {
429 if (argc < 3)
430 goto noarg;
431 argvalue = argv[2];
432 arginc = 2;
434 } else {
435 argvalue = NULL;
437 switch(c) {
438 case '\0':
439 arginc = 1;
440 inOption = FALSE;
441 break;
442 case 'B':
443 compatMake = TRUE;
444 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
445 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
446 break;
447 case 'C':
448 if (chdir(argvalue) == -1) {
449 (void)fprintf(stderr,
450 "%s: chdir %s: %s\n",
451 progname, argvalue,
452 strerror(errno));
453 exit(1);
455 if (getcwd(curdir, MAXPATHLEN) == NULL) {
456 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
457 exit(2);
459 ignorePWD = TRUE;
460 break;
461 case 'D':
462 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
463 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
464 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
465 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
466 break;
467 case 'I':
468 if (argvalue == NULL) goto noarg;
469 Parse_AddIncludeDir(argvalue);
470 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
471 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
472 break;
473 case 'J':
474 if (argvalue == NULL) goto noarg;
475 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
476 (void)fprintf(stderr,
477 "%s: internal error -- J option malformed (%s)\n",
478 progname, argvalue);
479 usage();
481 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
482 (fcntl(jp_1, F_GETFD, 0) < 0)) {
483 #if 0
484 (void)fprintf(stderr,
485 "%s: ###### warning -- J descriptors were closed!\n",
486 progname);
487 exit(2);
488 #endif
489 jp_0 = -1;
490 jp_1 = -1;
491 compatMake = TRUE;
492 } else {
493 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
494 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
495 jobServer = TRUE;
497 break;
498 case 'N':
499 noExecute = TRUE;
500 noRecursiveExecute = TRUE;
501 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
502 break;
503 case 'S':
504 keepgoing = FALSE;
505 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
506 break;
507 case 'T':
508 if (argvalue == NULL) goto noarg;
509 tracefile = bmake_strdup(argvalue);
510 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
511 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
512 break;
513 case 'V':
514 if (argvalue == NULL) goto noarg;
515 printVars = TRUE;
516 (void)Lst_AtEnd(variables, argvalue);
517 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
518 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
519 break;
520 case 'W':
521 parseWarnFatal = TRUE;
522 break;
523 case 'X':
524 varNoExportEnv = TRUE;
525 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
526 break;
527 case 'd':
528 if (argvalue == NULL) goto noarg;
529 /* If '-d-opts' don't pass to children */
530 if (argvalue[0] == '-')
531 argvalue++;
532 else {
533 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
534 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
536 parse_debug_options(argvalue);
537 break;
538 case 'e':
539 checkEnvFirst = TRUE;
540 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
541 break;
542 case 'f':
543 if (argvalue == NULL) goto noarg;
544 (void)Lst_AtEnd(makefiles, argvalue);
545 break;
546 case 'i':
547 ignoreErrors = TRUE;
548 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
549 break;
550 case 'j':
551 if (argvalue == NULL) goto noarg;
552 forceJobs = TRUE;
553 maxJobs = strtol(argvalue, &p, 0);
554 if (*p != '\0' || maxJobs < 1) {
555 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
556 progname);
557 exit(1);
559 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
560 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
561 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
562 maxJobTokens = maxJobs;
563 break;
564 case 'k':
565 keepgoing = TRUE;
566 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
567 break;
568 case 'm':
569 if (argvalue == NULL) goto noarg;
570 /* look for magic parent directory search string */
571 if (strncmp(".../", argvalue, 4) == 0) {
572 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
573 found_path, sizeof(found_path)))
574 break; /* nothing doing */
575 (void)Dir_AddDir(sysIncPath, found_path);
576 } else {
577 (void)Dir_AddDir(sysIncPath, argvalue);
579 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
580 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
581 break;
582 case 'n':
583 noExecute = TRUE;
584 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
585 break;
586 case 'q':
587 queryFlag = TRUE;
588 /* Kind of nonsensical, wot? */
589 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
590 break;
591 case 'r':
592 noBuiltins = TRUE;
593 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
594 break;
595 case 's':
596 beSilent = TRUE;
597 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
598 break;
599 case 't':
600 touchFlag = TRUE;
601 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
602 break;
603 case 'w':
604 enterFlag = TRUE;
605 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
606 break;
607 case '-':
608 dashDash = TRUE;
609 break;
610 default:
611 case '?':
612 #ifndef MAKE_NATIVE
613 fprintf(stderr, "getopt(%s) -> %d (%c)\n",
614 OPTFLAGS, c, c);
615 #endif
616 usage();
618 argv += arginc;
619 argc -= arginc;
622 oldVars = TRUE;
625 * See if the rest of the arguments are variable assignments and
626 * perform them if so. Else take them to be targets and stuff them
627 * on the end of the "create" list.
629 for (; argc > 1; ++argv, --argc)
630 if (Parse_IsVar(argv[1])) {
631 Parse_DoVar(argv[1], VAR_CMD);
632 } else {
633 if (!*argv[1])
634 Punt("illegal (null) argument.");
635 if (*argv[1] == '-' && !dashDash)
636 goto rearg;
637 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
640 return;
641 noarg:
642 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
643 progname, c);
644 usage();
648 * Main_ParseArgLine --
649 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
650 * is encountered and by main() when reading the .MAKEFLAGS envariable.
651 * Takes a line of arguments and breaks it into its
652 * component words and passes those words and the number of them to the
653 * MainParseArgs function.
654 * The line should have all its leading whitespace removed.
656 * Input:
657 * line Line to fracture
659 * Results:
660 * None
662 * Side Effects:
663 * Only those that come from the various arguments.
665 void
666 Main_ParseArgLine(const char *line)
668 char **argv; /* Manufactured argument vector */
669 int argc; /* Number of arguments in argv */
670 char *args; /* Space used by the args */
671 char *buf, *p1;
672 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
673 size_t len;
675 if (line == NULL)
676 return;
677 for (; *line == ' '; ++line)
678 continue;
679 if (!*line)
680 return;
682 #ifndef POSIX
685 * $MAKE may simply be naming the make(1) binary
687 char *cp;
689 if (!(cp = strrchr(line, '/')))
690 cp = line;
691 if ((cp = strstr(cp, "make")) &&
692 strcmp(cp, "make") == 0)
693 return;
695 #endif
696 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
697 (void)snprintf(buf, len, "%s %s", argv0, line);
698 free(p1);
700 argv = brk_string(buf, &argc, TRUE, &args);
701 if (argv == NULL) {
702 Error("Unterminated quoted string [%s]", buf);
703 free(buf);
704 return;
706 free(buf);
707 MainParseArgs(argc, argv);
709 free(args);
710 free(argv);
713 Boolean
714 Main_SetObjdir(const char *path)
716 struct stat sb;
717 char *p = NULL;
718 char buf[MAXPATHLEN + 1];
719 Boolean rc = FALSE;
721 /* expand variable substitutions */
722 if (strchr(path, '$') != 0) {
723 snprintf(buf, MAXPATHLEN, "%s", path);
724 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, VARF_WANTRES);
727 if (path[0] != '/') {
728 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
729 path = buf;
732 /* look for the directory and try to chdir there */
733 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
734 if (chdir(path)) {
735 (void)fprintf(stderr, "make warning: %s: %s.\n",
736 path, strerror(errno));
737 } else {
738 strncpy(objdir, path, MAXPATHLEN);
739 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
740 setenv("PWD", objdir, 1);
741 Dir_InitDot();
742 rc = TRUE;
743 if (enterFlag && strcmp(objdir, curdir) != 0)
744 enterFlagObj = TRUE;
748 free(p);
749 return rc;
753 * ReadAllMakefiles --
754 * wrapper around ReadMakefile() to read all.
756 * Results:
757 * TRUE if ok, FALSE on error
759 static int
760 ReadAllMakefiles(const void *p, const void *q)
762 return (ReadMakefile(p, q) == 0);
766 str2Lst_Append(Lst lp, char *str, const char *sep)
768 char *cp;
769 int n;
771 if (!sep)
772 sep = " \t";
774 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
775 (void)Lst_AtEnd(lp, cp);
776 n++;
778 return (n);
781 #ifdef SIGINFO
782 /*ARGSUSED*/
783 static void
784 siginfo(int signo MAKE_ATTR_UNUSED)
786 char dir[MAXPATHLEN];
787 char str[2 * MAXPATHLEN];
788 int len;
789 if (getcwd(dir, sizeof(dir)) == NULL)
790 return;
791 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
792 if (len > 0)
793 (void)write(STDERR_FILENO, str, (size_t)len);
795 #endif
798 * Allow makefiles some control over the mode we run in.
800 void
801 MakeMode(const char *mode)
803 char *mp = NULL;
805 if (!mode)
806 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}",
807 VAR_GLOBAL, VARF_WANTRES);
809 if (mode && *mode) {
810 if (strstr(mode, "compat")) {
811 compatMake = TRUE;
812 forceJobs = FALSE;
814 #if USE_META
815 if (strstr(mode, "meta"))
816 meta_mode_init(mode);
817 #endif
820 free(mp);
824 * main --
825 * The main function, for obvious reasons. Initializes variables
826 * and a few modules, then parses the arguments give it in the
827 * environment and on the command line. Reads the system makefile
828 * followed by either Makefile, makefile or the file given by the
829 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
830 * flags it has received by then uses either the Make or the Compat
831 * module to create the initial list of targets.
833 * Results:
834 * If -q was given, exits -1 if anything was out-of-date. Else it exits
835 * 0.
837 * Side Effects:
838 * The program exits when done. Targets are created. etc. etc. etc.
841 main(int argc, char **argv)
843 Lst targs; /* target nodes to create -- passed to Make_Init */
844 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
845 struct stat sb, sa;
846 char *p1, *path;
847 char mdpath[MAXPATHLEN];
848 #ifdef FORCE_MACHINE
849 const char *machine = FORCE_MACHINE;
850 #else
851 const char *machine = getenv("MACHINE");
852 #endif
853 const char *machine_arch = getenv("MACHINE_ARCH");
854 char *syspath = getenv("MAKESYSPATH");
855 Lst sysMkPath; /* Path of sys.mk */
856 char *cp = NULL, *start;
857 /* avoid faults on read-only strings */
858 static char defsyspath[] = _PATH_DEFSYSPATH;
859 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
860 struct timeval rightnow; /* to initialize random seed */
861 struct utsname utsname;
863 /* default to writing debug to stderr */
864 debug_file = stderr;
866 #ifdef SIGINFO
867 (void)bmake_signal(SIGINFO, siginfo);
868 #endif
870 * Set the seed to produce a different random sequence
871 * on each program execution.
873 gettimeofday(&rightnow, NULL);
874 srandom(rightnow.tv_sec + rightnow.tv_usec);
876 if ((progname = strrchr(argv[0], '/')) != NULL)
877 progname++;
878 else
879 progname = argv[0];
880 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
882 * get rid of resource limit on file descriptors
885 struct rlimit rl;
886 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
887 rl.rlim_cur != rl.rlim_max) {
888 rl.rlim_cur = rl.rlim_max;
889 (void)setrlimit(RLIMIT_NOFILE, &rl);
892 #endif
894 if (uname(&utsname) == -1) {
895 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
896 strerror(errno));
897 exit(2);
901 * Get the name of this type of MACHINE from utsname
902 * so we can share an executable for similar machines.
903 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
905 * Note that both MACHINE and MACHINE_ARCH are decided at
906 * run-time.
908 if (!machine) {
909 #ifdef MAKE_NATIVE
910 machine = utsname.machine;
911 #else
912 #ifdef MAKE_MACHINE
913 machine = MAKE_MACHINE;
914 #else
915 machine = "unknown";
916 #endif
917 #endif
920 if (!machine_arch) {
921 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL) && defined(CTL_HW) && defined(HW_MACHINE_ARCH)
922 static char machine_arch_buf[sizeof(utsname.machine)];
923 int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
924 size_t len = sizeof(machine_arch_buf);
926 if (sysctl(__DECONST(int *, mib) /* XXX */, __arraycount(mib), machine_arch_buf,
927 &len, NULL, 0) < 0) {
928 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
929 strerror(errno));
930 exit(2);
933 machine_arch = machine_arch_buf;
934 #else
935 #ifndef MACHINE_ARCH
936 #ifdef MAKE_MACHINE_ARCH
937 machine_arch = MAKE_MACHINE_ARCH;
938 #else
939 machine_arch = "unknown";
940 #endif
941 #else
942 machine_arch = MACHINE_ARCH;
943 #endif
944 #endif
947 myPid = getpid(); /* remember this for vFork() */
950 * Just in case MAKEOBJDIR wants us to do something tricky.
952 Var_Init(); /* Initialize the lists of variables for
953 * parsing arguments */
954 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
955 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
956 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
957 #ifdef MAKE_VERSION
958 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
959 #endif
960 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
962 * This is the traditional preference for makefiles.
964 #ifndef MAKEFILE_PREFERENCE_LIST
965 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
966 #endif
967 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
968 VAR_GLOBAL, 0);
969 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
971 create = Lst_Init(FALSE);
972 makefiles = Lst_Init(FALSE);
973 printVars = FALSE;
974 debugVflag = FALSE;
975 variables = Lst_Init(FALSE);
976 beSilent = FALSE; /* Print commands as executed */
977 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
978 noExecute = FALSE; /* Execute all commands */
979 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
980 keepgoing = FALSE; /* Stop on error */
981 allPrecious = FALSE; /* Remove targets when interrupted */
982 queryFlag = FALSE; /* This is not just a check-run */
983 noBuiltins = FALSE; /* Read the built-in rules */
984 touchFlag = FALSE; /* Actually update targets */
985 debug = 0; /* No debug verbosity, please. */
986 jobsRunning = FALSE;
988 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
989 maxJobTokens = maxJobs;
990 compatMake = FALSE; /* No compat mode */
991 ignorePWD = FALSE;
994 * Initialize the parsing, directory and variable modules to prepare
995 * for the reading of inclusion paths and variable settings on the
996 * command line
1000 * Initialize various variables.
1001 * MAKE also gets this name, for compatibility
1002 * .MAKEFLAGS gets set to the empty string just in case.
1003 * MFLAGS also gets initialized empty, for compatibility.
1005 Parse_Init();
1006 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1008 * Leave alone if it is an absolute path, or if it does
1009 * not contain a '/' in which case we need to find it in
1010 * the path, like execvp(3) and the shells do.
1012 p1 = argv[0];
1013 } else {
1015 * A relative path, canonicalize it.
1017 p1 = cached_realpath(argv[0], mdpath);
1018 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1019 p1 = argv[0]; /* realpath failed */
1022 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
1023 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
1024 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
1025 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
1026 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
1027 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
1028 /* some makefiles need to know this */
1029 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
1032 * Set some other useful macros
1035 char tmp[64], *ep;
1037 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1038 if (makelevel < 0)
1039 makelevel = 0;
1040 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1041 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
1042 snprintf(tmp, sizeof(tmp), "%u", myPid);
1043 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
1044 snprintf(tmp, sizeof(tmp), "%u", getppid());
1045 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
1046 Var_Set(".MAKE.BUILT.BY", CCVER, VAR_GLOBAL, 0);
1047 Var_Set(".MAKE.DF.VERSION", DFVER, VAR_GLOBAL, 0);
1048 Var_Set(".MAKE.DF.OSREL", OSREL, VAR_GLOBAL, 0);
1050 if (makelevel > 0) {
1051 char pn[1024];
1052 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1053 progname = bmake_strdup(pn);
1056 #ifdef USE_META
1057 meta_init();
1058 #endif
1060 * First snag any flags out of the MAKE environment variable.
1061 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1062 * in a different format).
1064 #ifdef POSIX
1065 p1 = explode(getenv("MAKEFLAGS"));
1066 Main_ParseArgLine(p1);
1067 free(p1);
1068 #else
1069 Main_ParseArgLine(getenv("MAKE"));
1070 #endif
1073 * Find where we are (now).
1074 * We take care of PWD for the automounter below...
1076 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1077 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1078 progname, strerror(errno));
1079 exit(2);
1082 MainParseArgs(argc, argv);
1084 if (enterFlag)
1085 printf("%s: Entering directory `%s'\n", progname, curdir);
1088 * Verify that cwd is sane.
1090 if (stat(curdir, &sa) == -1) {
1091 (void)fprintf(stderr, "%s: %s: %s.\n",
1092 progname, curdir, strerror(errno));
1093 exit(2);
1097 * All this code is so that we know where we are when we start up
1098 * on a different machine with pmake.
1099 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1100 * since the value of curdir can vary depending on how we got
1101 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1102 * or via subdir.mk in which case its likely a shell which does
1103 * not provide it.
1104 * So, to stop it breaking this case only, we ignore PWD if
1105 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1107 #ifndef NO_PWD_OVERRIDE
1108 if (!ignorePWD) {
1109 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1111 if ((pwd = getenv("PWD")) != NULL &&
1112 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1113 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1114 VAR_CMD, &ptmp2);
1116 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1117 if (stat(pwd, &sb) == 0 &&
1118 sa.st_ino == sb.st_ino &&
1119 sa.st_dev == sb.st_dev)
1120 (void)strncpy(curdir, pwd, MAXPATHLEN);
1123 free(ptmp1);
1124 free(ptmp2);
1126 #endif
1127 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1130 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1131 * MAKEOBJDIR is set in the environment, try only that value
1132 * and fall back to .CURDIR if it does not exist.
1134 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1135 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1136 * of these paths exist, just use .CURDIR.
1138 Dir_Init(curdir);
1139 (void)Main_SetObjdir(curdir);
1141 if ((path = Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &p1)) != NULL) {
1142 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1143 (void)Main_SetObjdir(mdpath);
1144 free(p1);
1145 } else if ((path = Var_Value("MAKEOBJDIR", VAR_CMD, &p1)) != NULL) {
1146 (void)Main_SetObjdir(path);
1147 free(p1);
1148 } else {
1149 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1150 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1151 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1152 _PATH_OBJDIRPREFIX, curdir);
1153 (void)Main_SetObjdir(mdpath);
1158 * Initialize archive, target and suffix modules in preparation for
1159 * parsing the makefile(s)
1161 Arch_Init();
1162 Targ_Init();
1163 Suff_Init();
1164 Trace_Init(tracefile);
1166 DEFAULT = NULL;
1167 (void)time(&now);
1169 Trace_Log(MAKESTART, NULL);
1172 * Set up the .TARGETS variable to contain the list of targets to be
1173 * created. If none specified, make the variable empty -- the parser
1174 * will fill the thing in with the default or .MAIN target.
1176 if (!Lst_IsEmpty(create)) {
1177 LstNode ln;
1179 for (ln = Lst_First(create); ln != NULL;
1180 ln = Lst_Succ(ln)) {
1181 char *name = (char *)Lst_Datum(ln);
1183 Var_Append(".TARGETS", name, VAR_GLOBAL);
1185 } else
1186 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1190 * If no user-supplied system path was given (through the -m option)
1191 * add the directories from the DEFSYSPATH (more than one may be given
1192 * as dir1:...:dirn) to the system include path.
1194 if (syspath == NULL || *syspath == '\0')
1195 syspath = defsyspath;
1196 else
1197 syspath = bmake_strdup(syspath);
1199 for (start = syspath; *start != '\0'; start = cp) {
1200 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1201 continue;
1202 if (*cp == ':') {
1203 *cp++ = '\0';
1205 /* look for magic parent directory search string */
1206 if (strncmp(".../", start, 4) != 0) {
1207 (void)Dir_AddDir(defIncPath, start);
1208 } else {
1209 if (Dir_FindHereOrAbove(curdir, start+4,
1210 found_path, sizeof(found_path))) {
1211 (void)Dir_AddDir(defIncPath, found_path);
1215 if (syspath != defsyspath)
1216 free(syspath);
1219 * Read in the built-in rules first, followed by the specified
1220 * makefile, if it was (makefile != NULL), or the default
1221 * makefile and Makefile, in that order, if it wasn't.
1223 if (!noBuiltins) {
1224 LstNode ln;
1226 sysMkPath = Lst_Init(FALSE);
1227 Dir_Expand(_PATH_DEFSYSMK,
1228 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1229 sysMkPath);
1230 if (Lst_IsEmpty(sysMkPath))
1231 Fatal("%s: no system rules (%s).", progname,
1232 _PATH_DEFSYSMK);
1233 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1234 if (ln == NULL)
1235 Fatal("%s: cannot open %s.", progname,
1236 (char *)Lst_Datum(ln));
1239 if (!Lst_IsEmpty(makefiles)) {
1240 LstNode ln;
1242 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1243 if (ln != NULL)
1244 Fatal("%s: cannot open %s.", progname,
1245 (char *)Lst_Datum(ln));
1246 } else {
1247 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1248 VAR_CMD, VARF_WANTRES);
1249 if (p1) {
1250 (void)str2Lst_Append(makefiles, p1, NULL);
1251 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1252 free(p1);
1256 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1257 if (!noBuiltins || !printVars) {
1258 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1259 VAR_CMD, VARF_WANTRES);
1260 doing_depend = TRUE;
1261 (void)ReadMakefile(makeDependfile, NULL);
1262 doing_depend = FALSE;
1265 if (enterFlagObj)
1266 printf("%s: Entering directory `%s'\n", progname, objdir);
1268 MakeMode(NULL);
1270 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1271 free(p1);
1273 if (!forceJobs && !compatMake &&
1274 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1275 char *value;
1276 int n;
1278 value = Var_Subst(NULL, "${.MAKE.JOBS}", VAR_GLOBAL, VARF_WANTRES);
1279 n = strtol(value, NULL, 0);
1280 if (n < 1) {
1281 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1282 progname);
1283 exit(1);
1285 if (n != maxJobs) {
1286 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1287 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1289 maxJobs = n;
1290 maxJobTokens = maxJobs;
1291 forceJobs = TRUE;
1292 free(value);
1296 * Be compatible if user did not specify -j and did not explicitly
1297 * turned compatibility on
1299 if (!compatMake && !forceJobs) {
1300 compatMake = TRUE;
1303 if (!compatMake)
1304 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1305 if (DEBUG(JOB))
1306 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1307 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1309 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1312 * For compatibility, look at the directories in the VPATH variable
1313 * and add them to the search path, if the variable is defined. The
1314 * variable's value is in the same format as the PATH envariable, i.e.
1315 * <directory>:<directory>:<directory>...
1317 if (Var_Exists("VPATH", VAR_CMD)) {
1318 char *vpath, savec;
1320 * GCC stores string constants in read-only memory, but
1321 * Var_Subst will want to write this thing, so store it
1322 * in an array
1324 static char VPATH[] = "${VPATH}";
1326 vpath = Var_Subst(NULL, VPATH, VAR_CMD, VARF_WANTRES);
1327 path = vpath;
1328 do {
1329 /* skip to end of directory */
1330 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1331 continue;
1332 /* Save terminator character so know when to stop */
1333 savec = *cp;
1334 *cp = '\0';
1335 /* Add directory to search path */
1336 (void)Dir_AddDir(dirSearchPath, path);
1337 *cp = savec;
1338 path = cp + 1;
1339 } while (savec == ':');
1340 free(vpath);
1344 * Now that all search paths have been read for suffixes et al, it's
1345 * time to add the default search path to their lists...
1347 Suff_DoPaths();
1350 * Propagate attributes through :: dependency lists.
1352 Targ_Propagate();
1354 /* print the initial graph, if the user requested it */
1355 if (DEBUG(GRAPH1))
1356 Targ_PrintGraph(1);
1358 /* print the values of any variables requested by the user */
1359 if (printVars) {
1360 LstNode ln;
1361 Boolean expandVars;
1363 if (debugVflag)
1364 expandVars = FALSE;
1365 else
1366 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1367 for (ln = Lst_First(variables); ln != NULL;
1368 ln = Lst_Succ(ln)) {
1369 char *var = (char *)Lst_Datum(ln);
1370 char *value;
1372 if (strchr(var, '$')) {
1373 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL,
1374 VARF_WANTRES);
1375 } else if (expandVars) {
1376 char tmp[128];
1378 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1379 Fatal("%s: variable name too big: %s",
1380 progname, var);
1381 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL,
1382 VARF_WANTRES);
1383 } else {
1384 value = Var_Value(var, VAR_GLOBAL, &p1);
1386 printf("%s\n", value ? value : "");
1387 free(p1);
1389 } else {
1391 * Have now read the entire graph and need to make a list of
1392 * targets to create. If none was given on the command line,
1393 * we consult the parsing module to find the main target(s)
1394 * to create.
1396 if (Lst_IsEmpty(create))
1397 targs = Parse_MainName();
1398 else
1399 targs = Targ_FindList(create, TARG_CREATE);
1401 if (!compatMake) {
1403 * Initialize job module before traversing the graph
1404 * now that any .BEGIN and .END targets have been read.
1405 * This is done only if the -q flag wasn't given
1406 * (to prevent the .BEGIN from being executed should
1407 * it exist).
1409 if (!queryFlag) {
1410 Job_Init();
1411 jobsRunning = TRUE;
1414 /* Traverse the graph, checking on all the targets */
1415 outOfDate = Make_Run(targs);
1416 } else {
1418 * Compat_Init will take care of creating all the
1419 * targets as well as initializing the module.
1421 Compat_Run(targs);
1425 #ifdef CLEANUP
1426 Lst_Destroy(targs, NULL);
1427 Lst_Destroy(variables, NULL);
1428 Lst_Destroy(makefiles, NULL);
1429 Lst_Destroy(create, (FreeProc *)free);
1430 #endif
1432 /* print the graph now it's been processed if the user requested it */
1433 if (DEBUG(GRAPH2))
1434 Targ_PrintGraph(2);
1436 Trace_Log(MAKEEND, 0);
1438 if (enterFlagObj)
1439 printf("%s: Leaving directory `%s'\n", progname, objdir);
1440 if (enterFlag)
1441 printf("%s: Leaving directory `%s'\n", progname, curdir);
1443 #ifdef USE_META
1444 meta_finish();
1445 #endif
1446 Suff_End();
1447 Targ_End();
1448 Arch_End();
1449 Var_End();
1450 Parse_End();
1451 Dir_End();
1452 Job_End();
1453 Trace_End();
1455 return outOfDate ? 1 : 0;
1459 * ReadMakefile --
1460 * Open and parse the given makefile.
1462 * Results:
1463 * 0 if ok. -1 if couldn't open file.
1465 * Side Effects:
1466 * lots
1468 static int
1469 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1471 const char *fname = p; /* makefile to read */
1472 int fd;
1473 size_t len = MAXPATHLEN;
1474 char *name, *path = bmake_malloc(len);
1476 if (!strcmp(fname, "-")) {
1477 Parse_File(NULL /*stdin*/, -1);
1478 Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1479 } else {
1480 /* if we've chdir'd, rebuild the path name */
1481 if (strcmp(curdir, objdir) && *fname != '/') {
1482 size_t plen = strlen(curdir) + strlen(fname) + 2;
1483 if (len < plen)
1484 path = bmake_realloc(path, len = 2 * plen);
1486 (void)snprintf(path, len, "%s/%s", curdir, fname);
1487 fd = open(path, O_RDONLY);
1488 if (fd != -1) {
1489 fname = path;
1490 goto found;
1493 /* If curdir failed, try objdir (ala .depend) */
1494 plen = strlen(objdir) + strlen(fname) + 2;
1495 if (len < plen)
1496 path = bmake_realloc(path, len = 2 * plen);
1497 (void)snprintf(path, len, "%s/%s", objdir, fname);
1498 fd = open(path, O_RDONLY);
1499 if (fd != -1) {
1500 fname = path;
1501 goto found;
1503 } else {
1504 fd = open(fname, O_RDONLY);
1505 if (fd != -1)
1506 goto found;
1508 /* look in -I and system include directories. */
1509 name = Dir_FindFile(fname, parseIncPath);
1510 if (!name)
1511 name = Dir_FindFile(fname,
1512 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1513 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1514 free(name);
1515 free(path);
1516 return(-1);
1518 fname = name;
1520 * set the MAKEFILE variable desired by System V fans -- the
1521 * placement of the setting here means it gets set to the last
1522 * makefile specified, as it is set by SysV make.
1524 found:
1525 if (!doing_depend)
1526 Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1527 Parse_File(fname, fd);
1529 free(path);
1530 return(0);
1536 * Cmd_Exec --
1537 * Execute the command in cmd, and return the output of that command
1538 * in a string.
1540 * Results:
1541 * A string containing the output of the command, or the empty string
1542 * If errnum is not NULL, it contains the reason for the command failure
1544 * Side Effects:
1545 * The string must be freed by the caller.
1547 char *
1548 Cmd_Exec(const char *cmd, const char **errnum)
1550 const char *args[4]; /* Args for invoking the shell */
1551 int fds[2]; /* Pipe streams */
1552 int cpid; /* Child PID */
1553 int pid; /* PID from wait() */
1554 char *res; /* result */
1555 WAIT_T status; /* command exit status */
1556 Buffer buf; /* buffer to store the result */
1557 char *cp;
1558 int cc; /* bytes read, or -1 */
1559 int savederr; /* saved errno */
1562 *errnum = NULL;
1564 if (!shellName)
1565 Shell_Init();
1567 * Set up arguments for shell
1569 args[0] = shellName;
1570 args[1] = "-c";
1571 args[2] = cmd;
1572 args[3] = NULL;
1575 * Open a pipe for fetching its output
1577 if (pipe(fds) == -1) {
1578 *errnum = "Couldn't create pipe for \"%s\"";
1579 goto bad;
1583 * Fork
1585 switch (cpid = vFork()) {
1586 case 0:
1588 * Close input side of pipe
1590 (void)close(fds[0]);
1593 * Duplicate the output stream to the shell's output, then
1594 * shut the extra thing down. Note we don't fetch the error
1595 * stream...why not? Why?
1597 (void)dup2(fds[1], 1);
1598 (void)close(fds[1]);
1600 Var_ExportVars();
1602 (void)execv(shellPath, UNCONST(args));
1603 _exit(1);
1604 /*NOTREACHED*/
1606 case -1:
1607 *errnum = "Couldn't exec \"%s\"";
1608 goto bad;
1610 default:
1612 * No need for the writing half
1614 (void)close(fds[1]);
1616 savederr = 0;
1617 Buf_Init(&buf, 0);
1619 do {
1620 char result[BUFSIZ];
1621 cc = read(fds[0], result, sizeof(result));
1622 if (cc > 0)
1623 Buf_AddBytes(&buf, cc, result);
1625 while (cc > 0 || (cc == -1 && errno == EINTR));
1626 if (cc == -1)
1627 savederr = errno;
1630 * Close the input side of the pipe.
1632 (void)close(fds[0]);
1635 * Wait for the process to exit.
1637 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1638 JobReapChild(pid, status, FALSE);
1639 continue;
1641 cc = Buf_Size(&buf);
1642 res = Buf_Destroy(&buf, FALSE);
1644 if (savederr != 0)
1645 *errnum = "Couldn't read shell's output for \"%s\"";
1647 if (WIFSIGNALED(status))
1648 *errnum = "\"%s\" exited on a signal";
1649 else if (WEXITSTATUS(status) != 0)
1650 *errnum = "\"%s\" returned non-zero status";
1653 * Null-terminate the result, convert newlines to spaces and
1654 * install it in the variable.
1656 res[cc] = '\0';
1657 cp = &res[cc];
1659 if (cc > 0 && *--cp == '\n') {
1661 * A final newline is just stripped
1663 *cp-- = '\0';
1665 while (cp >= res) {
1666 if (*cp == '\n') {
1667 *cp = ' ';
1669 cp--;
1671 break;
1673 return res;
1674 bad:
1675 res = bmake_malloc(1);
1676 *res = '\0';
1677 return res;
1681 * Error --
1682 * Print an error message given its format.
1684 * Results:
1685 * None.
1687 * Side Effects:
1688 * The message is printed.
1690 /* VARARGS */
1691 void
1692 Error(const char *fmt, ...)
1694 va_list ap;
1695 FILE *err_file;
1697 err_file = debug_file;
1698 if (err_file == stdout)
1699 err_file = stderr;
1700 (void)fflush(stdout);
1701 for (;;) {
1702 va_start(ap, fmt);
1703 fprintf(err_file, "%s: ", progname);
1704 (void)vfprintf(err_file, fmt, ap);
1705 va_end(ap);
1706 (void)fprintf(err_file, "\n");
1707 (void)fflush(err_file);
1708 if (err_file == stderr)
1709 break;
1710 err_file = stderr;
1715 * Fatal --
1716 * Produce a Fatal error message. If jobs are running, waits for them
1717 * to finish.
1719 * Results:
1720 * None
1722 * Side Effects:
1723 * The program exits
1725 /* VARARGS */
1726 void
1727 Fatal(const char *fmt, ...)
1729 va_list ap;
1731 va_start(ap, fmt);
1732 if (jobsRunning)
1733 Job_Wait();
1735 (void)fflush(stdout);
1736 (void)vfprintf(stderr, fmt, ap);
1737 va_end(ap);
1738 (void)fprintf(stderr, "\n");
1739 (void)fflush(stderr);
1741 PrintOnError(NULL, NULL);
1743 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1744 Targ_PrintGraph(2);
1745 Trace_Log(MAKEERROR, 0);
1746 exit(2); /* Not 1 so -q can distinguish error */
1750 * Punt --
1751 * Major exception once jobs are being created. Kills all jobs, prints
1752 * a message and exits.
1754 * Results:
1755 * None
1757 * Side Effects:
1758 * All children are killed indiscriminately and the program Lib_Exits
1760 /* VARARGS */
1761 void
1762 Punt(const char *fmt, ...)
1764 va_list ap;
1766 va_start(ap, fmt);
1767 (void)fflush(stdout);
1768 (void)fprintf(stderr, "%s: ", progname);
1769 (void)vfprintf(stderr, fmt, ap);
1770 va_end(ap);
1771 (void)fprintf(stderr, "\n");
1772 (void)fflush(stderr);
1774 PrintOnError(NULL, NULL);
1776 DieHorribly();
1780 * DieHorribly --
1781 * Exit without giving a message.
1783 * Results:
1784 * None
1786 * Side Effects:
1787 * A big one...
1789 void
1790 DieHorribly(void)
1792 if (jobsRunning)
1793 Job_AbortAll();
1794 if (DEBUG(GRAPH2))
1795 Targ_PrintGraph(2);
1796 Trace_Log(MAKEERROR, 0);
1797 exit(2); /* Not 1, so -q can distinguish error */
1801 * Finish --
1802 * Called when aborting due to errors in child shell to signal
1803 * abnormal exit.
1805 * Results:
1806 * None
1808 * Side Effects:
1809 * The program exits
1811 void
1812 Finish(int errors)
1813 /* number of errors encountered in Make_Make */
1815 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1819 * eunlink --
1820 * Remove a file carefully, avoiding directories.
1823 eunlink(const char *file)
1825 struct stat st;
1827 if (lstat(file, &st) == -1)
1828 return -1;
1830 if (S_ISDIR(st.st_mode)) {
1831 errno = EISDIR;
1832 return -1;
1834 return unlink(file);
1838 * execError --
1839 * Print why exec failed, avoiding stdio.
1841 void
1842 execError(const char *af, const char *av)
1844 #ifdef USE_IOVEC
1845 int i = 0;
1846 struct iovec iov[8];
1847 #define IOADD(s) \
1848 (void)(iov[i].iov_base = UNCONST(s), \
1849 iov[i].iov_len = strlen(iov[i].iov_base), \
1850 i++)
1851 #else
1852 #define IOADD(s) (void)write(2, s, strlen(s))
1853 #endif
1855 IOADD(progname);
1856 IOADD(": ");
1857 IOADD(af);
1858 IOADD("(");
1859 IOADD(av);
1860 IOADD(") failed (");
1861 IOADD(strerror(errno));
1862 IOADD(")\n");
1864 #ifdef USE_IOVEC
1865 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1866 continue;
1867 #endif
1871 * usage --
1872 * exit with usage message
1874 static void
1875 usage(void)
1877 char *p;
1878 if ((p = strchr(progname, '[')) != NULL)
1879 *p = '\0';
1881 (void)fprintf(stderr,
1882 "usage: %s [-BeikNnqrstWwX] \n\
1883 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1884 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1885 [-V variable] [variable=value] [target ...]\n", progname);
1886 exit(2);
1891 * realpath(3) can get expensive, cache results...
1893 char *
1894 cached_realpath(const char *pathname, char *resolved)
1896 static GNode *cache;
1897 char *rp, *cp;
1899 if (!pathname || !pathname[0])
1900 return NULL;
1902 if (!cache) {
1903 cache = Targ_NewGN("Realpath");
1904 #ifndef DEBUG_REALPATH_CACHE
1905 cache->flags = INTERNAL;
1906 #endif
1909 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
1910 /* a hit */
1911 strlcpy(resolved, rp, MAXPATHLEN);
1912 } else if ((rp = realpath(pathname, resolved)) != NULL) {
1913 Var_Set(pathname, rp, cache, 0);
1915 free(cp);
1916 return rp ? resolved : NULL;
1920 PrintAddr(void *a, void *b)
1922 printf("%lx ", (unsigned long) a);
1923 return b ? 0 : 0;
1927 static int
1928 addErrorCMD(void *cmdp, void __unused *gnp)
1930 if (cmdp == NULL)
1931 return 1; /* stop */
1932 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
1933 return 0;
1936 void
1937 PrintOnError(GNode *gn, const char *s)
1939 static GNode *en = NULL;
1940 char tmp[64];
1941 char *cp;
1943 if (s)
1944 printf("%s", s);
1946 printf("\n%s: stopped in %s\n", progname, curdir);
1948 if (en)
1949 return; /* we've been here! */
1950 if (gn) {
1952 * We can print this even if there is no .ERROR target.
1954 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1955 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
1956 Lst_ForEach(gn->commands, addErrorCMD, gn);
1958 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1959 sizeof(tmp) - 1);
1960 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
1961 if (cp) {
1962 if (*cp)
1963 printf("%s", cp);
1964 free(cp);
1966 fflush(stdout);
1969 * Finally, see if there is a .ERROR target, and run it if so.
1971 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1972 if (en) {
1973 en->type |= OP_SPECIAL;
1974 Compat_Make(en, en);
1978 void
1979 Main_ExportMAKEFLAGS(Boolean first)
1981 static int once = 1;
1982 char tmp[64];
1983 char *s;
1985 if (once != first)
1986 return;
1987 once = 0;
1989 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1990 sizeof(tmp));
1991 s = Var_Subst(NULL, tmp, VAR_CMD, VARF_WANTRES);
1992 if (s && *s) {
1993 #ifdef POSIX
1994 setenv("MAKEFLAGS", s, 1);
1995 #else
1996 setenv("MAKE", s, 1);
1997 #endif
2001 char *
2002 getTmpdir(void)
2004 static char *tmpdir = NULL;
2006 if (!tmpdir) {
2007 struct stat st;
2010 * Honor $TMPDIR but only if it is valid.
2011 * Ensure it ends with /.
2013 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2014 VARF_WANTRES);
2015 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2016 free(tmpdir);
2017 tmpdir = bmake_strdup(_PATH_TMP);
2020 return tmpdir;
2024 * Create and open a temp file using "pattern".
2025 * If "fnamep" is provided set it to a copy of the filename created.
2026 * Otherwise unlink the file once open.
2029 mkTempFile(const char *pattern, char **fnamep)
2031 static char *tmpdir = NULL;
2032 char tfile[MAXPATHLEN];
2033 int fd;
2035 if (!pattern)
2036 pattern = TMPPAT;
2037 if (!tmpdir)
2038 tmpdir = getTmpdir();
2039 if (pattern[0] == '/') {
2040 snprintf(tfile, sizeof(tfile), "%s", pattern);
2041 } else {
2042 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2044 if ((fd = mkstemp(tfile)) < 0)
2045 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2046 if (fnamep) {
2047 *fnamep = bmake_strdup(tfile);
2048 } else {
2049 unlink(tfile); /* we just want the descriptor */
2051 return fd;
2055 * Convert a string representation of a boolean.
2056 * Anything that looks like "No", "False", "Off", "0" etc,
2057 * is FALSE, otherwise TRUE.
2059 Boolean
2060 s2Boolean(const char *s, Boolean bf)
2062 if (s) {
2063 switch(*s) {
2064 case '\0': /* not set - the default wins */
2065 break;
2066 case '0':
2067 case 'F':
2068 case 'f':
2069 case 'N':
2070 case 'n':
2071 bf = FALSE;
2072 break;
2073 case 'O':
2074 case 'o':
2075 switch (s[1]) {
2076 case 'F':
2077 case 'f':
2078 bf = FALSE;
2079 break;
2080 default:
2081 bf = TRUE;
2082 break;
2084 break;
2085 default:
2086 bf = TRUE;
2087 break;
2090 return (bf);
2094 * Return a Boolean based on setting of a knob.
2096 * If the knob is not set, the supplied default is the return value.
2097 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2098 * is FALSE, otherwise TRUE.
2100 Boolean
2101 getBoolean(const char *name, Boolean bf)
2103 char tmp[64];
2104 char *cp;
2106 if (snprintf(tmp, sizeof(tmp), "${%s:U:tl}", name) < (int)(sizeof(tmp))) {
2107 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2109 if (cp) {
2110 bf = s2Boolean(cp, bf);
2111 free(cp);
2114 return (bf);