FreeBSD-Date: 2005/04/01 10:53:43
[dragonfly.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  * @(#) Copyright (c) 1988, 1989, 1990, 1993 The Regents of the University of California.  All rights reserved.
39  * @(#)main.c   8.3 (Berkeley) 3/19/94
40  * $FreeBSD: src/usr.bin/make/main.c,v 1.118 2005/02/13 13:33:56 harti Exp $
41  * $DragonFly: src/usr.bin/make/main.c,v 1.68 2005/04/07 00:44:18 okumoto Exp $
42  */
43
44 /*
45  * main.c
46  *      The main file for this entire program. Exit routines etc
47  *      reside here.
48  *
49  * Utility functions defined in this file:
50  *      Main_ParseArgLine
51  *                      Takes a line of arguments, breaks them and
52  *                      treats them as if they were given when first
53  *                      invoked. Used by the parse module to implement
54  *                      the .MFLAGS target.
55  */
56
57 #ifndef MACHINE
58 #include <sys/utsname.h>
59 #endif
60 #include <sys/param.h>
61 #include <sys/stat.h>
62 #include <sys/time.h>
63 #include <sys/queue.h>
64 #include <sys/resource.h>
65 #include <sys/wait.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <signal.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <unistd.h>
72
73 #include "arch.h"
74 #include "buf.h"
75 #include "compat.h"
76 #include "config.h"
77 #include "dir.h"
78 #include "globals.h"
79 #include "job.h"
80 #include "make.h"
81 #include "nonints.h"
82 #include "parse.h"
83 #include "pathnames.h"
84 #include "str.h"
85 #include "suff.h"
86 #include "targ.h"
87 #include "util.h"
88 #include "var.h"
89
90 #define WANT_ENV_MKLVL  1
91 #define MKLVL_MAXVAL    500
92 #define MKLVL_ENVVAR    "__MKLVL__"
93
94 #define MAKEFLAGS       ".MAKEFLAGS"
95
96 /* Targets to be made */
97 Lst create = Lst_Initializer(create);
98
99 time_t          now;            /* Time at start of make */
100 struct GNode    *DEFAULT;       /* .DEFAULT node */
101 Boolean         allPrecious;    /* .PRECIOUS given on line by itself */
102
103 static Boolean  noBuiltins;     /* -r flag */
104
105 /* ordered list of makefiles to read */
106 static Lst makefiles = Lst_Initializer(makefiles);
107
108 static Boolean  expandVars;     /* fully expand printed variables */
109
110 /* list of variables to print */
111 static Lst variables = Lst_Initializer(variables);
112
113 int             maxJobs;        /* -j argument */
114 static Boolean  forceJobs;      /* -j argument given */
115 Boolean         compatMake;     /* -B argument */
116 Boolean         debug;          /* -d flag */
117 Boolean         noExecute;      /* -n flag */
118 Boolean         keepgoing;      /* -k flag */
119 Boolean         queryFlag;      /* -q flag */
120 Boolean         touchFlag;      /* -t flag */
121 Boolean         usePipes;       /* !-P flag */
122 Boolean         ignoreErrors;   /* -i flag */
123 Boolean         beSilent;       /* -s flag */
124 Boolean         beVerbose;      /* -v flag */
125 Boolean         oldVars;        /* variable substitution style */
126 Boolean         checkEnvFirst;  /* -e flag */
127
128 /* (-E) vars to override from env */
129 Lst envFirstVars = Lst_Initializer(envFirstVars);
130
131 Boolean         jobsRunning;    /* TRUE if the jobs might be running */
132
133 static void     MainParseArgs(int, char **);
134 char            *chdir_verify_path(const char *, char *);
135 static int      ReadMakefile(const char *);
136 static void     usage(void);
137
138 static char     *curdir;        /* startup directory */
139 static char     *objdir;        /* where we chdir'ed to */
140
141 /**
142  * MFLAGS_append
143  *      Append a flag with an optional argument to MAKEFLAGS and MFLAGS
144  */
145 static void
146 MFLAGS_append(const char *flag, char *arg)
147 {
148         char *str;
149
150         Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
151         if (arg != NULL) {
152                 str = MAKEFLAGS_quote(arg);
153                 Var_Append(MAKEFLAGS, str, VAR_GLOBAL);
154                 free(str);
155         }
156
157         Var_Append("MFLAGS", flag, VAR_GLOBAL);
158         if (arg != NULL) {
159                 str = MAKEFLAGS_quote(arg);
160                 Var_Append("MFLAGS", str, VAR_GLOBAL);
161                 free(str);
162         }
163 }
164
165 /**
166  * MainParseArgs
167  *      Parse a given argument vector. Called from main() and from
168  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
169  *
170  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
171  *
172  * Side Effects:
173  *      Various global and local flags will be set depending on the flags
174  *      given
175  */
176 static void
177 MainParseArgs(int argc, char **argv)
178 {
179         int c;
180
181 rearg:
182         optind = 1;     /* since we're called more than once */
183 #define OPTFLAGS "ABC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
184         while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
185                 switch(c) {
186
187                 case 'A':
188                         arch_fatal = FALSE;
189                         MFLAGS_append("-A", NULL);
190                         break;
191                 case 'C':
192                         if (chdir(optarg) == -1)
193                                 err(1, "chdir %s", optarg);
194                         break;
195                 case 'D':
196                         Var_Set(optarg, "1", VAR_GLOBAL);
197                         MFLAGS_append("-D", optarg);
198                         break;
199                 case 'I':
200                         Parse_AddIncludeDir(optarg);
201                         MFLAGS_append("-I", optarg);
202                         break;
203                 case 'V':
204                         Lst_AtEnd(&variables, estrdup(optarg));
205                         MFLAGS_append("-V", optarg);
206                         break;
207                 case 'X':
208                         expandVars = FALSE;
209                         break;
210                 case 'B':
211                         compatMake = TRUE;
212                         MFLAGS_append("-B", NULL);
213                         unsetenv("MAKE_JOBS_FIFO");
214                         break;
215                 case 'P':
216                         usePipes = FALSE;
217                         MFLAGS_append("-P", NULL);
218                         break;
219                 case 'S':
220                         keepgoing = FALSE;
221                         MFLAGS_append("-S", NULL);
222                         break;
223                 case 'd': {
224                         char *modules = optarg;
225
226                         for (; *modules; ++modules)
227                                 switch (*modules) {
228                                 case 'A':
229                                         debug = ~0;
230                                         break;
231                                 case 'a':
232                                         debug |= DEBUG_ARCH;
233                                         break;
234                                 case 'c':
235                                         debug |= DEBUG_COND;
236                                         break;
237                                 case 'd':
238                                         debug |= DEBUG_DIR;
239                                         break;
240                                 case 'f':
241                                         debug |= DEBUG_FOR;
242                                         break;
243                                 case 'g':
244                                         if (modules[1] == '1') {
245                                                 debug |= DEBUG_GRAPH1;
246                                                 ++modules;
247                                         }
248                                         else if (modules[1] == '2') {
249                                                 debug |= DEBUG_GRAPH2;
250                                                 ++modules;
251                                         }
252                                         break;
253                                 case 'j':
254                                         debug |= DEBUG_JOB;
255                                         break;
256                                 case 'l':
257                                         debug |= DEBUG_LOUD;
258                                         break;
259                                 case 'm':
260                                         debug |= DEBUG_MAKE;
261                                         break;
262                                 case 's':
263                                         debug |= DEBUG_SUFF;
264                                         break;
265                                 case 't':
266                                         debug |= DEBUG_TARG;
267                                         break;
268                                 case 'v':
269                                         debug |= DEBUG_VAR;
270                                         break;
271                                 default:
272                                         warnx("illegal argument to d option "
273                                             "-- %c", *modules);
274                                         usage();
275                                 }
276                         MFLAGS_append("-d", optarg);
277                         break;
278                 }
279                 case 'E':
280                         Lst_AtEnd(&envFirstVars, estrdup(optarg));
281                         MFLAGS_append("-E", optarg);
282                         break;
283                 case 'e':
284                         checkEnvFirst = TRUE;
285                         MFLAGS_append("-e", NULL);
286                         break;
287                 case 'f':
288                         Lst_AtEnd(&makefiles, estrdup(optarg));
289                         break;
290                 case 'i':
291                         ignoreErrors = TRUE;
292                         MFLAGS_append("-i", NULL);
293                         break;
294                 case 'j': {
295                         char *endptr;
296
297                         forceJobs = TRUE;
298                         maxJobs = strtol(optarg, &endptr, 10);
299                         if (maxJobs <= 0 || *endptr != '\0') {
300                                 warnx("illegal number, -j argument -- %s",
301                                     optarg);
302                                 usage();
303                         }
304                         MFLAGS_append("-j", optarg);
305                         break;
306                 }
307                 case 'k':
308                         keepgoing = TRUE;
309                         MFLAGS_append("-k", NULL);
310                         break;
311                 case 'm':
312                         Path_AddDir(&sysIncPath, optarg);
313                         MFLAGS_append("-m", optarg);
314                         break;
315                 case 'n':
316                         noExecute = TRUE;
317                         MFLAGS_append("-n", NULL);
318                         break;
319                 case 'q':
320                         queryFlag = TRUE;
321                         /* Kind of nonsensical, wot? */
322                         MFLAGS_append("-q", NULL);
323                         break;
324                 case 'r':
325                         noBuiltins = TRUE;
326                         MFLAGS_append("-r", NULL);
327                         break;
328                 case 's':
329                         beSilent = TRUE;
330                         MFLAGS_append("-s", NULL);
331                         break;
332                 case 't':
333                         touchFlag = TRUE;
334                         MFLAGS_append("-t", NULL);
335                         break;
336                 case 'v':
337                         beVerbose = TRUE;
338                         MFLAGS_append("-v", NULL);
339                         break;
340                 default:
341                 case '?':
342                         usage();
343                 }
344         }
345
346         oldVars = TRUE;
347
348         /*
349          * See if the rest of the arguments are variable assignments and
350          * perform them if so. Else take them to be targets and stuff them
351          * on the end of the "create" list.
352          */
353         for (argv += optind, argc -= optind; *argv; ++argv, --argc)
354                 if (Parse_IsVar(*argv)) {
355                         char *ptr = MAKEFLAGS_quote(*argv);
356
357                         Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
358                         free(ptr);
359
360                         Parse_DoVar(*argv, VAR_CMD);
361                 } else {
362                         if (!**argv)
363                                 Punt("illegal (null) argument.");
364                         if (**argv == '-') {
365                                 if ((*argv)[1]) {
366                                         argc++;
367                                         argv--;
368                                 }
369                                 goto rearg;
370                         }
371                         Lst_AtEnd(&create, estrdup(*argv));
372                 }
373 }
374
375 /**
376  * Main_ParseArgLine
377  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
378  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
379  *      Takes a line of arguments and breaks it into its
380  *      component words and passes those words and the number of them to the
381  *      MainParseArgs function.
382  *      The line should have all its leading whitespace removed.
383  *
384  * Side Effects:
385  *      Only those that come from the various arguments.
386  */
387 void
388 Main_ParseArgLine(char *line, int mflags)
389 {
390         char **argv;                    /* Manufactured argument vector */
391         int argc;                       /* Number of arguments in argv */
392
393         if (line == NULL)
394                 return;
395         for (; *line == ' '; ++line)
396                 continue;
397         if (!*line)
398                 return;
399
400         if (mflags)
401                 argv = MAKEFLAGS_break(line, &argc);
402         else
403                 argv = brk_string(line, &argc, TRUE);
404
405         MainParseArgs(argc, argv);
406 }
407
408 char *
409 chdir_verify_path(const char *path, char *obpath)
410 {
411         struct stat sb;
412
413         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
414                 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
415                         warn("warning: %s", path);
416                         return (NULL);
417                 }
418                 return (obpath);
419         }
420
421         return (NULL);
422 }
423
424 static void
425 catch_child(int sig __unused)
426 {
427 }
428
429 /*
430  * In lieu of a good way to prevent every possible looping in
431  * make(1), stop there from being more than MKLVL_MAXVAL processes forked
432  * by make(1), to prevent a forkbomb from happening, in a dumb and
433  * mechanical way.
434  */
435 static void
436 check_make_level(void)
437 {
438 #ifdef WANT_ENV_MKLVL
439         char    *value = getenv(MKLVL_ENVVAR);
440         int     level = (value == NULL) ? 0 : atoi(value);
441
442         if (level < 0) {
443                 errc(2, EAGAIN, "Invalid value for recursion level (%d).",
444                     level);
445         } else if (level > MKLVL_MAXVAL) {
446                 errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
447                     MKLVL_MAXVAL);
448         } else {
449                 char new_value[32];
450                 sprintf(new_value, "%d", level + 1);
451                 setenv(MKLVL_ENVVAR, new_value, 1);
452         }
453 #endif /* WANT_ENV_MKLVL */
454 }
455
456 /**
457  * main
458  *      The main function, for obvious reasons. Initializes variables
459  *      and a few modules, then parses the arguments give it in the
460  *      environment and on the command line. Reads the system makefile
461  *      followed by either Makefile, makefile or the file given by the
462  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
463  *      flags it has received by then uses either the Make or the Compat
464  *      module to create the initial list of targets.
465  *
466  * Results:
467  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
468  *      0.
469  *
470  * Side Effects:
471  *      The program exits when done. Targets are created. etc. etc. etc.
472  */
473 int
474 main(int argc, char **argv)
475 {
476         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
477         char *p, *p1;
478         const char *pathp;
479         const char *path;
480         char mdpath[MAXPATHLEN];
481         char obpath[MAXPATHLEN];
482         char cdpath[MAXPATHLEN];
483         const char *machine = getenv("MACHINE");
484         const char *machine_arch = getenv("MACHINE_ARCH");
485         const char *machine_cpu = getenv("MACHINE_CPU");
486         char *cp = NULL, *start;
487
488         /* avoid faults on read-only strings */
489         static char syspath[] = PATH_DEFSYSPATH;
490
491         {
492         /*
493          * Catch SIGCHLD so that we get kicked out of select() when we
494          * need to look at a child.  This is only known to matter for the
495          * -j case (perhaps without -P).
496          *
497          * XXX this is intentionally misplaced.
498          */
499         struct sigaction sa;
500
501         sigemptyset(&sa.sa_mask);
502         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
503         sa.sa_handler = catch_child;
504         sigaction(SIGCHLD, &sa, NULL);
505         }
506
507         check_make_level();
508
509 #if DEFSHELL == 2
510         /*
511          * Turn off ENV to make ksh happier.
512          */
513         unsetenv("ENV");
514 #endif
515
516 #ifdef RLIMIT_NOFILE
517         /*
518          * get rid of resource limit on file descriptors
519          */
520         {
521                 struct rlimit rl;
522                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
523                     rl.rlim_cur != rl.rlim_max) {
524                         rl.rlim_cur = rl.rlim_max;
525                         setrlimit(RLIMIT_NOFILE, &rl);
526                 }
527         }
528 #endif
529         /*
530          * Get the name of this type of MACHINE from utsname
531          * so we can share an executable for similar machines.
532          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
533          *
534          * Note that while MACHINE is decided at run-time,
535          * MACHINE_ARCH is always known at compile time.
536          */
537         if (!machine) {
538 #ifndef MACHINE
539                 static struct utsname utsname;
540
541                 if (uname(&utsname) == -1)
542                         err(2, "uname");
543                 machine = utsname.machine;
544 #else
545                 machine = MACHINE;
546 #endif
547         }
548
549         if (!machine_arch) {
550 #ifndef MACHINE_ARCH
551                 machine_arch = "unknown";
552 #else
553                 machine_arch = MACHINE_ARCH;
554 #endif
555         }
556
557         /*
558          * Set machine_cpu to the minumum supported CPU revision based
559          * on the target architecture, if not already set.
560          */
561         if (!machine_cpu) {
562                 if (!strcmp(machine_arch, "i386"))
563                         machine_cpu = "i386";
564                 else if (!strcmp(machine_arch, "alpha"))
565                         machine_cpu = "ev4";
566                 else
567                         machine_cpu = "unknown";
568         }
569
570         expandVars = TRUE;
571         beSilent = FALSE;               /* Print commands as executed */
572         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
573         noExecute = FALSE;              /* Execute all commands */
574         keepgoing = FALSE;              /* Stop on error */
575         allPrecious = FALSE;            /* Remove targets when interrupted */
576         queryFlag = FALSE;              /* This is not just a check-run */
577         noBuiltins = FALSE;             /* Read the built-in rules */
578         touchFlag = FALSE;              /* Actually update targets */
579         usePipes = TRUE;                /* Catch child output in pipes */
580         debug = 0;                      /* No debug verbosity, please. */
581         jobsRunning = FALSE;
582
583         maxJobs = DEFMAXJOBS;
584         forceJobs = FALSE;              /* No -j flag */
585         compatMake = FALSE;             /* No compat mode */
586
587         /*
588          * Initialize the parsing, directory and variable modules to prepare
589          * for the reading of inclusion paths and variable settings on the
590          * command line
591          */
592         Dir_Init();             /* Initialize directory structures so -I flags
593                                  * can be processed correctly */
594         Parse_Init();           /* Need to initialize the paths of #include
595                                  * directories */
596         Var_Init();             /* As well as the lists of variables for
597                                  * parsing arguments */
598         str_init();
599
600         /*
601          * Initialize various variables.
602          *      MAKE also gets this name, for compatibility
603          *      .MAKEFLAGS gets set to the empty string just in case.
604          *      MFLAGS also gets initialized empty, for compatibility.
605          */
606         Var_Set("MAKE", argv[0], VAR_GLOBAL);
607         Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
608         Var_Set("MFLAGS", "", VAR_GLOBAL);
609         Var_Set("MACHINE", machine, VAR_GLOBAL);
610         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
611         Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
612 #ifdef MAKE_VERSION
613         Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
614 #endif
615
616         /*
617          * First snag any flags out of the MAKE environment variable.
618          * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
619          * in a different format).
620          */
621         Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
622
623         MainParseArgs(argc, argv);
624
625         /*
626          * Find where we are...
627          * All this code is so that we know where we are when we start up
628          * on a different machine with pmake.
629          */
630         curdir = cdpath;
631         if (getcwd(curdir, MAXPATHLEN) == NULL)
632                 err(2, NULL);
633
634         {
635         struct stat sa;
636
637         if (stat(curdir, &sa) == -1)
638             err(2, "%s", curdir);
639         }
640
641         /*
642          * The object directory location is determined using the
643          * following order of preference:
644          *
645          *      1. MAKEOBJDIRPREFIX`cwd`
646          *      2. MAKEOBJDIR
647          *      3. PATH_OBJDIR.${MACHINE}
648          *      4. PATH_OBJDIR
649          *      5. PATH_OBJDIRPREFIX`cwd`
650          *
651          * If one of the first two fails, use the current directory.
652          * If the remaining three all fail, use the current directory.
653          *
654          * Once things are initted,
655          * have to add the original directory to the search path,
656          * and modify the paths for the Makefiles apropriately.  The
657          * current directory is also placed as a variable for make scripts.
658          */
659         if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
660                 if (!(path = getenv("MAKEOBJDIR"))) {
661                         path = PATH_OBJDIR;
662                         pathp = PATH_OBJDIRPREFIX;
663                         snprintf(mdpath, MAXPATHLEN, "%s.%s",
664                                         path, machine);
665                         if (!(objdir = chdir_verify_path(mdpath, obpath)))
666                                 if (!(objdir=chdir_verify_path(path, obpath))) {
667                                         snprintf(mdpath, MAXPATHLEN,
668                                                         "%s%s", pathp, curdir);
669                                         if (!(objdir=chdir_verify_path(mdpath,
670                                                                        obpath)))
671                                                 objdir = curdir;
672                                 }
673                 }
674                 else if (!(objdir = chdir_verify_path(path, obpath)))
675                         objdir = curdir;
676         }
677         else {
678                 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
679                 if (!(objdir = chdir_verify_path(mdpath, obpath)))
680                         objdir = curdir;
681         }
682         Dir_InitDot();          /* Initialize the "." directory */
683         if (objdir != curdir)
684                 Path_AddDir(&dirSearchPath, curdir);
685         Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
686         Var_Set(".CURDIR", curdir, VAR_GLOBAL);
687         Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
688
689         if (getenv("MAKE_JOBS_FIFO") != NULL)
690                 forceJobs = TRUE;
691         /*
692          * Be compatible if user did not specify -j and did not explicitly
693          * turned compatibility on
694          */
695         if (!compatMake && !forceJobs)
696                 compatMake = TRUE;
697
698         /*
699          * Initialize target and suffix modules in preparation for
700          * parsing the makefile(s)
701          */
702         Targ_Init();
703         Suff_Init();
704
705         DEFAULT = NULL;
706         time(&now);
707
708         /*
709          * Set up the .TARGETS variable to contain the list of targets to be
710          * created. If none specified, make the variable empty -- the parser
711          * will fill the thing in with the default or .MAIN target.
712          */
713         if (!Lst_IsEmpty(&create)) {
714                 LstNode *ln;
715
716                 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
717                         char *name = Lst_Datum(ln);
718
719                         Var_Append(".TARGETS", name, VAR_GLOBAL);
720                 }
721         } else
722                 Var_Set(".TARGETS", "", VAR_GLOBAL);
723
724
725         /*
726          * If no user-supplied system path was given (through the -m option)
727          * add the directories from the DEFSYSPATH (more than one may be given
728          * as dir1:...:dirn) to the system include path.
729          */
730         if (TAILQ_EMPTY(&sysIncPath)) {
731                 for (start = syspath; *start != '\0'; start = cp) {
732                         for (cp = start; *cp != '\0' && *cp != ':'; cp++)
733                                 continue;
734                         if (*cp == '\0') {
735                                 Path_AddDir(&sysIncPath, start);
736                         } else {
737                                 *cp++ = '\0';
738                                 Path_AddDir(&sysIncPath, start);
739                         }
740                 }
741         }
742
743         /*
744          * Read in the built-in rules first, followed by the specified
745          * makefile, if it was (makefile != (char *) NULL), or the default
746          * Makefile and makefile, in that order, if it wasn't.
747          */
748         if (!noBuiltins) {
749                 /* Path of sys.mk */
750                 Lst sysMkPath = Lst_Initializer(sysMkPath);
751                 LstNode *ln;
752
753                 Path_Expand(PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
754                 if (Lst_IsEmpty(&sysMkPath))
755                         Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
756                 LST_FOREACH(ln, &sysMkPath) {
757                         if (!ReadMakefile(Lst_Datum(ln)))
758                                 break;
759                 }
760                 if (ln != NULL)
761                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
762                 Lst_Destroy(&sysMkPath, free);
763         }
764
765         if (!Lst_IsEmpty(&makefiles)) {
766                 LstNode *ln;
767
768                 LST_FOREACH(ln, &makefiles) {
769                         if (!ReadMakefile(Lst_Datum(ln)))
770                                 break;
771                 }
772                 if (ln != NULL)
773                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
774         } else if (!ReadMakefile("BSDmakefile"))
775             if (!ReadMakefile("makefile"))
776                 ReadMakefile("Makefile");
777
778         ReadMakefile(".depend");
779
780         /* Install all the flags into the MAKE envariable. */
781         if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
782                 setenv("MAKEFLAGS", p, 1);
783         free(p1);
784
785         /*
786          * For compatibility, look at the directories in the VPATH variable
787          * and add them to the search path, if the variable is defined. The
788          * variable's value is in the same format as the PATH envariable, i.e.
789          * <directory>:<directory>:<directory>...
790          */
791         if (Var_Exists("VPATH", VAR_CMD)) {
792                 /*
793                  * GCC stores string constants in read-only memory, but
794                  * Var_Subst will want to write this thing, so store it
795                  * in an array
796                  */
797                 static char VPATH[] = "${VPATH}";
798                 Buffer  *buf;
799                 char    *vpath;
800                 char    *ptr;
801                 char    savec;
802
803                 buf = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
804
805                 vpath = Buf_Data(buf);
806                 do {
807                         /* skip to end of directory */
808                         for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
809                                 ;
810
811                         /* Save terminator character so know when to stop */
812                         savec = *ptr;
813                         *ptr = '\0';
814
815                         /* Add directory to search path */
816                         Path_AddDir(&dirSearchPath, vpath);
817
818                         vpath = ptr + 1;
819                 } while (savec != '\0');
820
821                 Buf_Destroy(buf, TRUE);
822         }
823
824         /*
825          * Now that all search paths have been read for suffixes et al, it's
826          * time to add the default search path to their lists...
827          */
828         Suff_DoPaths();
829
830         /* print the initial graph, if the user requested it */
831         if (DEBUG(GRAPH1))
832                 Targ_PrintGraph(1);
833
834         /* print the values of any variables requested by the user */
835         if (Lst_IsEmpty(&variables)) {
836                 /*
837                  * Since the user has not requested that any variables
838                  * be printed, we can build targets.
839                  *
840                  * Have read the entire graph and need to make a list of targets
841                  * to create. If none was given on the command line, we consult
842                  * the parsing module to find the main target(s) to create.
843                  */
844                 Lst targs = Lst_Initializer(targs);
845
846                 if (Lst_IsEmpty(&create))
847                         Parse_MainName(&targs);
848                 else
849                         Targ_FindList(&targs, &create, TARG_CREATE);
850
851                 if (compatMake) {
852                         /*
853                          * Compat_Init will take care of creating
854                          * all the targets as well as initializing
855                          * the module.
856                          */
857                         Compat_Run(&targs);
858                         outOfDate = 0;
859                 } else {
860                         /*
861                          * Initialize job module before traversing
862                          * the graph, now that any .BEGIN and .END
863                          * targets have been read.  This is done
864                          * only if the -q flag wasn't given (to
865                          * prevent the .BEGIN from being executed
866                          * should it exist).
867                          */
868                         if (!queryFlag) {
869                                 Job_Init(maxJobs);
870                                 jobsRunning = TRUE;
871                         }
872
873                         /* Traverse the graph, checking on all the targets */
874                         outOfDate = Make_Run(&targs);
875                 }
876                 Lst_Destroy(&targs, NOFREE);
877
878         } else {
879                 /*
880                  * Print the values of any variables requested by
881                  * the user.
882                  */
883                 LstNode *n;
884
885                 LST_FOREACH(n, &variables) {
886                         const char      *name = Lst_Datum(n);
887                         if (expandVars) {
888                                 char            *v;
889                                 char            *value;
890
891                                 v = emalloc(strlen(name) + 1 + 3);
892                                 sprintf(v, "${%s}", name);
893
894                                 value = Buf_Peel(Var_Subst(NULL, v,
895                                     VAR_GLOBAL, FALSE));
896                                 printf("%s\n", value);
897
898                                 free(v);
899                                 free(value);
900                         } else {
901                                 char    *value;
902                                 char    *v;
903                                 value = Var_Value(name, VAR_GLOBAL, &v);
904                                 printf("%s\n", value != NULL ? value : "");
905                                 if (v != NULL)
906                                         free(v);
907                         }
908                 }
909         }
910
911         Lst_Destroy(&variables, free);
912         Lst_Destroy(&makefiles, free);
913         Lst_Destroy(&create, free);
914
915         /* print the graph now it's been processed if the user requested it */
916         if (DEBUG(GRAPH2))
917                 Targ_PrintGraph(2);
918
919         if (queryFlag && outOfDate)
920                 return (1);
921         else
922                 return (0);
923 }
924
925 /**
926  * ReadMakefile
927  *      Open and parse the given makefile.
928  *
929  * Results:
930  *      TRUE if ok. FALSE if couldn't open file.
931  *
932  * Side Effects:
933  *      lots
934  */
935 static Boolean
936 ReadMakefile(const char *p)
937 {
938         char *fname;                    /* makefile to read */
939         FILE *stream;
940         char *name, path[MAXPATHLEN];
941         char *MAKEFILE;
942         int setMAKEFILE;
943
944         /* XXX - remove this once constification is done */
945         fname = estrdup(p);
946
947         if (!strcmp(fname, "-")) {
948                 Parse_File("(stdin)", stdin);
949                 Var_Set("MAKEFILE", "", VAR_GLOBAL);
950         } else {
951                 setMAKEFILE = strcmp(fname, ".depend");
952
953                 /* if we've chdir'd, rebuild the path name */
954                 if (curdir != objdir && *fname != '/') {
955                         snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
956                         /*
957                          * XXX The realpath stuff breaks relative includes
958                          * XXX in some cases.   The problem likely is in
959                          * XXX parse.c where it does special things in
960                          * XXX ParseDoInclude if the file is relateive
961                          * XXX or absolute and not a system file.  There
962                          * XXX it assumes that if the current file that's
963                          * XXX being included is absolute, that any files
964                          * XXX that it includes shouldn't do the -I path
965                          * XXX stuff, which is inconsistant with historical
966                          * XXX behavior.  However, I can't pentrate the mists
967                          * XXX further, so I'm putting this workaround in
968                          * XXX here until such time as the underlying bug
969                          * XXX can be fixed.
970                          */
971 #if THIS_BREAKS_THINGS
972                         if (realpath(path, path) != NULL &&
973                             (stream = fopen(path, "r")) != NULL) {
974                                 MAKEFILE = fname;
975                                 fname = path;
976                                 goto found;
977                         }
978                 } else if (realpath(fname, path) != NULL) {
979                         MAKEFILE = fname;
980                         fname = path;
981                         if ((stream = fopen(fname, "r")) != NULL)
982                                 goto found;
983                 }
984 #else
985                         if ((stream = fopen(path, "r")) != NULL) {
986                                 MAKEFILE = fname;
987                                 fname = path;
988                                 goto found;
989                         }
990                 } else {
991                         MAKEFILE = fname;
992                         if ((stream = fopen(fname, "r")) != NULL)
993                                 goto found;
994                 }
995 #endif
996                 /* look in -I and system include directories. */
997                 name = Path_FindFile(fname, &parseIncPath);
998                 if (!name)
999                         name = Path_FindFile(fname, &sysIncPath);
1000                 if (!name || !(stream = fopen(name, "r")))
1001                         return (FALSE);
1002                 MAKEFILE = fname = name;
1003                 /*
1004                  * set the MAKEFILE variable desired by System V fans -- the
1005                  * placement of the setting here means it gets set to the last
1006                  * makefile specified, as it is set by SysV make.
1007                  */
1008 found:
1009                 if (setMAKEFILE)
1010                         Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1011                 Parse_File(fname, stream);
1012                 fclose(stream);
1013         }
1014         return (TRUE);
1015 }
1016
1017 /**
1018  * Cmd_Exec
1019  *      Execute the command in cmd, and return the output of that command
1020  *      in a string.
1021  *
1022  * Results:
1023  *      A string containing the output of the command, or the empty string
1024  *      If error is not NULL, it contains the reason for the command failure
1025  *
1026  * Side Effects:
1027  *      The string must be freed by the caller.
1028  */
1029 Buffer *
1030 Cmd_Exec(const char *cmd, const char **error)
1031 {
1032         int     fds[2]; /* Pipe streams */
1033         int     cpid;   /* Child PID */
1034         int     pid;    /* PID from wait() */
1035         int     status; /* command exit status */
1036         Buffer  *buf;   /* buffer to store the result */
1037         ssize_t rcnt;
1038
1039         *error = NULL;
1040         buf = Buf_Init(0);
1041
1042         if (shellPath == NULL)
1043                 Shell_Init();
1044         /*
1045          * Open a pipe for fetching its output
1046          */
1047         if (pipe(fds) == -1) {
1048                 *error = "Couldn't create pipe for \"%s\"";
1049                 return (buf);
1050         }
1051
1052         /*
1053          * Fork
1054          */
1055         switch (cpid = vfork()) {
1056           case 0:
1057                 /*
1058                  * Close input side of pipe
1059                  */
1060                 close(fds[0]);
1061
1062                 /*
1063                  * Duplicate the output stream to the shell's output, then
1064                  * shut the extra thing down. Note we don't fetch the error
1065                  * stream...why not? Why?
1066                  */
1067                 dup2(fds[1], 1);
1068                 close(fds[1]);
1069
1070                 {
1071                         char    *args[4];
1072
1073                         /* Set up arguments for shell */
1074                         args[0] = shellName;
1075                         args[1] = "-c";
1076                         args[2] = cmd;
1077                         args[3] = NULL;
1078
1079                         execv(shellPath, args);
1080                         _exit(1);
1081                         /*NOTREACHED*/
1082                 }
1083
1084           case -1:
1085                 *error = "Couldn't exec \"%s\"";
1086                 return (buf);
1087
1088           default:
1089                 /*
1090                  * No need for the writing half
1091                  */
1092                 close(fds[1]);
1093
1094                 do {
1095                         char    result[BUFSIZ];
1096
1097                         rcnt = read(fds[0], result, sizeof(result));
1098                         if (rcnt != -1)
1099                                 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1100                 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1101
1102                 if (rcnt == -1)
1103                         *error = "Error reading shell's output for \"%s\"";
1104
1105                 /*
1106                  * Close the input side of the pipe.
1107                  */
1108                 close(fds[0]);
1109
1110                 /*
1111                  * Wait for the process to exit.
1112                  */
1113                 while (((pid = wait(&status)) != cpid) && (pid >= 0))
1114                         continue;
1115
1116                 if (status)
1117                         *error = "\"%s\" returned non-zero status";
1118
1119                 Buf_StripNewlines(buf);
1120
1121                 break;
1122         }
1123         return (buf);
1124 }
1125
1126 /*
1127  * usage --
1128  *      exit with usage message
1129  */
1130 static void
1131 usage(void)
1132 {
1133         fprintf(stderr, "%s\n%s\n%s\n",
1134 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1135 "            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1136 "            [-m directory] [-V variable] [variable=value] [target ...]");
1137         exit(2);
1138 }