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