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