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