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