]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bmake/main.c
Update to 9.8.4-P2
[FreeBSD/FreeBSD.git] / contrib / bmake / main.c
1 /*      $NetBSD: main.c,v 1.205 2013/01/26 15:53:00 christos Exp $      */
2
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. 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.
21  *
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.
33  */
34
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
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.
57  *
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.
69  */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.205 2013/01/26 15:53:00 christos 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 */
79
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.205 2013/01/26 15:53:00 christos Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
88
89 /*-
90  * main.c --
91  *      The main file for this entire program. Exit routines etc
92  *      reside here.
93  *
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.
99  *
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.
104  *
105  *      Fatal                   Print an error message and exit. Also takes
106  *                              a format string and two arguments.
107  *
108  *      Punt                    Aborts all jobs and exits with a message. Also
109  *                              takes a format string and two arguments.
110  *
111  *      Finish                  Finish things up by printing the number of
112  *                              errors which occurred, as passed to it, and
113  *                              exiting.
114  */
115
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <signal.h>
121 #include <sys/stat.h>
122 #ifdef MAKE_NATIVE
123 #include <sys/utsname.h>
124 #endif
125 #include "wait.h"
126
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
133
134 #include "make.h"
135 #include "hash.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "pathnames.h"
139 #include "trace.h"
140
141 #ifdef USE_IOVEC
142 #include <sys/uio.h>
143 #endif
144
145 #ifndef DEFMAXLOCAL
146 #define DEFMAXLOCAL DEFMAXJOBS
147 #endif  /* DEFMAXLOCAL */
148
149 Lst                     create;         /* Targets to be made */
150 time_t                  now;            /* Time at start of make */
151 GNode                   *DEFAULT;       /* .DEFAULT node */
152 Boolean                 allPrecious;    /* .PRECIOUS given on line by itself */
153
154 static Boolean          noBuiltins;     /* -r flag */
155 static Lst              makefiles;      /* ordered list of makefiles to read */
156 static Boolean          printVars;      /* print value of one or more vars */
157 static Lst              variables;      /* list of variables to print */
158 int                     maxJobs;        /* -j argument */
159 static int              maxJobTokens;   /* -j argument */
160 Boolean                 compatMake;     /* -B argument */
161 int                     debug;          /* -d argument */
162 Boolean                 debugVflag;     /* -dV */
163 Boolean                 noExecute;      /* -n flag */
164 Boolean                 noRecursiveExecute;     /* -N flag */
165 Boolean                 keepgoing;      /* -k flag */
166 Boolean                 queryFlag;      /* -q flag */
167 Boolean                 touchFlag;      /* -t flag */
168 Boolean                 ignoreErrors;   /* -i flag */
169 Boolean                 beSilent;       /* -s flag */
170 Boolean                 oldVars;        /* variable substitution style */
171 Boolean                 checkEnvFirst;  /* -e flag */
172 Boolean                 parseWarnFatal; /* -W flag */
173 Boolean                 jobServer;      /* -J flag */
174 static int jp_0 = -1, jp_1 = -1;        /* ends of parent job pipe */
175 Boolean                 varNoExportEnv; /* -X flag */
176 Boolean                 doing_depend;   /* Set while reading .depend */
177 static Boolean          jobsRunning;    /* TRUE if the jobs might be running */
178 static const char *     tracefile;
179 static void             MainParseArgs(int, char **);
180 static int              ReadMakefile(const void *, const void *);
181 static void             usage(void) MAKE_ATTR_DEAD;
182
183 static Boolean          ignorePWD;      /* if we use -C, PWD is meaningless */
184 static char objdir[MAXPATHLEN + 1];     /* where we chdir'ed to */
185 char curdir[MAXPATHLEN + 1];            /* Startup directory */
186 char *progname;                         /* the program name */
187 char *makeDependfile;
188 pid_t myPid;
189
190 Boolean forceJobs = FALSE;
191
192 /*
193  * On some systems MACHINE is defined as something other than
194  * what we want.
195  */
196 #ifdef FORCE_MACHINE
197 # undef MACHINE
198 # define MACHINE FORCE_MACHINE
199 #endif
200
201 extern Lst parseIncPath;
202
203 static void
204 parse_debug_options(const char *argvalue)
205 {
206         const char *modules;
207         const char *mode;
208         char *fname;
209         int len;
210
211         for (modules = argvalue; *modules; ++modules) {
212                 switch (*modules) {
213                 case 'A':
214                         debug = ~0;
215                         break;
216                 case 'a':
217                         debug |= DEBUG_ARCH;
218                         break;
219                 case 'C':
220                         debug |= DEBUG_CWD;
221                         break;
222                 case 'c':
223                         debug |= DEBUG_COND;
224                         break;
225                 case 'd':
226                         debug |= DEBUG_DIR;
227                         break;
228                 case 'e':
229                         debug |= DEBUG_ERROR;
230                         break;
231                 case 'f':
232                         debug |= DEBUG_FOR;
233                         break;
234                 case 'g':
235                         if (modules[1] == '1') {
236                                 debug |= DEBUG_GRAPH1;
237                                 ++modules;
238                         }
239                         else if (modules[1] == '2') {
240                                 debug |= DEBUG_GRAPH2;
241                                 ++modules;
242                         }
243                         else if (modules[1] == '3') {
244                                 debug |= DEBUG_GRAPH3;
245                                 ++modules;
246                         }
247                         break;
248                 case 'j':
249                         debug |= DEBUG_JOB;
250                         break;
251                 case 'l':
252                         debug |= DEBUG_LOUD;
253                         break;
254                 case 'M':
255                         debug |= DEBUG_META;
256                         break;
257                 case 'm':
258                         debug |= DEBUG_MAKE;
259                         break;
260                 case 'n':
261                         debug |= DEBUG_SCRIPT;
262                         break;
263                 case 'p':
264                         debug |= DEBUG_PARSE;
265                         break;
266                 case 's':
267                         debug |= DEBUG_SUFF;
268                         break;
269                 case 't':
270                         debug |= DEBUG_TARG;
271                         break;
272                 case 'V':
273                         debugVflag = TRUE;
274                         break;
275                 case 'v':
276                         debug |= DEBUG_VAR;
277                         break;
278                 case 'x':
279                         debug |= DEBUG_SHELL;
280                         break;
281                 case 'F':
282                         if (debug_file != stdout && debug_file != stderr)
283                                 fclose(debug_file);
284                         if (*++modules == '+') {
285                                 modules++;
286                                 mode = "a";
287                         } else
288                                 mode = "w";
289                         if (strcmp(modules, "stdout") == 0) {
290                                 debug_file = stdout;
291                                 goto debug_setbuf;
292                         }
293                         if (strcmp(modules, "stderr") == 0) {
294                                 debug_file = stderr;
295                                 goto debug_setbuf;
296                         }
297                         len = strlen(modules);
298                         fname = malloc(len + 20);
299                         memcpy(fname, modules, len + 1);
300                         /* Let the filename be modified by the pid */
301                         if (strcmp(fname + len - 3, ".%d") == 0)
302                                 snprintf(fname + len - 2, 20, "%d", getpid());
303                         debug_file = fopen(fname, mode);
304                         if (!debug_file) {
305                                 fprintf(stderr, "Cannot open debug file %s\n",
306                                     fname);
307                                 usage();
308                         }
309                         free(fname);
310                         goto debug_setbuf;
311                 default:
312                         (void)fprintf(stderr,
313                             "%s: illegal argument to d option -- %c\n",
314                             progname, *modules);
315                         usage();
316                 }
317         }
318 debug_setbuf:
319         /*
320          * Make the debug_file unbuffered, and make
321          * stdout line buffered (unless debugfile == stdout).
322          */
323         setvbuf(debug_file, NULL, _IONBF, 0);
324         if (debug_file != stdout) {
325                 setvbuf(stdout, NULL, _IOLBF, 0);
326         }
327 }
328
329 /*-
330  * MainParseArgs --
331  *      Parse a given argument vector. Called from main() and from
332  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
333  *
334  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
335  *
336  * Results:
337  *      None
338  *
339  * Side Effects:
340  *      Various global and local flags will be set depending on the flags
341  *      given
342  */
343 static void
344 MainParseArgs(int argc, char **argv)
345 {
346         char *p;
347         int c = '?';
348         int arginc;
349         char *argvalue;
350         const char *getopt_def;
351         char *optscan;
352         Boolean inOption, dashDash = FALSE;
353         char found_path[MAXPATHLEN + 1];        /* for searching for sys.mk */
354
355 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrst"
356 /* Can't actually use getopt(3) because rescanning is not portable */
357
358         getopt_def = OPTFLAGS;
359 rearg:  
360         inOption = FALSE;
361         optscan = NULL;
362         while(argc > 1) {
363                 char *getopt_spec;
364                 if(!inOption)
365                         optscan = argv[1];
366                 c = *optscan++;
367                 arginc = 0;
368                 if(inOption) {
369                         if(c == '\0') {
370                                 ++argv;
371                                 --argc;
372                                 inOption = FALSE;
373                                 continue;
374                         }
375                 } else {
376                         if (c != '-' || dashDash)
377                                 break;
378                         inOption = TRUE;
379                         c = *optscan++;
380                 }
381                 /* '-' found at some earlier point */
382                 getopt_spec = strchr(getopt_def, c);
383                 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
384                         /* -<something> found, and <something> should have an arg */
385                         inOption = FALSE;
386                         arginc = 1;
387                         argvalue = optscan;
388                         if(*argvalue == '\0') {
389                                 if (argc < 3)
390                                         goto noarg;
391                                 argvalue = argv[2];
392                                 arginc = 2;
393                         }
394                 } else {
395                         argvalue = NULL; 
396                 }
397                 switch(c) {
398                 case '\0':
399                         arginc = 1;
400                         inOption = FALSE;
401                         break;
402                 case 'B':
403                         compatMake = TRUE;
404                         Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
405                         Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
406                         break;
407                 case 'C':
408                         if (chdir(argvalue) == -1) {
409                                 (void)fprintf(stderr,
410                                               "%s: chdir %s: %s\n",
411                                               progname, argvalue,
412                                               strerror(errno));
413                                 exit(1);
414                         }
415                         if (getcwd(curdir, MAXPATHLEN) == NULL) {
416                                 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
417                                 exit(2);
418                         }
419                         ignorePWD = TRUE;
420                         break;
421                 case 'D':
422                         if (argvalue == NULL || argvalue[0] == 0) goto noarg;
423                         Var_Set(argvalue, "1", VAR_GLOBAL, 0);
424                         Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
425                         Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
426                         break;
427                 case 'I':
428                         if (argvalue == NULL) goto noarg;
429                         Parse_AddIncludeDir(argvalue);
430                         Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
431                         Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
432                         break;
433                 case 'J':
434                         if (argvalue == NULL) goto noarg;
435                         if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
436                             (void)fprintf(stderr,
437                                 "%s: internal error -- J option malformed (%s)\n",
438                                 progname, argvalue);
439                                 usage();
440                         }
441                         if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
442                             (fcntl(jp_1, F_GETFD, 0) < 0)) {
443 #if 0
444                             (void)fprintf(stderr,
445                                 "%s: ###### warning -- J descriptors were closed!\n",
446                                 progname);
447                             exit(2);
448 #endif
449                             jp_0 = -1;
450                             jp_1 = -1;
451                             compatMake = TRUE;
452                         } else {
453                             Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
454                             Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
455                             jobServer = TRUE;
456                         }
457                         break;
458                 case 'N':
459                         noExecute = TRUE;
460                         noRecursiveExecute = TRUE;
461                         Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
462                         break;
463                 case 'S':
464                         keepgoing = FALSE;
465                         Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
466                         break;
467                 case 'T':
468                         if (argvalue == NULL) goto noarg;
469                         tracefile = bmake_strdup(argvalue);
470                         Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
471                         Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
472                         break;
473                 case 'V':
474                         if (argvalue == NULL) goto noarg;
475                         printVars = TRUE;
476                         (void)Lst_AtEnd(variables, argvalue);
477                         Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
478                         Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
479                         break;
480                 case 'W':
481                         parseWarnFatal = TRUE;
482                         break;
483                 case 'X':
484                         varNoExportEnv = TRUE;
485                         Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
486                         break;
487                 case 'd':
488                         if (argvalue == NULL) goto noarg;
489                         /* If '-d-opts' don't pass to children */
490                         if (argvalue[0] == '-')
491                             argvalue++;
492                         else {
493                             Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
494                             Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
495                         }
496                         parse_debug_options(argvalue);
497                         break;
498                 case 'e':
499                         checkEnvFirst = TRUE;
500                         Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
501                         break;
502                 case 'f':
503                         if (argvalue == NULL) goto noarg;
504                         (void)Lst_AtEnd(makefiles, argvalue);
505                         break;
506                 case 'i':
507                         ignoreErrors = TRUE;
508                         Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
509                         break;
510                 case 'j':
511                         if (argvalue == NULL) goto noarg;
512                         forceJobs = TRUE;
513                         maxJobs = strtol(argvalue, &p, 0);
514                         if (*p != '\0' || maxJobs < 1) {
515                                 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
516                                     progname);
517                                 exit(1);
518                         }
519                         Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
520                         Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
521                         Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
522                         maxJobTokens = maxJobs;
523                         break;
524                 case 'k':
525                         keepgoing = TRUE;
526                         Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
527                         break;
528                 case 'm':
529                         if (argvalue == NULL) goto noarg;
530                         /* look for magic parent directory search string */
531                         if (strncmp(".../", argvalue, 4) == 0) {
532                                 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
533                                     found_path, sizeof(found_path)))
534                                         break;          /* nothing doing */
535                                 (void)Dir_AddDir(sysIncPath, found_path);
536                         } else {
537                                 (void)Dir_AddDir(sysIncPath, argvalue);
538                         }
539                         Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
540                         Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
541                         break;
542                 case 'n':
543                         noExecute = TRUE;
544                         Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
545                         break;
546                 case 'q':
547                         queryFlag = TRUE;
548                         /* Kind of nonsensical, wot? */
549                         Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
550                         break;
551                 case 'r':
552                         noBuiltins = TRUE;
553                         Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
554                         break;
555                 case 's':
556                         beSilent = TRUE;
557                         Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
558                         break;
559                 case 't':
560                         touchFlag = TRUE;
561                         Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
562                         break;
563                 case '-':
564                         dashDash = TRUE;
565                         break;
566                 default:
567                 case '?':
568 #ifndef MAKE_NATIVE
569                         fprintf(stderr, "getopt(%s) -> %d (%c)\n",
570                                 OPTFLAGS, c, c);
571 #endif
572                         usage();
573                 }
574                 argv += arginc;
575                 argc -= arginc;
576         }
577
578         oldVars = TRUE;
579
580         /*
581          * See if the rest of the arguments are variable assignments and
582          * perform them if so. Else take them to be targets and stuff them
583          * on the end of the "create" list.
584          */
585         for (; argc > 1; ++argv, --argc)
586                 if (Parse_IsVar(argv[1])) {
587                         Parse_DoVar(argv[1], VAR_CMD);
588                 } else {
589                         if (!*argv[1])
590                                 Punt("illegal (null) argument.");
591                         if (*argv[1] == '-' && !dashDash)
592                                 goto rearg;
593                         (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
594                 }
595
596         return;
597 noarg:
598         (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
599             progname, c);
600         usage();
601 }
602
603 /*-
604  * Main_ParseArgLine --
605  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
606  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
607  *      Takes a line of arguments and breaks it into its
608  *      component words and passes those words and the number of them to the
609  *      MainParseArgs function.
610  *      The line should have all its leading whitespace removed.
611  *
612  * Input:
613  *      line            Line to fracture
614  *
615  * Results:
616  *      None
617  *
618  * Side Effects:
619  *      Only those that come from the various arguments.
620  */
621 void
622 Main_ParseArgLine(const char *line)
623 {
624         char **argv;                    /* Manufactured argument vector */
625         int argc;                       /* Number of arguments in argv */
626         char *args;                     /* Space used by the args */
627         char *buf, *p1;
628         char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
629         size_t len;
630
631         if (line == NULL)
632                 return;
633         for (; *line == ' '; ++line)
634                 continue;
635         if (!*line)
636                 return;
637
638 #ifndef POSIX
639         {
640                 /*
641                  * $MAKE may simply be naming the make(1) binary
642                  */
643                 char *cp;
644
645                 if (!(cp = strrchr(line, '/')))
646                         cp = line;
647                 if ((cp = strstr(cp, "make")) &&
648                     strcmp(cp, "make") == 0)
649                         return;
650         }
651 #endif
652         buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
653         (void)snprintf(buf, len, "%s %s", argv0, line);
654         if (p1)
655                 free(p1);
656
657         argv = brk_string(buf, &argc, TRUE, &args);
658         if (argv == NULL) {
659                 Error("Unterminated quoted string [%s]", buf);
660                 free(buf);
661                 return;
662         }
663         free(buf);
664         MainParseArgs(argc, argv);
665
666         free(args);
667         free(argv);
668 }
669
670 Boolean
671 Main_SetObjdir(const char *path)
672 {
673         struct stat sb;
674         char *p = NULL;
675         char buf[MAXPATHLEN + 1];
676         Boolean rc = FALSE;
677
678         /* expand variable substitutions */
679         if (strchr(path, '$') != 0) {
680                 snprintf(buf, MAXPATHLEN, "%s", path);
681                 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
682         }
683
684         if (path[0] != '/') {
685                 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
686                 path = buf;
687         }
688
689         /* look for the directory and try to chdir there */
690         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
691                 if (chdir(path)) {
692                         (void)fprintf(stderr, "make warning: %s: %s.\n",
693                                       path, strerror(errno));
694                 } else {
695                         strncpy(objdir, path, MAXPATHLEN);
696                         Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
697                         setenv("PWD", objdir, 1);
698                         Dir_InitDot();
699                         rc = TRUE;
700                 }
701         }
702
703         if (p)
704                 free(p);
705         return rc;
706 }
707
708 /*-
709  * ReadAllMakefiles --
710  *      wrapper around ReadMakefile() to read all.
711  *
712  * Results:
713  *      TRUE if ok, FALSE on error
714  */
715 static int
716 ReadAllMakefiles(const void *p, const void *q)
717 {
718         return (ReadMakefile(p, q) == 0);
719 }
720
721 int
722 str2Lst_Append(Lst lp, char *str, const char *sep)
723 {
724     char *cp;
725     int n;
726
727     if (!sep)
728         sep = " \t";
729
730     for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
731         (void)Lst_AtEnd(lp, cp);
732         n++;
733     }
734     return (n);
735 }
736
737 #ifdef SIGINFO
738 /*ARGSUSED*/
739 static void
740 siginfo(int signo MAKE_ATTR_UNUSED)
741 {
742         char dir[MAXPATHLEN];
743         char str[2 * MAXPATHLEN];
744         int len;
745         if (getcwd(dir, sizeof(dir)) == NULL)
746                 return;
747         len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
748         if (len > 0)
749                 (void)write(STDERR_FILENO, str, (size_t)len);
750 }
751 #endif
752
753 /*
754  * Allow makefiles some control over the mode we run in.
755  */
756 void
757 MakeMode(const char *mode)
758 {
759     char *mp = NULL;
760
761     if (!mode)
762         mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}", VAR_GLOBAL, 0);
763
764     if (mode && *mode) {
765         if (strstr(mode, "compat")) {
766             compatMake = TRUE;
767             forceJobs = FALSE;
768         }
769 #if USE_META
770         if (strstr(mode, "meta"))
771             meta_init(mode);
772 #endif
773     }
774     if (mp)
775         free(mp);
776 }
777
778 /*-
779  * main --
780  *      The main function, for obvious reasons. Initializes variables
781  *      and a few modules, then parses the arguments give it in the
782  *      environment and on the command line. Reads the system makefile
783  *      followed by either Makefile, makefile or the file given by the
784  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
785  *      flags it has received by then uses either the Make or the Compat
786  *      module to create the initial list of targets.
787  *
788  * Results:
789  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
790  *      0.
791  *
792  * Side Effects:
793  *      The program exits when done. Targets are created. etc. etc. etc.
794  */
795 int
796 main(int argc, char **argv)
797 {
798         Lst targs;      /* target nodes to create -- passed to Make_Init */
799         Boolean outOfDate = FALSE;      /* FALSE if all targets up to date */
800         struct stat sb, sa;
801         char *p1, *path, *pwd;
802         char mdpath[MAXPATHLEN];
803 #ifdef FORCE_MACHINE
804         const char *machine = FORCE_MACHINE;
805 #else
806         const char *machine = getenv("MACHINE");
807 #endif
808         const char *machine_arch = getenv("MACHINE_ARCH");
809         char *syspath = getenv("MAKESYSPATH");
810         Lst sysMkPath;                  /* Path of sys.mk */
811         char *cp = NULL, *start;
812                                         /* avoid faults on read-only strings */
813         static char defsyspath[] = _PATH_DEFSYSPATH;
814         char found_path[MAXPATHLEN + 1];        /* for searching for sys.mk */
815         struct timeval rightnow;                /* to initialize random seed */
816 #ifdef MAKE_NATIVE
817         struct utsname utsname;
818 #endif
819
820         /* default to writing debug to stderr */
821         debug_file = stderr;
822
823 #ifdef SIGINFO
824         (void)bmake_signal(SIGINFO, siginfo);
825 #endif
826         /*
827          * Set the seed to produce a different random sequence
828          * on each program execution.
829          */
830         gettimeofday(&rightnow, NULL);
831         srandom(rightnow.tv_sec + rightnow.tv_usec);
832         
833         if ((progname = strrchr(argv[0], '/')) != NULL)
834                 progname++;
835         else
836                 progname = argv[0];
837 #ifdef RLIMIT_NOFILE
838         /*
839          * get rid of resource limit on file descriptors
840          */
841         {
842                 struct rlimit rl;
843                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
844                     rl.rlim_cur != rl.rlim_max) {
845                         rl.rlim_cur = rl.rlim_max;
846                         (void)setrlimit(RLIMIT_NOFILE, &rl);
847                 }
848         }
849 #endif
850
851         /*
852          * Get the name of this type of MACHINE from utsname
853          * so we can share an executable for similar machines.
854          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
855          *
856          * Note that both MACHINE and MACHINE_ARCH are decided at
857          * run-time.
858          */
859         if (!machine) {
860 #ifdef MAKE_NATIVE
861             if (uname(&utsname) == -1) {
862                 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
863                     strerror(errno));
864                 exit(2);
865             }
866             machine = utsname.machine;
867 #else
868 #ifdef MAKE_MACHINE
869             machine = MAKE_MACHINE;
870 #else
871             machine = "unknown";
872 #endif
873 #endif
874         }
875
876         if (!machine_arch) {
877 #ifndef MACHINE_ARCH
878 #ifdef MAKE_MACHINE_ARCH
879             machine_arch = MAKE_MACHINE_ARCH;
880 #else
881             machine_arch = "unknown";
882 #endif
883 #else
884             machine_arch = MACHINE_ARCH;
885 #endif
886         }
887
888         myPid = getpid();               /* remember this for vFork() */
889
890         /*
891          * Just in case MAKEOBJDIR wants us to do something tricky.
892          */
893         Var_Init();             /* Initialize the lists of variables for
894                                  * parsing arguments */
895         Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
896         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
897 #ifdef MAKE_VERSION
898         Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
899 #endif
900         Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
901         /*
902          * This is the traditional preference for makefiles.
903          */
904 #ifndef MAKEFILE_PREFERENCE_LIST
905 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
906 #endif
907         Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
908                 VAR_GLOBAL, 0);
909         Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
910
911         create = Lst_Init(FALSE);
912         makefiles = Lst_Init(FALSE);
913         printVars = FALSE;
914         debugVflag = FALSE;
915         variables = Lst_Init(FALSE);
916         beSilent = FALSE;               /* Print commands as executed */
917         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
918         noExecute = FALSE;              /* Execute all commands */
919         noRecursiveExecute = FALSE;     /* Execute all .MAKE targets */
920         keepgoing = FALSE;              /* Stop on error */
921         allPrecious = FALSE;            /* Remove targets when interrupted */
922         queryFlag = FALSE;              /* This is not just a check-run */
923         noBuiltins = FALSE;             /* Read the built-in rules */
924         touchFlag = FALSE;              /* Actually update targets */
925         debug = 0;                      /* No debug verbosity, please. */
926         jobsRunning = FALSE;
927
928         maxJobs = DEFMAXLOCAL;          /* Set default local max concurrency */
929         maxJobTokens = maxJobs;
930         compatMake = FALSE;             /* No compat mode */
931         ignorePWD = FALSE;
932
933         /*
934          * Initialize the parsing, directory and variable modules to prepare
935          * for the reading of inclusion paths and variable settings on the
936          * command line
937          */
938
939         /*
940          * Initialize various variables.
941          *      MAKE also gets this name, for compatibility
942          *      .MAKEFLAGS gets set to the empty string just in case.
943          *      MFLAGS also gets initialized empty, for compatibility.
944          */
945         Parse_Init();
946         if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
947             /*
948              * Leave alone if it is an absolute path, or if it does
949              * not contain a '/' in which case we need to find it in
950              * the path, like execvp(3) and the shells do.
951              */
952             p1 = argv[0];
953         } else {
954             /*
955              * A relative path, canonicalize it.
956              */
957             p1 = realpath(argv[0], mdpath);
958             if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
959                 p1 = argv[0];           /* realpath failed */
960             }
961         }
962         Var_Set("MAKE", p1, VAR_GLOBAL, 0);
963         Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
964         Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
965         Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
966         Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
967         Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
968
969         /*
970          * Set some other useful macros
971          */
972         {
973             char tmp[64];
974             const char *ep;
975
976             if (!(ep = getenv(MAKE_LEVEL))) {
977 #ifdef MAKE_LEVEL_SAFE
978                 if (!(ep = getenv(MAKE_LEVEL_SAFE)))
979 #endif
980                     ep = "0";
981             }
982             Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
983             snprintf(tmp, sizeof(tmp), "%u", myPid);
984             Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
985             snprintf(tmp, sizeof(tmp), "%u", getppid());
986             Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
987         }
988         Job_SetPrefix();
989
990         /*
991          * First snag any flags out of the MAKE environment variable.
992          * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
993          * in a different format).
994          */
995 #ifdef POSIX
996         Main_ParseArgLine(getenv("MAKEFLAGS"));
997 #else
998         Main_ParseArgLine(getenv("MAKE"));
999 #endif
1000
1001         /*
1002          * Find where we are (now).
1003          * We take care of PWD for the automounter below...
1004          */
1005         if (getcwd(curdir, MAXPATHLEN) == NULL) {
1006                 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1007                     progname, strerror(errno));
1008                 exit(2);
1009         }
1010
1011         MainParseArgs(argc, argv);
1012
1013         /*
1014          * Verify that cwd is sane.
1015          */
1016         if (stat(curdir, &sa) == -1) {
1017             (void)fprintf(stderr, "%s: %s: %s.\n",
1018                  progname, curdir, strerror(errno));
1019             exit(2);
1020         }
1021
1022         /*
1023          * All this code is so that we know where we are when we start up
1024          * on a different machine with pmake.
1025          * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1026          * since the value of curdir can vary depending on how we got
1027          * here.  Ie sitting at a shell prompt (shell that provides $PWD)
1028          * or via subdir.mk in which case its likely a shell which does
1029          * not provide it.
1030          * So, to stop it breaking this case only, we ignore PWD if
1031          * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1032          */
1033 #ifndef NO_PWD_OVERRIDE
1034         if (!ignorePWD &&
1035             (pwd = getenv("PWD")) != NULL &&
1036             getenv("MAKEOBJDIRPREFIX") == NULL) {
1037                 const char *makeobjdir = getenv("MAKEOBJDIR");
1038
1039                 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1040                         if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
1041                             sa.st_dev == sb.st_dev)
1042                                 (void)strncpy(curdir, pwd, MAXPATHLEN);
1043                 }
1044         }
1045 #endif
1046         Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1047
1048         /*
1049          * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
1050          * MAKEOBJDIR is set in the environment, try only that value
1051          * and fall back to .CURDIR if it does not exist.
1052          *
1053          * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1054          * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
1055          * of these paths exist, just use .CURDIR.
1056          */
1057         Dir_Init(curdir);
1058         (void)Main_SetObjdir(curdir);
1059
1060         if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1061                 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1062                 (void)Main_SetObjdir(mdpath);
1063         } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1064                 (void)Main_SetObjdir(path);
1065         } else {
1066                 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1067                 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1068                         (void)snprintf(mdpath, MAXPATHLEN, "%s%s", 
1069                                         _PATH_OBJDIRPREFIX, curdir);
1070                         (void)Main_SetObjdir(mdpath);
1071                 }
1072         }
1073
1074         /*
1075          * Be compatible if user did not specify -j and did not explicitly
1076          * turned compatibility on
1077          */
1078         if (!compatMake && !forceJobs) {
1079                 compatMake = TRUE;
1080         }
1081         
1082         /*
1083          * Initialize archive, target and suffix modules in preparation for
1084          * parsing the makefile(s)
1085          */
1086         Arch_Init();
1087         Targ_Init();
1088         Suff_Init();
1089         Trace_Init(tracefile);
1090
1091         DEFAULT = NULL;
1092         (void)time(&now);
1093
1094         Trace_Log(MAKESTART, NULL);
1095         
1096         /*
1097          * Set up the .TARGETS variable to contain the list of targets to be
1098          * created. If none specified, make the variable empty -- the parser
1099          * will fill the thing in with the default or .MAIN target.
1100          */
1101         if (!Lst_IsEmpty(create)) {
1102                 LstNode ln;
1103
1104                 for (ln = Lst_First(create); ln != NULL;
1105                     ln = Lst_Succ(ln)) {
1106                         char *name = (char *)Lst_Datum(ln);
1107
1108                         Var_Append(".TARGETS", name, VAR_GLOBAL);
1109                 }
1110         } else
1111                 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1112
1113
1114         /*
1115          * If no user-supplied system path was given (through the -m option)
1116          * add the directories from the DEFSYSPATH (more than one may be given
1117          * as dir1:...:dirn) to the system include path.
1118          */
1119         if (syspath == NULL || *syspath == '\0')
1120                 syspath = defsyspath;
1121         else
1122                 syspath = bmake_strdup(syspath);
1123
1124         for (start = syspath; *start != '\0'; start = cp) {
1125                 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1126                         continue;
1127                 if (*cp == ':') {
1128                         *cp++ = '\0';
1129                 }
1130                 /* look for magic parent directory search string */
1131                 if (strncmp(".../", start, 4) != 0) {
1132                         (void)Dir_AddDir(defIncPath, start);
1133                 } else {
1134                         if (Dir_FindHereOrAbove(curdir, start+4, 
1135                             found_path, sizeof(found_path))) {
1136                                 (void)Dir_AddDir(defIncPath, found_path);
1137                         }
1138                 }
1139         }
1140         if (syspath != defsyspath)
1141                 free(syspath);
1142
1143         /*
1144          * Read in the built-in rules first, followed by the specified
1145          * makefile, if it was (makefile != NULL), or the default
1146          * makefile and Makefile, in that order, if it wasn't.
1147          */
1148         if (!noBuiltins) {
1149                 LstNode ln;
1150
1151                 sysMkPath = Lst_Init(FALSE);
1152                 Dir_Expand(_PATH_DEFSYSMK,
1153                            Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1154                            sysMkPath);
1155                 if (Lst_IsEmpty(sysMkPath))
1156                         Fatal("%s: no system rules (%s).", progname,
1157                             _PATH_DEFSYSMK);
1158                 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1159                 if (ln == NULL)
1160                         Fatal("%s: cannot open %s.", progname,
1161                             (char *)Lst_Datum(ln));
1162         }
1163
1164         if (!Lst_IsEmpty(makefiles)) {
1165                 LstNode ln;
1166
1167                 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1168                 if (ln != NULL)
1169                         Fatal("%s: cannot open %s.", progname, 
1170                             (char *)Lst_Datum(ln));
1171         } else {
1172             p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1173                 VAR_CMD, 0);
1174             if (p1) {
1175                 (void)str2Lst_Append(makefiles, p1, NULL);
1176                 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1177                 free(p1);
1178             }
1179         }
1180
1181         /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1182         if (!noBuiltins || !printVars) {
1183             makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1184                 VAR_CMD, 0);
1185             doing_depend = TRUE;
1186             (void)ReadMakefile(makeDependfile, NULL);
1187             doing_depend = FALSE;
1188         }
1189
1190         MakeMode(NULL);
1191
1192         Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1193         if (p1)
1194             free(p1);
1195
1196         if (!compatMake)
1197             Job_ServerStart(maxJobTokens, jp_0, jp_1);
1198         if (DEBUG(JOB))
1199             fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1200                 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1201
1202         Main_ExportMAKEFLAGS(TRUE);     /* initial export */
1203
1204         /*
1205          * For compatibility, look at the directories in the VPATH variable
1206          * and add them to the search path, if the variable is defined. The
1207          * variable's value is in the same format as the PATH envariable, i.e.
1208          * <directory>:<directory>:<directory>...
1209          */
1210         if (Var_Exists("VPATH", VAR_CMD)) {
1211                 char *vpath, savec;
1212                 /*
1213                  * GCC stores string constants in read-only memory, but
1214                  * Var_Subst will want to write this thing, so store it
1215                  * in an array
1216                  */
1217                 static char VPATH[] = "${VPATH}";
1218
1219                 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1220                 path = vpath;
1221                 do {
1222                         /* skip to end of directory */
1223                         for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1224                                 continue;
1225                         /* Save terminator character so know when to stop */
1226                         savec = *cp;
1227                         *cp = '\0';
1228                         /* Add directory to search path */
1229                         (void)Dir_AddDir(dirSearchPath, path);
1230                         *cp = savec;
1231                         path = cp + 1;
1232                 } while (savec == ':');
1233                 free(vpath);
1234         }
1235
1236         /*
1237          * Now that all search paths have been read for suffixes et al, it's
1238          * time to add the default search path to their lists...
1239          */
1240         Suff_DoPaths();
1241
1242         /*
1243          * Propagate attributes through :: dependency lists.
1244          */
1245         Targ_Propagate();
1246
1247         /* print the initial graph, if the user requested it */
1248         if (DEBUG(GRAPH1))
1249                 Targ_PrintGraph(1);
1250
1251         /* print the values of any variables requested by the user */
1252         if (printVars) {
1253                 LstNode ln;
1254                 Boolean expandVars;
1255
1256                 if (debugVflag)
1257                         expandVars = FALSE;
1258                 else
1259                         expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1260                 for (ln = Lst_First(variables); ln != NULL;
1261                     ln = Lst_Succ(ln)) {
1262                         char *var = (char *)Lst_Datum(ln);
1263                         char *value;
1264                         
1265                         if (strchr(var, '$')) {
1266                                 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1267                         } else if (expandVars) {
1268                                 char tmp[128];
1269                                                                 
1270                                 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1271                                         Fatal("%s: variable name too big: %s",
1272                                               progname, var);
1273                                 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1274                         } else {
1275                                 value = Var_Value(var, VAR_GLOBAL, &p1);
1276                         }
1277                         printf("%s\n", value ? value : "");
1278                         if (p1)
1279                                 free(p1);
1280                 }
1281         } else {
1282                 /*
1283                  * Have now read the entire graph and need to make a list of
1284                  * targets to create. If none was given on the command line,
1285                  * we consult the parsing module to find the main target(s)
1286                  * to create.
1287                  */
1288                 if (Lst_IsEmpty(create))
1289                         targs = Parse_MainName();
1290                 else
1291                         targs = Targ_FindList(create, TARG_CREATE);
1292
1293                 if (!compatMake) {
1294                         /*
1295                          * Initialize job module before traversing the graph
1296                          * now that any .BEGIN and .END targets have been read.
1297                          * This is done only if the -q flag wasn't given
1298                          * (to prevent the .BEGIN from being executed should
1299                          * it exist).
1300                          */
1301                         if (!queryFlag) {
1302                                 Job_Init();
1303                                 jobsRunning = TRUE;
1304                         }
1305
1306                         /* Traverse the graph, checking on all the targets */
1307                         outOfDate = Make_Run(targs);
1308                 } else {
1309                         /*
1310                          * Compat_Init will take care of creating all the
1311                          * targets as well as initializing the module.
1312                          */
1313                         Compat_Run(targs);
1314                 }
1315         }
1316
1317 #ifdef CLEANUP
1318         Lst_Destroy(targs, NULL);
1319         Lst_Destroy(variables, NULL);
1320         Lst_Destroy(makefiles, NULL);
1321         Lst_Destroy(create, (FreeProc *)free);
1322 #endif
1323
1324         /* print the graph now it's been processed if the user requested it */
1325         if (DEBUG(GRAPH2))
1326                 Targ_PrintGraph(2);
1327
1328         Trace_Log(MAKEEND, 0);
1329
1330         Suff_End();
1331         Targ_End();
1332         Arch_End();
1333         Var_End();
1334         Parse_End();
1335         Dir_End();
1336         Job_End();
1337         Trace_End();
1338
1339         return outOfDate ? 1 : 0;
1340 }
1341
1342 /*-
1343  * ReadMakefile  --
1344  *      Open and parse the given makefile.
1345  *
1346  * Results:
1347  *      0 if ok. -1 if couldn't open file.
1348  *
1349  * Side Effects:
1350  *      lots
1351  */
1352 static int
1353 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1354 {
1355         const char *fname = p;          /* makefile to read */
1356         int fd;
1357         size_t len = MAXPATHLEN;
1358         char *name, *path = bmake_malloc(len);
1359
1360         if (!strcmp(fname, "-")) {
1361                 Parse_File(NULL /*stdin*/, -1);
1362                 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1363         } else {
1364                 /* if we've chdir'd, rebuild the path name */
1365                 if (strcmp(curdir, objdir) && *fname != '/') {
1366                         size_t plen = strlen(curdir) + strlen(fname) + 2;
1367                         if (len < plen)
1368                                 path = bmake_realloc(path, len = 2 * plen);
1369                         
1370                         (void)snprintf(path, len, "%s/%s", curdir, fname);
1371                         fd = open(path, O_RDONLY);
1372                         if (fd != -1) {
1373                                 fname = path;
1374                                 goto found;
1375                         }
1376                         
1377                         /* If curdir failed, try objdir (ala .depend) */
1378                         plen = strlen(objdir) + strlen(fname) + 2;
1379                         if (len < plen)
1380                                 path = bmake_realloc(path, len = 2 * plen);
1381                         (void)snprintf(path, len, "%s/%s", objdir, fname);
1382                         fd = open(path, O_RDONLY);
1383                         if (fd != -1) {
1384                                 fname = path;
1385                                 goto found;
1386                         }
1387                 } else {
1388                         fd = open(fname, O_RDONLY);
1389                         if (fd != -1)
1390                                 goto found;
1391                 }
1392                 /* look in -I and system include directories. */
1393                 name = Dir_FindFile(fname, parseIncPath);
1394                 if (!name)
1395                         name = Dir_FindFile(fname,
1396                                 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1397                 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1398                         if (name)
1399                                 free(name);
1400                         free(path);
1401                         return(-1);
1402                 }
1403                 fname = name;
1404                 /*
1405                  * set the MAKEFILE variable desired by System V fans -- the
1406                  * placement of the setting here means it gets set to the last
1407                  * makefile specified, as it is set by SysV make.
1408                  */
1409 found:
1410                 if (!doing_depend)
1411                         Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1412                 Parse_File(fname, fd);
1413         }
1414         free(path);
1415         return(0);
1416 }
1417
1418
1419
1420 /*-
1421  * Cmd_Exec --
1422  *      Execute the command in cmd, and return the output of that command
1423  *      in a string.
1424  *
1425  * Results:
1426  *      A string containing the output of the command, or the empty string
1427  *      If errnum is not NULL, it contains the reason for the command failure
1428  *
1429  * Side Effects:
1430  *      The string must be freed by the caller.
1431  */
1432 char *
1433 Cmd_Exec(const char *cmd, const char **errnum)
1434 {
1435     const char  *args[4];       /* Args for invoking the shell */
1436     int         fds[2];         /* Pipe streams */
1437     int         cpid;           /* Child PID */
1438     int         pid;            /* PID from wait() */
1439     char        *res;           /* result */
1440     WAIT_T      status;         /* command exit status */
1441     Buffer      buf;            /* buffer to store the result */
1442     char        *cp;
1443     int         cc;
1444
1445
1446     *errnum = NULL;
1447
1448     if (!shellName)
1449         Shell_Init();
1450     /*
1451      * Set up arguments for shell
1452      */
1453     args[0] = shellName;
1454     args[1] = "-c";
1455     args[2] = cmd;
1456     args[3] = NULL;
1457
1458     /*
1459      * Open a pipe for fetching its output
1460      */
1461     if (pipe(fds) == -1) {
1462         *errnum = "Couldn't create pipe for \"%s\"";
1463         goto bad;
1464     }
1465
1466     /*
1467      * Fork
1468      */
1469     switch (cpid = vFork()) {
1470     case 0:
1471         /*
1472          * Close input side of pipe
1473          */
1474         (void)close(fds[0]);
1475
1476         /*
1477          * Duplicate the output stream to the shell's output, then
1478          * shut the extra thing down. Note we don't fetch the error
1479          * stream...why not? Why?
1480          */
1481         (void)dup2(fds[1], 1);
1482         (void)close(fds[1]);
1483
1484         Var_ExportVars();
1485
1486         (void)execv(shellPath, UNCONST(args));
1487         _exit(1);
1488         /*NOTREACHED*/
1489
1490     case -1:
1491         *errnum = "Couldn't exec \"%s\"";
1492         goto bad;
1493
1494     default:
1495         /*
1496          * No need for the writing half
1497          */
1498         (void)close(fds[1]);
1499
1500         Buf_Init(&buf, 0);
1501
1502         do {
1503             char   result[BUFSIZ];
1504             cc = read(fds[0], result, sizeof(result));
1505             if (cc > 0)
1506                 Buf_AddBytes(&buf, cc, result);
1507         }
1508         while (cc > 0 || (cc == -1 && errno == EINTR));
1509
1510         /*
1511          * Close the input side of the pipe.
1512          */
1513         (void)close(fds[0]);
1514
1515         /*
1516          * Wait for the process to exit.
1517          */
1518         while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1519             JobReapChild(pid, status, FALSE);
1520             continue;
1521         }
1522         cc = Buf_Size(&buf);
1523         res = Buf_Destroy(&buf, FALSE);
1524
1525         if (cc == 0)
1526             *errnum = "Couldn't read shell's output for \"%s\"";
1527
1528         if (WIFSIGNALED(status))
1529             *errnum = "\"%s\" exited on a signal";
1530         else if (WEXITSTATUS(status) != 0)
1531             *errnum = "\"%s\" returned non-zero status";
1532
1533         /*
1534          * Null-terminate the result, convert newlines to spaces and
1535          * install it in the variable.
1536          */
1537         res[cc] = '\0';
1538         cp = &res[cc];
1539
1540         if (cc > 0 && *--cp == '\n') {
1541             /*
1542              * A final newline is just stripped
1543              */
1544             *cp-- = '\0';
1545         }
1546         while (cp >= res) {
1547             if (*cp == '\n') {
1548                 *cp = ' ';
1549             }
1550             cp--;
1551         }
1552         break;
1553     }
1554     return res;
1555 bad:
1556     res = bmake_malloc(1);
1557     *res = '\0';
1558     return res;
1559 }
1560
1561 /*-
1562  * Error --
1563  *      Print an error message given its format.
1564  *
1565  * Results:
1566  *      None.
1567  *
1568  * Side Effects:
1569  *      The message is printed.
1570  */
1571 /* VARARGS */
1572 void
1573 Error(const char *fmt, ...)
1574 {
1575         va_list ap;
1576         FILE *err_file;
1577
1578         err_file = debug_file;
1579         if (err_file == stdout)
1580                 err_file = stderr;
1581         (void)fflush(stdout);
1582         for (;;) {
1583                 va_start(ap, fmt);
1584                 fprintf(err_file, "%s: ", progname);
1585                 (void)vfprintf(err_file, fmt, ap);
1586                 va_end(ap);
1587                 (void)fprintf(err_file, "\n");
1588                 (void)fflush(err_file);
1589                 if (err_file == stderr)
1590                         break;
1591                 err_file = stderr;
1592         }
1593 }
1594
1595 /*-
1596  * Fatal --
1597  *      Produce a Fatal error message. If jobs are running, waits for them
1598  *      to finish.
1599  *
1600  * Results:
1601  *      None
1602  *
1603  * Side Effects:
1604  *      The program exits
1605  */
1606 /* VARARGS */
1607 void
1608 Fatal(const char *fmt, ...)
1609 {
1610         va_list ap;
1611
1612         va_start(ap, fmt);
1613         if (jobsRunning)
1614                 Job_Wait();
1615
1616         (void)fflush(stdout);
1617         (void)vfprintf(stderr, fmt, ap);
1618         va_end(ap);
1619         (void)fprintf(stderr, "\n");
1620         (void)fflush(stderr);
1621
1622         PrintOnError(NULL, NULL);
1623
1624         if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1625                 Targ_PrintGraph(2);
1626         Trace_Log(MAKEERROR, 0);
1627         exit(2);                /* Not 1 so -q can distinguish error */
1628 }
1629
1630 /*
1631  * Punt --
1632  *      Major exception once jobs are being created. Kills all jobs, prints
1633  *      a message and exits.
1634  *
1635  * Results:
1636  *      None
1637  *
1638  * Side Effects:
1639  *      All children are killed indiscriminately and the program Lib_Exits
1640  */
1641 /* VARARGS */
1642 void
1643 Punt(const char *fmt, ...)
1644 {
1645         va_list ap;
1646
1647         va_start(ap, fmt);
1648         (void)fflush(stdout);
1649         (void)fprintf(stderr, "%s: ", progname);
1650         (void)vfprintf(stderr, fmt, ap);
1651         va_end(ap);
1652         (void)fprintf(stderr, "\n");
1653         (void)fflush(stderr);
1654
1655         PrintOnError(NULL, NULL);
1656
1657         DieHorribly();
1658 }
1659
1660 /*-
1661  * DieHorribly --
1662  *      Exit without giving a message.
1663  *
1664  * Results:
1665  *      None
1666  *
1667  * Side Effects:
1668  *      A big one...
1669  */
1670 void
1671 DieHorribly(void)
1672 {
1673         if (jobsRunning)
1674                 Job_AbortAll();
1675         if (DEBUG(GRAPH2))
1676                 Targ_PrintGraph(2);
1677         Trace_Log(MAKEERROR, 0);
1678         exit(2);                /* Not 1, so -q can distinguish error */
1679 }
1680
1681 /*
1682  * Finish --
1683  *      Called when aborting due to errors in child shell to signal
1684  *      abnormal exit.
1685  *
1686  * Results:
1687  *      None
1688  *
1689  * Side Effects:
1690  *      The program exits
1691  */
1692 void
1693 Finish(int errors)
1694                         /* number of errors encountered in Make_Make */
1695 {
1696         Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1697 }
1698
1699 /*
1700  * enunlink --
1701  *      Remove a file carefully, avoiding directories.
1702  */
1703 int
1704 eunlink(const char *file)
1705 {
1706         struct stat st;
1707
1708         if (lstat(file, &st) == -1)
1709                 return -1;
1710
1711         if (S_ISDIR(st.st_mode)) {
1712                 errno = EISDIR;
1713                 return -1;
1714         }
1715         return unlink(file);
1716 }
1717
1718 /*
1719  * execError --
1720  *      Print why exec failed, avoiding stdio.
1721  */
1722 void
1723 execError(const char *af, const char *av)
1724 {
1725 #ifdef USE_IOVEC
1726         int i = 0;
1727         struct iovec iov[8];
1728 #define IOADD(s) \
1729         (void)(iov[i].iov_base = UNCONST(s), \
1730             iov[i].iov_len = strlen(iov[i].iov_base), \
1731             i++)
1732 #else
1733 #define IOADD(s) (void)write(2, s, strlen(s))
1734 #endif
1735
1736         IOADD(progname);
1737         IOADD(": ");
1738         IOADD(af);
1739         IOADD("(");
1740         IOADD(av);
1741         IOADD(") failed (");
1742         IOADD(strerror(errno));
1743         IOADD(")\n");
1744
1745 #ifdef USE_IOVEC
1746         while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1747             continue;
1748 #endif
1749 }
1750
1751 /*
1752  * usage --
1753  *      exit with usage message
1754  */
1755 static void
1756 usage(void)
1757 {
1758         (void)fprintf(stderr,
1759 "usage: %s [-BeikNnqrstWX] \n\
1760             [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1761             [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1762             [-V variable] [variable=value] [target ...]\n", progname);
1763         exit(2);
1764 }
1765
1766
1767 int
1768 PrintAddr(void *a, void *b)
1769 {
1770     printf("%lx ", (unsigned long) a);
1771     return b ? 0 : 0;
1772 }
1773
1774
1775
1776 void
1777 PrintOnError(GNode *gn, const char *s)
1778 {
1779     static GNode *en = NULL;
1780     char tmp[64];
1781     char *cp;
1782
1783     if (s)
1784         printf("%s", s);
1785         
1786     printf("\n%s: stopped in %s\n", progname, curdir);
1787
1788     if (en)
1789         return;                         /* we've been here! */
1790     if (gn) {
1791         /*
1792          * We can print this even if there is no .ERROR target.
1793          */
1794         Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1795     }
1796     strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1797             sizeof(tmp) - 1);
1798     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1799     if (cp) {
1800         if (*cp)
1801             printf("%s", cp);
1802         free(cp);
1803     }
1804     /*
1805      * Finally, see if there is a .ERROR target, and run it if so.
1806      */
1807     en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1808     if (en) {
1809         en->type |= OP_SPECIAL;
1810         Compat_Make(en, en);
1811     }
1812 }
1813
1814 void
1815 Main_ExportMAKEFLAGS(Boolean first)
1816 {
1817     static int once = 1;
1818     char tmp[64];
1819     char *s;
1820
1821     if (once != first)
1822         return;
1823     once = 0;
1824     
1825     strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1826             sizeof(tmp));
1827     s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1828     if (s && *s) {
1829 #ifdef POSIX
1830         setenv("MAKEFLAGS", s, 1);
1831 #else
1832         setenv("MAKE", s, 1);
1833 #endif
1834     }
1835 }
1836
1837 char *
1838 getTmpdir(void)
1839 {
1840     static char *tmpdir = NULL;
1841
1842     if (!tmpdir) {
1843         struct stat st;
1844
1845         /*
1846          * Honor $TMPDIR but only if it is valid.
1847          * Ensure it ends with /.
1848          */
1849         tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1850         if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1851             free(tmpdir);
1852             tmpdir = bmake_strdup(_PATH_TMP);
1853         }
1854     }
1855     return tmpdir;
1856 }
1857
1858 /*
1859  * Create and open a temp file using "pattern".
1860  * If "fnamep" is provided set it to a copy of the filename created.
1861  * Otherwise unlink the file once open.
1862  */
1863 int
1864 mkTempFile(const char *pattern, char **fnamep)
1865 {
1866     static char *tmpdir = NULL;
1867     char tfile[MAXPATHLEN];
1868     int fd;
1869     
1870     if (!pattern)
1871         pattern = TMPPAT;
1872     if (!tmpdir)
1873         tmpdir = getTmpdir();
1874     if (pattern[0] == '/') {
1875         snprintf(tfile, sizeof(tfile), "%s", pattern);
1876     } else {
1877         snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1878     }
1879     if ((fd = mkstemp(tfile)) < 0)
1880         Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1881     if (fnamep) {
1882         *fnamep = bmake_strdup(tfile);
1883     } else {
1884         unlink(tfile);                  /* we just want the descriptor */
1885     }
1886     return fd;
1887 }
1888
1889
1890 /*
1891  * Return a Boolean based on setting of a knob.
1892  *
1893  * If the knob is not set, the supplied default is the return value.
1894  * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1895  * is FALSE, otherwise TRUE.
1896  */
1897 Boolean
1898 getBoolean(const char *name, Boolean bf)
1899 {
1900     char tmp[64];
1901     char *cp;
1902
1903     if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1904         cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1905
1906         if (cp) {
1907             switch(*cp) {
1908             case '\0':                  /* not set - the default wins */
1909                 break;
1910             case '0':
1911             case 'f':
1912             case 'n':
1913                 bf = FALSE;
1914                 break;
1915             case 'o':
1916                 switch (cp[1]) {
1917                 case 'f':
1918                     bf = FALSE;
1919                     break;
1920                 default:
1921                     bf = TRUE;
1922                     break;
1923                 }
1924                 break;
1925             default:
1926                 bf = TRUE;
1927                 break;
1928             }
1929             free(cp);
1930         }
1931     }
1932     return (bf);
1933 }