]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/make/main.c
This commit was generated by cvs2svn to compensate for changes in r178479,
[FreeBSD/FreeBSD.git] / usr.bin / make / main.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * 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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)main.c      8.3 (Berkeley) 3/19/94
39  */
40
41 #ifndef lint
42 #if 0
43 static char copyright[] =
44 "@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
45         The Regents of the University of California.  All rights reserved.\n";
46 #endif
47 #endif /* not lint */
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50
51 /*
52  * main.c
53  *      The main file for this entire program. Exit routines etc
54  *      reside here.
55  *
56  * Utility functions defined in this file:
57  *      Main_ParseArgLine
58  *                      Takes a line of arguments, breaks them and
59  *                      treats them as if they were given when first
60  *                      invoked. Used by the parse module to implement
61  *                      the .MFLAGS target.
62  */
63
64 #include <sys/param.h>
65 #include <sys/stat.h>
66 #include <sys/sysctl.h>
67 #include <sys/time.h>
68 #include <sys/queue.h>
69 #include <sys/resource.h>
70 #include <sys/utsname.h>
71 #include <sys/wait.h>
72 #include <err.h>
73 #include <errno.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <unistd.h>
77
78 #include "arch.h"
79 #include "buf.h"
80 #include "config.h"
81 #include "dir.h"
82 #include "globals.h"
83 #include "GNode.h"
84 #include "job.h"
85 #include "make.h"
86 #include "parse.h"
87 #include "pathnames.h"
88 #include "shell.h"
89 #include "str.h"
90 #include "suff.h"
91 #include "targ.h"
92 #include "util.h"
93 #include "var.h"
94
95 extern char **environ;  /* XXX what header declares this variable? */
96
97 #define WANT_ENV_MKLVL  1
98 #define MKLVL_MAXVAL    500
99 #define MKLVL_ENVVAR    "__MKLVL__"
100
101 /* ordered list of makefiles to read */
102 static Lst makefiles = Lst_Initializer(makefiles);
103
104 /* ordered list of source makefiles */
105 static Lst source_makefiles = Lst_Initializer(source_makefiles);
106
107 /* list of variables to print */
108 static Lst variables = Lst_Initializer(variables);
109
110 static Boolean  expandVars;     /* fully expand printed variables */
111 static Boolean  noBuiltins;     /* -r flag */
112 static Boolean  forceJobs;      /* -j argument given */
113 static char     *curdir;        /* startup directory */
114 static char     *objdir;        /* where we chdir'ed to */
115 static char     **save_argv;    /* saved argv */
116 static char     *save_makeflags;/* saved MAKEFLAGS */
117
118 /* (-E) vars to override from env */
119 Lst envFirstVars = Lst_Initializer(envFirstVars);
120
121 /* Targets to be made */
122 Lst create = Lst_Initializer(create);
123
124 Boolean         allPrecious;    /* .PRECIOUS given on line by itself */
125 Boolean         is_posix;       /* .POSIX target seen */
126 Boolean         mfAutoDeps;     /* .MAKEFILEDEPS target seen */
127 Boolean         beSilent;       /* -s flag */
128 Boolean         beVerbose;      /* -v flag */
129 Boolean         compatMake;     /* -B argument */
130 int             debug;          /* -d flag */
131 Boolean         ignoreErrors;   /* -i flag */
132 int             jobLimit;       /* -j argument */
133 Boolean         jobsRunning;    /* TRUE if the jobs might be running */
134 Boolean         keepgoing;      /* -k flag */
135 Boolean         noExecute;      /* -n flag */
136 Boolean         queryFlag;      /* -q flag */
137 Boolean         touchFlag;      /* -t flag */
138 Boolean         usePipes;       /* !-P flag */
139 uint32_t        warn_cmd;       /* command line warning flags */
140 uint32_t        warn_flags;     /* actual warning flags */
141 uint32_t        warn_nocmd;     /* command line no-warning flags */
142
143 time_t          now;            /* Time at start of make */
144 struct GNode    *DEFAULT;       /* .DEFAULT node */
145
146 /**
147  * Exit with usage message.
148  */
149 static void
150 usage(void)
151 {
152         fprintf(stderr,
153             "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable]\n"
154             "\t[-d flags] [-E variable] [-f makefile] [-I directory]\n"
155             "\t[-j max_jobs] [-m directory] [-V variable]\n"
156             "\t[variable=value] [target ...]\n");
157         exit(2);
158 }
159
160 /**
161  * MFLAGS_append
162  *      Append a flag with an optional argument to MAKEFLAGS and MFLAGS
163  */
164 static void
165 MFLAGS_append(const char *flag, char *arg)
166 {
167         char *str;
168
169         Var_Append(".MAKEFLAGS", flag, VAR_GLOBAL);
170         if (arg != NULL) {
171                 str = MAKEFLAGS_quote(arg);
172                 Var_Append(".MAKEFLAGS", str, VAR_GLOBAL);
173                 free(str);
174         }
175
176         Var_Append("MFLAGS", flag, VAR_GLOBAL);
177         if (arg != NULL) {
178                 str = MAKEFLAGS_quote(arg);
179                 Var_Append("MFLAGS", str, VAR_GLOBAL);
180                 free(str);
181         }
182 }
183
184 /**
185  * Main_ParseWarn
186  *
187  *      Handle argument to warning option.
188  */
189 int
190 Main_ParseWarn(const char *arg, int iscmd)
191 {
192         int i, neg;
193
194         static const struct {
195                 const char      *option;
196                 uint32_t        flag;
197         } options[] = {
198                 { "dirsyntax",  WARN_DIRSYNTAX },
199                 { NULL,         0 }
200         };
201
202         neg = 0;
203         if (arg[0] == 'n' && arg[1] == 'o') {
204                 neg = 1;
205                 arg += 2;
206         }
207
208         for (i = 0; options[i].option != NULL; i++)
209                 if (strcmp(arg, options[i].option) == 0)
210                         break;
211
212         if (options[i].option == NULL)
213                 /* unknown option */
214                 return (-1);
215
216         if (iscmd) {
217                 if (!neg) {
218                         warn_cmd |= options[i].flag;
219                         warn_nocmd &= ~options[i].flag;
220                         warn_flags |= options[i].flag;
221                 } else {
222                         warn_nocmd |= options[i].flag;
223                         warn_cmd &= ~options[i].flag;
224                         warn_flags &= ~options[i].flag;
225                 }
226         } else {
227                 if (!neg) {
228                         warn_flags |= (options[i].flag & ~warn_nocmd);
229                 } else {
230                         warn_flags &= ~(options[i].flag | warn_cmd);
231                 }
232         }
233         return (0);
234 }
235
236 /**
237  * Open and parse the given makefile.
238  *
239  * Results:
240  *      TRUE if ok. FALSE if couldn't open file.
241  */
242 static Boolean
243 ReadMakefile(const char p[])
244 {
245         char *fname, *fnamesave;        /* makefile to read */
246         FILE *stream;
247         char *name, path[MAXPATHLEN];
248         char *MAKEFILE;
249         int setMAKEFILE;
250
251         /* XXX - remove this once constification is done */
252         fnamesave = fname = estrdup(p);
253
254         if (!strcmp(fname, "-")) {
255                 Parse_File("(stdin)", stdin);
256                 Var_SetGlobal("MAKEFILE", "");
257         } else {
258                 setMAKEFILE = strcmp(fname, ".depend");
259
260                 /* if we've chdir'd, rebuild the path name */
261                 if (curdir != objdir && *fname != '/') {
262                         snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
263                         /*
264                          * XXX The realpath stuff breaks relative includes
265                          * XXX in some cases.   The problem likely is in
266                          * XXX parse.c where it does special things in
267                          * XXX ParseDoInclude if the file is relateive
268                          * XXX or absolute and not a system file.  There
269                          * XXX it assumes that if the current file that's
270                          * XXX being included is absolute, that any files
271                          * XXX that it includes shouldn't do the -I path
272                          * XXX stuff, which is inconsistant with historical
273                          * XXX behavior.  However, I can't pentrate the mists
274                          * XXX further, so I'm putting this workaround in
275                          * XXX here until such time as the underlying bug
276                          * XXX can be fixed.
277                          */
278 #if THIS_BREAKS_THINGS
279                         if (realpath(path, path) != NULL &&
280                             (stream = fopen(path, "r")) != NULL) {
281                                 MAKEFILE = fname;
282                                 fname = path;
283                                 goto found;
284                         }
285                 } else if (realpath(fname, path) != NULL) {
286                         MAKEFILE = fname;
287                         fname = path;
288                         if ((stream = fopen(fname, "r")) != NULL)
289                                 goto found;
290                 }
291 #else
292                         if ((stream = fopen(path, "r")) != NULL) {
293                                 MAKEFILE = fname;
294                                 fname = path;
295                                 goto found;
296                         }
297                 } else {
298                         MAKEFILE = fname;
299                         if ((stream = fopen(fname, "r")) != NULL)
300                                 goto found;
301                 }
302 #endif
303                 /* look in -I and system include directories. */
304                 name = Path_FindFile(fname, &parseIncPath);
305                 if (!name)
306                         name = Path_FindFile(fname, &sysIncPath);
307                 if (!name || !(stream = fopen(name, "r"))) {
308                         free(fnamesave);
309                         return (FALSE);
310                 }
311                 MAKEFILE = fname = name;
312                 /*
313                  * set the MAKEFILE variable desired by System V fans -- the
314                  * placement of the setting here means it gets set to the last
315                  * makefile specified, as it is set by SysV make.
316                  */
317 found:
318                 if (setMAKEFILE)
319                         Var_SetGlobal("MAKEFILE", MAKEFILE);
320                 Parse_File(fname, stream);
321         }
322         free(fnamesave);
323         return (TRUE);
324 }
325
326 /**
327  * Open and parse the given makefile.
328  * If open is successful add it to the list of makefiles.
329  *
330  * Results:
331  *      TRUE if ok. FALSE if couldn't open file.
332  */
333 static Boolean
334 TryReadMakefile(const char p[])
335 {
336         char *data;
337         LstNode *last = Lst_Last(&source_makefiles);
338
339         if (!ReadMakefile(p))
340                 return (FALSE);
341
342         data = estrdup(p);
343         if (last == NULL) {
344                 LstNode *first = Lst_First(&source_makefiles);
345                 Lst_Insert(&source_makefiles, first, data);
346         } else
347                 Lst_Append(&source_makefiles, last, estrdup(p));
348         return (TRUE);
349 }
350
351 /**
352  * MainParseArgs
353  *      Parse a given argument vector. Called from main() and from
354  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
355  *
356  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
357  *
358  * Side Effects:
359  *      Various global and local flags will be set depending on the flags
360  *      given
361  */
362 static void
363 MainParseArgs(int argc, char **argv)
364 {
365         int c;
366         Boolean found_dd = FALSE;
367
368 rearg:
369         optind = 1;     /* since we're called more than once */
370         optreset = 1;
371 #define OPTFLAGS "ABC:D:E:I:PSV:Xd:ef:ij:km:nqrstvx:"
372         for (;;) {
373                 if ((optind < argc) && strcmp(argv[optind], "--") == 0) {
374                         found_dd = TRUE;
375                 }
376                 if ((c = getopt(argc, argv, OPTFLAGS)) == -1) {
377                         break;
378                 }
379                 switch(c) {
380
381                 case 'A':
382                         arch_fatal = FALSE;
383                         MFLAGS_append("-A", NULL);
384                         break;
385                 case 'C':
386                         if (chdir(optarg) == -1)
387                                 err(1, "chdir %s", optarg);
388                         break;
389                 case 'D':
390                         Var_SetGlobal(optarg, "1");
391                         MFLAGS_append("-D", optarg);
392                         break;
393                 case 'I':
394                         Parse_AddIncludeDir(optarg);
395                         MFLAGS_append("-I", optarg);
396                         break;
397                 case 'V':
398                         Lst_AtEnd(&variables, estrdup(optarg));
399                         MFLAGS_append("-V", optarg);
400                         break;
401                 case 'X':
402                         expandVars = FALSE;
403                         break;
404                 case 'B':
405                         compatMake = TRUE;
406                         MFLAGS_append("-B", NULL);
407                         unsetenv("MAKE_JOBS_FIFO");
408                         break;
409                 case 'P':
410                         usePipes = FALSE;
411                         MFLAGS_append("-P", NULL);
412                         break;
413                 case 'S':
414                         keepgoing = FALSE;
415                         MFLAGS_append("-S", NULL);
416                         break;
417                 case 'd': {
418                         char *modules = optarg;
419
420                         for (; *modules; ++modules)
421                                 switch (*modules) {
422                                 case 'A':
423                                         debug = ~0;
424                                         break;
425                                 case 'a':
426                                         debug |= DEBUG_ARCH;
427                                         break;
428                                 case 'c':
429                                         debug |= DEBUG_COND;
430                                         break;
431                                 case 'd':
432                                         debug |= DEBUG_DIR;
433                                         break;
434                                 case 'f':
435                                         debug |= DEBUG_FOR;
436                                         break;
437                                 case 'g':
438                                         if (modules[1] == '1') {
439                                                 debug |= DEBUG_GRAPH1;
440                                                 ++modules;
441                                         }
442                                         else if (modules[1] == '2') {
443                                                 debug |= DEBUG_GRAPH2;
444                                                 ++modules;
445                                         }
446                                         break;
447                                 case 'j':
448                                         debug |= DEBUG_JOB;
449                                         break;
450                                 case 'l':
451                                         debug |= DEBUG_LOUD;
452                                         break;
453                                 case 'm':
454                                         debug |= DEBUG_MAKE;
455                                         break;
456                                 case 's':
457                                         debug |= DEBUG_SUFF;
458                                         break;
459                                 case 't':
460                                         debug |= DEBUG_TARG;
461                                         break;
462                                 case 'v':
463                                         debug |= DEBUG_VAR;
464                                         break;
465                                 default:
466                                         warnx("illegal argument to d option "
467                                             "-- %c", *modules);
468                                         usage();
469                                 }
470                         MFLAGS_append("-d", optarg);
471                         break;
472                 }
473                 case 'E':
474                         Lst_AtEnd(&envFirstVars, estrdup(optarg));
475                         MFLAGS_append("-E", optarg);
476                         break;
477                 case 'e':
478                         checkEnvFirst = TRUE;
479                         MFLAGS_append("-e", NULL);
480                         break;
481                 case 'f':
482                         Lst_AtEnd(&makefiles, estrdup(optarg));
483                         break;
484                 case 'i':
485                         ignoreErrors = TRUE;
486                         MFLAGS_append("-i", NULL);
487                         break;
488                 case 'j': {
489                         char *endptr;
490
491                         forceJobs = TRUE;
492                         jobLimit = strtol(optarg, &endptr, 10);
493                         if (jobLimit <= 0 || *endptr != '\0') {
494                                 warnx("illegal number, -j argument -- %s",
495                                     optarg);
496                                 usage();
497                         }
498                         MFLAGS_append("-j", optarg);
499                         break;
500                 }
501                 case 'k':
502                         keepgoing = TRUE;
503                         MFLAGS_append("-k", NULL);
504                         break;
505                 case 'm':
506                         Path_AddDir(&sysIncPath, optarg);
507                         MFLAGS_append("-m", optarg);
508                         break;
509                 case 'n':
510                         noExecute = TRUE;
511                         MFLAGS_append("-n", NULL);
512                         break;
513                 case 'q':
514                         queryFlag = TRUE;
515                         /* Kind of nonsensical, wot? */
516                         MFLAGS_append("-q", NULL);
517                         break;
518                 case 'r':
519                         noBuiltins = TRUE;
520                         MFLAGS_append("-r", NULL);
521                         break;
522                 case 's':
523                         beSilent = TRUE;
524                         MFLAGS_append("-s", NULL);
525                         break;
526                 case 't':
527                         touchFlag = TRUE;
528                         MFLAGS_append("-t", NULL);
529                         break;
530                 case 'v':
531                         beVerbose = TRUE;
532                         MFLAGS_append("-v", NULL);
533                         break;
534                 case 'x':
535                         if (Main_ParseWarn(optarg, 1) != -1)
536                                 MFLAGS_append("-x", optarg);
537                         break;
538
539                 default:
540                 case '?':
541                         usage();
542                 }
543         }
544         argv += optind;
545         argc -= optind;
546
547         oldVars = TRUE;
548
549         /*
550          * Parse the rest of the arguments.
551          *      o Check for variable assignments and perform them if so.
552          *      o Check for more flags and restart getopt if so.
553          *      o Anything else is taken to be a target and added
554          *        to the end of the "create" list.
555          */
556         for (; *argv != NULL; ++argv, --argc) {
557                 if (Parse_IsVar(*argv)) {
558                         char *ptr = MAKEFLAGS_quote(*argv);
559                         char *v = estrdup(*argv);
560
561                         Var_Append(".MAKEFLAGS", ptr, VAR_GLOBAL);
562                         Parse_DoVar(v, VAR_CMD);
563                         free(ptr);
564                         free(v);
565
566                 } else if ((*argv)[0] == '-') {
567                         if ((*argv)[1] == '\0') {
568                                 /*
569                                  * (*argv) is a single dash, so we
570                                  * just ignore it.
571                                  */
572                         } else if (found_dd) {
573                                 /*
574                                  * Double dash has been found, ignore
575                                  * any more options.  But what do we do
576                                  * with it?  For now treat it like a target.
577                                  */
578                                 Lst_AtEnd(&create, estrdup(*argv));
579                         } else {
580                                 /*
581                                  * (*argv) is a -flag, so backup argv and
582                                  * argc.  getopt() expects options to start
583                                  * in the 2nd position.
584                                  */
585                                 argc++;
586                                 argv--;
587                                 goto rearg;
588                         }
589
590                 } else if ((*argv)[0] == '\0') {
591                         Punt("illegal (null) argument.");
592
593                 } else {
594                         Lst_AtEnd(&create, estrdup(*argv));
595                 }
596         }
597 }
598
599 /**
600  * Main_ParseArgLine
601  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
602  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
603  *      Takes a line of arguments and breaks it into its
604  *      component words and passes those words and the number of them to the
605  *      MainParseArgs function.
606  *      The line should have all its leading whitespace removed.
607  *
608  * Side Effects:
609  *      Only those that come from the various arguments.
610  */
611 void
612 Main_ParseArgLine(char *line, int mflags)
613 {
614         ArgArray        aa;
615
616         if (line == NULL)
617                 return;
618         for (; *line == ' '; ++line)
619                 continue;
620         if (!*line)
621                 return;
622
623         if (mflags)
624                 MAKEFLAGS_break(&aa, line);
625         else
626                 brk_string(&aa, line, TRUE);
627
628         MainParseArgs(aa.argc, aa.argv);
629         ArgArray_Done(&aa);
630 }
631
632 static char *
633 chdir_verify_path(const char *path, char *obpath)
634 {
635         struct stat sb;
636
637         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
638                 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
639                         warn("warning: %s", path);
640                         return (NULL);
641                 }
642                 return (obpath);
643         }
644
645         return (NULL);
646 }
647
648 /**
649  * In lieu of a good way to prevent every possible looping in make(1), stop
650  * there from being more than MKLVL_MAXVAL processes forked by make(1), to
651  * prevent a forkbomb from happening, in a dumb and mechanical way.
652  *
653  * Side Effects:
654  *      Creates or modifies enviornment variable MKLVL_ENVVAR via setenv().
655  */
656 static void
657 check_make_level(void)
658 {
659 #ifdef WANT_ENV_MKLVL
660         char    *value = getenv(MKLVL_ENVVAR);
661         int     level = (value == NULL) ? 0 : atoi(value);
662
663         if (level < 0) {
664                 errc(2, EAGAIN, "Invalid value for recursion level (%d).",
665                     level);
666         } else if (level > MKLVL_MAXVAL) {
667                 errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
668                     MKLVL_MAXVAL);
669         } else {
670                 char new_value[32];
671                 sprintf(new_value, "%d", level + 1);
672                 setenv(MKLVL_ENVVAR, new_value, 1);
673         }
674 #endif /* WANT_ENV_MKLVL */
675 }
676
677 /**
678  * Main_AddSourceMakefile
679  *      Add a file to the list of source makefiles
680  */
681 void
682 Main_AddSourceMakefile(const char *name)
683 {
684
685         Lst_AtEnd(&source_makefiles, estrdup(name));
686 }
687
688 /**
689  * Remake_Makefiles
690  *      Remake all the makefiles
691  */
692 static void
693 Remake_Makefiles(void)
694 {
695         LstNode *ln;
696         int error_cnt = 0;
697         int remade_cnt = 0;
698
699         Compat_InstallSignalHandlers();
700         if (curdir != objdir) {
701                 if (chdir(curdir) < 0)
702                         Fatal("Failed to change directory to %s.", curdir);
703         }
704
705         LST_FOREACH(ln, &source_makefiles) {
706                 LstNode *ln2;
707                 struct GNode *gn;
708                 const char *name = Lst_Datum(ln);
709                 Boolean saveTouchFlag = touchFlag;
710                 Boolean saveQueryFlag = queryFlag;
711                 Boolean saveNoExecute = noExecute;
712                 int mtime;
713
714                 /*
715                  * Create node
716                  */
717                 gn = Targ_FindNode(name, TARG_CREATE);
718                 DEBUGF(MAKE, ("Checking %s...", gn->name));
719                 Suff_FindDeps(gn);
720
721                 /*
722                  * ! dependencies as well as
723                  * dependencies with .FORCE, .EXEC and .PHONY attributes
724                  * are skipped to prevent infinite loops
725                  */
726                 if (gn->type & (OP_FORCE | OP_EXEC | OP_PHONY)) {
727                         DEBUGF(MAKE, ("skipping (force, exec or phony).\n",
728                             gn->name));
729                         continue;
730                 }
731
732                 /*
733                  * Skip :: targets that have commands and no children
734                  * because such targets are always out-of-date
735                  */
736                 if ((gn->type & OP_DOUBLEDEP) &&
737                     !Lst_IsEmpty(&gn->commands) &&
738                     Lst_IsEmpty(&gn->children)) {
739                         DEBUGF(MAKE, ("skipping (doubledep, no sources "
740                             "and has commands).\n"));
741                         continue;
742                 }
743
744                 /*
745                  * Skip targets without sources and without commands
746                  */
747                 if (Lst_IsEmpty(&gn->commands) &&
748                     Lst_IsEmpty(&gn->children)) {
749                         DEBUGF(MAKE,
750                             ("skipping (no sources and no commands).\n"));
751                         continue;
752                 }
753
754                 DEBUGF(MAKE, ("\n"));
755
756                 /*
757                  * -t, -q and -n has no effect unless the makefile is
758                  * specified as one of the targets explicitly in the
759                  * command line
760                  */
761                 LST_FOREACH(ln2, &create) {
762                         if (!strcmp(gn->name, Lst_Datum(ln2))) {
763                                 /* found as a target */
764                                 break;
765                         }
766                 }
767                 if (ln2 == NULL) {
768                         touchFlag = FALSE;
769                         queryFlag = FALSE;
770                         noExecute = FALSE;
771                 }
772
773                 /*
774                  * Check and remake the makefile
775                  */
776                 mtime = Dir_MTime(gn);
777                 Compat_Make(gn, gn);
778
779                 /*
780                  * Restore -t, -q and -n behaviour
781                  */
782                 touchFlag = saveTouchFlag;
783                 queryFlag = saveQueryFlag;
784                 noExecute = saveNoExecute;
785
786                 /*
787                  * Compat_Make will leave the 'made' field of gn
788                  * in one of the following states:
789                  *      UPTODATE  gn was already up-to-date
790                  *      MADE      gn was recreated successfully
791                  *      ERROR     An error occurred while gn was being created
792                  *      ABORTED   gn was not remade because one of its inferiors
793                  *                could not be made due to errors.
794                  */
795                 if (gn->made == MADE) {
796                         if (mtime != Dir_MTime(gn)) {
797                                 DEBUGF(MAKE,
798                                     ("%s updated (%d -> %d).\n",
799                                      gn->name, mtime, gn->mtime));
800                                 remade_cnt++;
801                         } else {
802                                 DEBUGF(MAKE,
803                                     ("%s not updated: skipping restart.\n",
804                                      gn->name));
805                         }
806                 } else if (gn->made == ERROR)
807                         error_cnt++;
808                 else if (gn->made == ABORTED) {
809                         printf("`%s' not remade because of errors.\n",
810                             gn->name);
811                         error_cnt++;
812                 } else if (gn->made == UPTODATE) {
813                         Lst examine;
814
815                         Lst_Init(&examine);
816                         Lst_EnQueue(&examine, gn);
817                         while (!Lst_IsEmpty(&examine)) {
818                                 LstNode *eln;
819                                 GNode *egn = Lst_DeQueue(&examine);
820
821                                 egn->make = FALSE;
822                                 LST_FOREACH(eln, &egn->children) {
823                                         GNode *cgn = Lst_Datum(eln);
824
825                                         Lst_EnQueue(&examine, cgn);
826                                 }
827                         }
828                 }
829         }
830
831         if (error_cnt > 0)
832                 Fatal("Failed to remake Makefiles.");
833         if (remade_cnt > 0) {
834                 DEBUGF(MAKE, ("Restarting `%s'.\n", save_argv[0]));
835
836                 /*
837                  * Some of makefiles were remade -- restart from clean state
838                  */
839                 if (save_makeflags != NULL)
840                         setenv("MAKEFLAGS", save_makeflags, 1);
841                 else
842                         unsetenv("MAKEFLAGS");
843                 if (execvp(save_argv[0], save_argv) < 0) {
844                         Fatal("Can't restart `%s': %s.",
845                             save_argv[0], strerror(errno));
846                 }
847         }
848
849         if (curdir != objdir) {
850                 if (chdir(objdir) < 0)
851                         Fatal("Failed to change directory to %s.", objdir);
852         }
853 }
854
855 /**
856  * main
857  *      The main function, for obvious reasons. Initializes variables
858  *      and a few modules, then parses the arguments give it in the
859  *      environment and on the command line. Reads the system makefile
860  *      followed by either Makefile, makefile or the file given by the
861  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
862  *      flags it has received by then uses either the Make or the Compat
863  *      module to create the initial list of targets.
864  *
865  * Results:
866  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
867  *      0.
868  *
869  * Side Effects:
870  *      The program exits when done. Targets are created. etc. etc. etc.
871  */
872 int
873 main(int argc, char **argv)
874 {
875         const char *machine;
876         const char *machine_arch;
877         const char *machine_cpu;
878         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
879         const char *p;
880         const char *pathp;
881         const char *path;
882         char mdpath[MAXPATHLEN];
883         char obpath[MAXPATHLEN];
884         char cdpath[MAXPATHLEN];
885         char *cp = NULL, *start;
886
887         save_argv = argv;
888         save_makeflags = getenv("MAKEFLAGS");
889         if (save_makeflags != NULL)
890                 save_makeflags = estrdup(save_makeflags);
891
892         /*
893          * Initialize file global variables.
894          */
895         expandVars = TRUE;
896         noBuiltins = FALSE;             /* Read the built-in rules */
897         forceJobs = FALSE;              /* No -j flag */
898         curdir = cdpath;
899
900         /*
901          * Initialize program global variables.
902          */
903         beSilent = FALSE;               /* Print commands as executed */
904         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
905         noExecute = FALSE;              /* Execute all commands */
906         keepgoing = FALSE;              /* Stop on error */
907         allPrecious = FALSE;            /* Remove targets when interrupted */
908         queryFlag = FALSE;              /* This is not just a check-run */
909         touchFlag = FALSE;              /* Actually update targets */
910         usePipes = TRUE;                /* Catch child output in pipes */
911         debug = 0;                      /* No debug verbosity, please. */
912         jobsRunning = FALSE;
913
914         jobLimit = DEFMAXJOBS;
915         compatMake = FALSE;             /* No compat mode */
916
917         check_make_level();
918
919 #ifdef RLIMIT_NOFILE
920         /*
921          * get rid of resource limit on file descriptors
922          */
923         {
924                 struct rlimit rl;
925                 if (getrlimit(RLIMIT_NOFILE, &rl) == -1) {
926                         err(2, "getrlimit");
927                 }
928                 rl.rlim_cur = rl.rlim_max;
929                 if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
930                         err(2, "setrlimit");
931                 }
932         }
933 #endif
934
935         /*
936          * Prior to 7.0, FreeBSD/pc98 kernel used to set the
937          * utsname.machine to "i386", and MACHINE was defined as
938          * "i386", so it could not be distinguished from FreeBSD/i386.
939          * Therefore, we had to check machine.ispc98 and adjust the
940          * MACHINE variable.  NOTE: The code is still here to be able
941          * to compile new make binary on old FreeBSD/pc98 systems, and
942          * have the MACHINE variable set properly.
943          */
944         if ((machine = getenv("MACHINE")) == NULL) {
945                 int     ispc98;
946                 size_t  len;
947
948                 len = sizeof(ispc98);
949                 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
950                         if (ispc98)
951                                 machine = "pc98";
952                 }
953         }
954
955         /*
956          * Get the name of this type of MACHINE from utsname
957          * so we can share an executable for similar machines.
958          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
959          *
960          * Note that both MACHINE and MACHINE_ARCH are decided at
961          * run-time.
962          */
963         if (machine == NULL) {
964                 static struct utsname utsname;
965
966                 if (uname(&utsname) == -1)
967                         err(2, "uname");
968                 machine = utsname.machine;
969         }
970
971         if ((machine_arch = getenv("MACHINE_ARCH")) == NULL) {
972 #ifdef MACHINE_ARCH
973                 machine_arch = MACHINE_ARCH;
974 #else
975                 machine_arch = "unknown";
976 #endif
977         }
978
979         /*
980          * Set machine_cpu to the minumum supported CPU revision based
981          * on the target architecture, if not already set.
982          */
983         if ((machine_cpu = getenv("MACHINE_CPU")) == NULL) {
984                 if (!strcmp(machine_arch, "i386"))
985                         machine_cpu = "i386";
986                 else if (!strcmp(machine_arch, "alpha"))
987                         machine_cpu = "ev4";
988                 else
989                         machine_cpu = "unknown";
990         }
991
992         /*
993          * Initialize the parsing, directory and variable modules to prepare
994          * for the reading of inclusion paths and variable settings on the
995          * command line
996          */
997         Proc_Init();
998
999         Dir_Init();             /* Initialize directory structures so -I flags
1000                                  * can be processed correctly */
1001         Var_Init(environ);      /* As well as the lists of variables for
1002                                  * parsing arguments */
1003
1004         /*
1005          * Initialize the Shell so that we have a shell for != assignments
1006          * on the command line.
1007          */
1008         Shell_Init();
1009
1010         /*
1011          * Initialize various variables.
1012          *      MAKE also gets this name, for compatibility
1013          *      .MAKEFLAGS gets set to the empty string just in case.
1014          *      MFLAGS also gets initialized empty, for compatibility.
1015          */
1016         Var_SetGlobal("MAKE", argv[0]);
1017         Var_SetGlobal(".MAKEFLAGS", "");
1018         Var_SetGlobal("MFLAGS", "");
1019         Var_SetGlobal("MACHINE", machine);
1020         Var_SetGlobal("MACHINE_ARCH", machine_arch);
1021         Var_SetGlobal("MACHINE_CPU", machine_cpu);
1022 #ifdef MAKE_VERSION
1023         Var_SetGlobal("MAKE_VERSION", MAKE_VERSION);
1024 #endif
1025
1026         /*
1027          * First snag things out of the MAKEFLAGS environment
1028          * variable.  Then parse the command line arguments.
1029          */
1030         Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
1031
1032         MainParseArgs(argc, argv);
1033
1034         /*
1035          * Find where we are...
1036          */
1037         if (getcwd(curdir, MAXPATHLEN) == NULL)
1038                 err(2, NULL);
1039
1040         {
1041         struct stat sa;
1042
1043         if (stat(curdir, &sa) == -1)
1044             err(2, "%s", curdir);
1045         }
1046
1047         /*
1048          * The object directory location is determined using the
1049          * following order of preference:
1050          *
1051          *      1. MAKEOBJDIRPREFIX`cwd`
1052          *      2. MAKEOBJDIR
1053          *      3. PATH_OBJDIR.${MACHINE}
1054          *      4. PATH_OBJDIR
1055          *      5. PATH_OBJDIRPREFIX`cwd`
1056          *
1057          * If one of the first two fails, use the current directory.
1058          * If the remaining three all fail, use the current directory.
1059          *
1060          * Once things are initted,
1061          * have to add the original directory to the search path,
1062          * and modify the paths for the Makefiles apropriately.  The
1063          * current directory is also placed as a variable for make scripts.
1064          */
1065         if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
1066                 if (!(path = getenv("MAKEOBJDIR"))) {
1067                         path = PATH_OBJDIR;
1068                         pathp = PATH_OBJDIRPREFIX;
1069                         snprintf(mdpath, MAXPATHLEN, "%s.%s", path, machine);
1070                         if (!(objdir = chdir_verify_path(mdpath, obpath)))
1071                                 if (!(objdir=chdir_verify_path(path, obpath))) {
1072                                         snprintf(mdpath, MAXPATHLEN,
1073                                                         "%s%s", pathp, curdir);
1074                                         if (!(objdir=chdir_verify_path(mdpath,
1075                                                                        obpath)))
1076                                                 objdir = curdir;
1077                                 }
1078                 }
1079                 else if (!(objdir = chdir_verify_path(path, obpath)))
1080                         objdir = curdir;
1081         }
1082         else {
1083                 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
1084                 if (!(objdir = chdir_verify_path(mdpath, obpath)))
1085                         objdir = curdir;
1086         }
1087         Dir_InitDot();          /* Initialize the "." directory */
1088         if (objdir != curdir)
1089                 Path_AddDir(&dirSearchPath, curdir);
1090         Var_SetGlobal(".ST_EXPORTVAR", "YES");
1091         Var_SetGlobal(".CURDIR", curdir);
1092         Var_SetGlobal(".OBJDIR", objdir);
1093
1094         if (getenv("MAKE_JOBS_FIFO") != NULL)
1095                 forceJobs = TRUE;
1096         /*
1097          * Be compatible if user did not specify -j and did not explicitly
1098          * turned compatibility on
1099          */
1100         if (!compatMake && !forceJobs)
1101                 compatMake = TRUE;
1102
1103         /*
1104          * Initialize target and suffix modules in preparation for
1105          * parsing the makefile(s)
1106          */
1107         Targ_Init();
1108         Suff_Init();
1109
1110         DEFAULT = NULL;
1111         time(&now);
1112
1113         /*
1114          * Set up the .TARGETS variable to contain the list of targets to be
1115          * created. If none specified, make the variable empty -- the parser
1116          * will fill the thing in with the default or .MAIN target.
1117          */
1118         if (Lst_IsEmpty(&create)) {
1119                 Var_SetGlobal(".TARGETS", "");
1120         } else {
1121                 LstNode *ln;
1122
1123                 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
1124                         char *name = Lst_Datum(ln);
1125
1126                         Var_Append(".TARGETS", name, VAR_GLOBAL);
1127                 }
1128         }
1129
1130
1131         /*
1132          * If no user-supplied system path was given (through the -m option)
1133          * add the directories from the DEFSYSPATH (more than one may be given
1134          * as dir1:...:dirn) to the system include path.
1135          */
1136         if (TAILQ_EMPTY(&sysIncPath)) {
1137                 char syspath[] = PATH_DEFSYSPATH;
1138
1139                 for (start = syspath; *start != '\0'; start = cp) {
1140                         for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1141                                 continue;
1142                         if (*cp == '\0') {
1143                                 Path_AddDir(&sysIncPath, start);
1144                         } else {
1145                                 *cp++ = '\0';
1146                                 Path_AddDir(&sysIncPath, start);
1147                         }
1148                 }
1149         }
1150
1151         /*
1152          * Read in the built-in rules first, followed by the specified
1153          * makefile, if it was (makefile != (char *) NULL), or the default
1154          * Makefile and makefile, in that order, if it wasn't.
1155          */
1156         if (!noBuiltins) {
1157                 /* Path of sys.mk */
1158                 Lst sysMkPath = Lst_Initializer(sysMkPath);
1159                 LstNode *ln;
1160                 char    defsysmk[] = PATH_DEFSYSMK;
1161
1162                 Path_Expand(defsysmk, &sysIncPath, &sysMkPath);
1163                 if (Lst_IsEmpty(&sysMkPath))
1164                         Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
1165                 LST_FOREACH(ln, &sysMkPath) {
1166                         if (!ReadMakefile(Lst_Datum(ln)))
1167                                 break;
1168                 }
1169                 if (ln != NULL)
1170                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
1171                 Lst_Destroy(&sysMkPath, free);
1172         }
1173
1174         if (!Lst_IsEmpty(&makefiles)) {
1175                 LstNode *ln;
1176
1177                 LST_FOREACH(ln, &makefiles) {
1178                         if (!TryReadMakefile(Lst_Datum(ln)))
1179                                 break;
1180                 }
1181                 if (ln != NULL)
1182                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
1183         } else if (!TryReadMakefile("BSDmakefile"))
1184             if (!TryReadMakefile("makefile"))
1185                 TryReadMakefile("Makefile");
1186
1187         ReadMakefile(".depend");
1188
1189         /* Install all the flags into the MAKEFLAGS envariable. */
1190         if (((p = Var_Value(".MAKEFLAGS", VAR_GLOBAL)) != NULL) && *p)
1191                 setenv("MAKEFLAGS", p, 1);
1192         else
1193                 setenv("MAKEFLAGS", "", 1);
1194
1195         /*
1196          * For compatibility, look at the directories in the VPATH variable
1197          * and add them to the search path, if the variable is defined. The
1198          * variable's value is in the same format as the PATH envariable, i.e.
1199          * <directory>:<directory>:<directory>...
1200          */
1201         if (Var_Exists("VPATH", VAR_CMD)) {
1202                 /*
1203                  * GCC stores string constants in read-only memory, but
1204                  * Var_Subst will want to write this thing, so store it
1205                  * in an array
1206                  */
1207                 static char VPATH[] = "${VPATH}";
1208                 Buffer  *buf;
1209                 char    *vpath;
1210                 char    *ptr;
1211                 char    savec;
1212
1213                 buf = Var_Subst(VPATH, VAR_CMD, FALSE);
1214
1215                 vpath = Buf_Data(buf);
1216                 do {
1217                         /* skip to end of directory */
1218                         for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
1219                                 ;
1220
1221                         /* Save terminator character so know when to stop */
1222                         savec = *ptr;
1223                         *ptr = '\0';
1224
1225                         /* Add directory to search path */
1226                         Path_AddDir(&dirSearchPath, vpath);
1227
1228                         vpath = ptr + 1;
1229                 } while (savec != '\0');
1230
1231                 Buf_Destroy(buf, TRUE);
1232         }
1233
1234         /*
1235          * Now that all search paths have been read for suffixes et al, it's
1236          * time to add the default search path to their lists...
1237          */
1238         Suff_DoPaths();
1239
1240         /* print the initial graph, if the user requested it */
1241         if (DEBUG(GRAPH1))
1242                 Targ_PrintGraph(1);
1243
1244         /* print the values of any variables requested by the user */
1245         if (Lst_IsEmpty(&variables)) {
1246                 /*
1247                  * Since the user has not requested that any variables
1248                  * be printed, we can build targets.
1249                  *
1250                  * Have read the entire graph and need to make a list of targets
1251                  * to create. If none was given on the command line, we consult
1252                  * the parsing module to find the main target(s) to create.
1253                  */
1254                 Lst targs = Lst_Initializer(targs);
1255
1256                 if (!is_posix && mfAutoDeps) {
1257                         /*
1258                          * Check if any of the makefiles are out-of-date.
1259                          */
1260                         Remake_Makefiles();
1261                 }
1262
1263                 if (Lst_IsEmpty(&create))
1264                         Parse_MainName(&targs);
1265                 else
1266                         Targ_FindList(&targs, &create, TARG_CREATE);
1267
1268                 if (compatMake) {
1269                         /*
1270                          * Compat_Init will take care of creating
1271                          * all the targets as well as initializing
1272                          * the module.
1273                          */
1274                         Compat_Run(&targs);
1275                         outOfDate = 0;
1276                 } else {
1277                         /*
1278                          * Initialize job module before traversing
1279                          * the graph, now that any .BEGIN and .END
1280                          * targets have been read.  This is done
1281                          * only if the -q flag wasn't given (to
1282                          * prevent the .BEGIN from being executed
1283                          * should it exist).
1284                          */
1285                         if (!queryFlag) {
1286                                 Job_Init(jobLimit);
1287                                 jobsRunning = TRUE;
1288                         }
1289
1290                         /* Traverse the graph, checking on all the targets */
1291                         outOfDate = Make_Run(&targs);
1292                 }
1293                 Lst_Destroy(&targs, NOFREE);
1294
1295         } else {
1296                 Var_Print(&variables, expandVars);
1297         }
1298
1299         Lst_Destroy(&variables, free);
1300         Lst_Destroy(&makefiles, free);
1301         Lst_Destroy(&source_makefiles, free);
1302         Lst_Destroy(&create, free);
1303
1304         /* print the graph now it's been processed if the user requested it */
1305         if (DEBUG(GRAPH2))
1306                 Targ_PrintGraph(2);
1307
1308         if (queryFlag && outOfDate)
1309                 return (1);
1310         else
1311                 return (0);
1312 }
1313