8d6e1a2920020f801f69fa3d984555df6ae17856
[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.72 2005/04/15 21:05:52 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 char            *chdir_verify_path(const char *, char *);
134 static int      ReadMakefile(const char *);
135 static void     usage(void);
136
137 static char     *curdir;        /* startup directory */
138 static char     *objdir;        /* where we chdir'ed to */
139
140 /**
141  * MFLAGS_append
142  *      Append a flag with an optional argument to MAKEFLAGS and MFLAGS
143  */
144 static void
145 MFLAGS_append(const char *flag, char *arg)
146 {
147         char *str;
148
149         Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
150         if (arg != NULL) {
151                 str = MAKEFLAGS_quote(arg);
152                 Var_Append(MAKEFLAGS, str, VAR_GLOBAL);
153                 free(str);
154         }
155
156         Var_Append("MFLAGS", flag, VAR_GLOBAL);
157         if (arg != NULL) {
158                 str = MAKEFLAGS_quote(arg);
159                 Var_Append("MFLAGS", str, VAR_GLOBAL);
160                 free(str);
161         }
162 }
163
164 /**
165  * MainParseArgs
166  *      Parse a given argument vector. Called from main() and from
167  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
168  *
169  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
170  *
171  * Side Effects:
172  *      Various global and local flags will be set depending on the flags
173  *      given
174  */
175 static void
176 MainParseArgs(int argc, char **argv)
177 {
178         int c;
179
180 rearg:
181         optind = 1;     /* since we're called more than once */
182         optreset = 1;
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         argv += optind;
346         argc -= optind;
347
348         oldVars = TRUE;
349
350         /*
351          * Parse the rest of the arguments.
352          *      o Check for variable assignments and perform them if so.
353          *      o Check for more flags and restart getopt if so.
354          *      o Anything else is taken to be a target and added
355          *        to the end of the "create" list.
356          */
357         for (; *argv != NULL; ++argv, --argc) {
358                 if (Parse_IsVar(*argv)) {
359                         char *ptr = MAKEFLAGS_quote(*argv);
360
361                         Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
362                         Parse_DoVar(*argv, VAR_CMD);
363                         free(ptr);
364
365                 } else if ((*argv)[0] == '-') {
366                         if ((*argv)[1] == '\0') {
367                                 /*
368                                  * (*argv) is a single dash, so we
369                                  * just ignore it.
370                                  */
371                         } else {
372                                 /*
373                                  * (*argv) is a -flag, so backup argv
374                                  *  and argc, since getopt() expects
375                                  * options to start in the 2nd position.
376                                  */
377                                 argc++;
378                                 argv--;
379                                 goto rearg;
380                         }
381
382                 } else if ((*argv)[0] == '\0') {
383                         Punt("illegal (null) argument.");
384
385                 } else {
386                         Lst_AtEnd(&create, estrdup(*argv));
387                 }
388         }
389 }
390
391 /**
392  * Main_ParseArgLine
393  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
394  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
395  *      Takes a line of arguments and breaks it into its
396  *      component words and passes those words and the number of them to the
397  *      MainParseArgs function.
398  *      The line should have all its leading whitespace removed.
399  *
400  * Side Effects:
401  *      Only those that come from the various arguments.
402  */
403 void
404 Main_ParseArgLine(char *line, int mflags)
405 {
406         char **argv;                    /* Manufactured argument vector */
407         int argc;                       /* Number of arguments in argv */
408
409         if (line == NULL)
410                 return;
411         for (; *line == ' '; ++line)
412                 continue;
413         if (!*line)
414                 return;
415
416         if (mflags)
417                 argv = MAKEFLAGS_break(line, &argc);
418         else
419                 argv = brk_string(line, &argc, TRUE);
420
421         MainParseArgs(argc, argv);
422 }
423
424 char *
425 chdir_verify_path(const char *path, char *obpath)
426 {
427         struct stat sb;
428
429         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
430                 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
431                         warn("warning: %s", path);
432                         return (NULL);
433                 }
434                 return (obpath);
435         }
436
437         return (NULL);
438 }
439
440 static void
441 catch_child(int sig __unused)
442 {
443 }
444
445 /*
446  * In lieu of a good way to prevent every possible looping in
447  * make(1), stop there from being more than MKLVL_MAXVAL processes forked
448  * by make(1), to prevent a forkbomb from happening, in a dumb and
449  * mechanical way.
450  */
451 static void
452 check_make_level(void)
453 {
454 #ifdef WANT_ENV_MKLVL
455         char    *value = getenv(MKLVL_ENVVAR);
456         int     level = (value == NULL) ? 0 : atoi(value);
457
458         if (level < 0) {
459                 errc(2, EAGAIN, "Invalid value for recursion level (%d).",
460                     level);
461         } else if (level > MKLVL_MAXVAL) {
462                 errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
463                     MKLVL_MAXVAL);
464         } else {
465                 char new_value[32];
466                 sprintf(new_value, "%d", level + 1);
467                 setenv(MKLVL_ENVVAR, new_value, 1);
468         }
469 #endif /* WANT_ENV_MKLVL */
470 }
471
472 /**
473  * main
474  *      The main function, for obvious reasons. Initializes variables
475  *      and a few modules, then parses the arguments give it in the
476  *      environment and on the command line. Reads the system makefile
477  *      followed by either Makefile, makefile or the file given by the
478  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
479  *      flags it has received by then uses either the Make or the Compat
480  *      module to create the initial list of targets.
481  *
482  * Results:
483  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
484  *      0.
485  *
486  * Side Effects:
487  *      The program exits when done. Targets are created. etc. etc. etc.
488  */
489 int
490 main(int argc, char **argv)
491 {
492         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
493         char *p, *p1;
494         const char *pathp;
495         const char *path;
496         char mdpath[MAXPATHLEN];
497         char obpath[MAXPATHLEN];
498         char cdpath[MAXPATHLEN];
499         const char *machine = getenv("MACHINE");
500         const char *machine_arch = getenv("MACHINE_ARCH");
501         const char *machine_cpu = getenv("MACHINE_CPU");
502         char *cp = NULL, *start;
503
504         /* avoid faults on read-only strings */
505         static char syspath[] = PATH_DEFSYSPATH;
506
507         {
508         /*
509          * Catch SIGCHLD so that we get kicked out of select() when we
510          * need to look at a child.  This is only known to matter for the
511          * -j case (perhaps without -P).
512          *
513          * XXX this is intentionally misplaced.
514          */
515         struct sigaction sa;
516
517         sigemptyset(&sa.sa_mask);
518         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
519         sa.sa_handler = catch_child;
520         sigaction(SIGCHLD, &sa, NULL);
521         }
522
523         check_make_level();
524
525 #if DEFSHELL == 2
526         /*
527          * Turn off ENV to make ksh happier.
528          */
529         unsetenv("ENV");
530 #endif
531
532 #ifdef RLIMIT_NOFILE
533         /*
534          * get rid of resource limit on file descriptors
535          */
536         {
537                 struct rlimit rl;
538                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
539                     rl.rlim_cur != rl.rlim_max) {
540                         rl.rlim_cur = rl.rlim_max;
541                         setrlimit(RLIMIT_NOFILE, &rl);
542                 }
543         }
544 #endif
545         /*
546          * Get the name of this type of MACHINE from utsname
547          * so we can share an executable for similar machines.
548          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
549          *
550          * Note that while MACHINE is decided at run-time,
551          * MACHINE_ARCH is always known at compile time.
552          */
553         if (!machine) {
554 #ifndef MACHINE
555                 static struct utsname utsname;
556
557                 if (uname(&utsname) == -1)
558                         err(2, "uname");
559                 machine = utsname.machine;
560 #else
561                 machine = MACHINE;
562 #endif
563         }
564
565         if (!machine_arch) {
566 #ifndef MACHINE_ARCH
567                 machine_arch = "unknown";
568 #else
569                 machine_arch = MACHINE_ARCH;
570 #endif
571         }
572
573         /*
574          * Set machine_cpu to the minumum supported CPU revision based
575          * on the target architecture, if not already set.
576          */
577         if (!machine_cpu) {
578                 if (!strcmp(machine_arch, "i386"))
579                         machine_cpu = "i386";
580                 else if (!strcmp(machine_arch, "alpha"))
581                         machine_cpu = "ev4";
582                 else
583                         machine_cpu = "unknown";
584         }
585
586         expandVars = TRUE;
587         beSilent = FALSE;               /* Print commands as executed */
588         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
589         noExecute = FALSE;              /* Execute all commands */
590         keepgoing = FALSE;              /* Stop on error */
591         allPrecious = FALSE;            /* Remove targets when interrupted */
592         queryFlag = FALSE;              /* This is not just a check-run */
593         noBuiltins = FALSE;             /* Read the built-in rules */
594         touchFlag = FALSE;              /* Actually update targets */
595         usePipes = TRUE;                /* Catch child output in pipes */
596         debug = 0;                      /* No debug verbosity, please. */
597         jobsRunning = FALSE;
598
599         maxJobs = DEFMAXJOBS;
600         forceJobs = FALSE;              /* No -j flag */
601         compatMake = FALSE;             /* No compat mode */
602
603         /*
604          * Initialize the parsing, directory and variable modules to prepare
605          * for the reading of inclusion paths and variable settings on the
606          * command line
607          */
608         Dir_Init();             /* Initialize directory structures so -I flags
609                                  * can be processed correctly */
610         Var_Init();             /* As well as the lists of variables for
611                                  * parsing arguments */
612         str_init();
613
614         /*
615          * Initialize various variables.
616          *      MAKE also gets this name, for compatibility
617          *      .MAKEFLAGS gets set to the empty string just in case.
618          *      MFLAGS also gets initialized empty, for compatibility.
619          */
620         Var_Set("MAKE", argv[0], VAR_GLOBAL);
621         Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
622         Var_Set("MFLAGS", "", VAR_GLOBAL);
623         Var_Set("MACHINE", machine, VAR_GLOBAL);
624         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
625         Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
626 #ifdef MAKE_VERSION
627         Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
628 #endif
629
630         /*
631          * First snag things out of the MAKEFLAGS environment
632          * variable.  Then parse the command line arguments.
633          */
634         Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
635
636         MainParseArgs(argc, argv);
637
638         /*
639          * Find where we are...
640          */
641         curdir = cdpath;
642         if (getcwd(curdir, MAXPATHLEN) == NULL)
643                 err(2, NULL);
644
645         {
646         struct stat sa;
647
648         if (stat(curdir, &sa) == -1)
649             err(2, "%s", curdir);
650         }
651
652         /*
653          * The object directory location is determined using the
654          * following order of preference:
655          *
656          *      1. MAKEOBJDIRPREFIX`cwd`
657          *      2. MAKEOBJDIR
658          *      3. PATH_OBJDIR.${MACHINE}
659          *      4. PATH_OBJDIR
660          *      5. PATH_OBJDIRPREFIX`cwd`
661          *
662          * If one of the first two fails, use the current directory.
663          * If the remaining three all fail, use the current directory.
664          *
665          * Once things are initted,
666          * have to add the original directory to the search path,
667          * and modify the paths for the Makefiles apropriately.  The
668          * current directory is also placed as a variable for make scripts.
669          */
670         if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
671                 if (!(path = getenv("MAKEOBJDIR"))) {
672                         path = PATH_OBJDIR;
673                         pathp = PATH_OBJDIRPREFIX;
674                         snprintf(mdpath, MAXPATHLEN, "%s.%s",
675                                         path, machine);
676                         if (!(objdir = chdir_verify_path(mdpath, obpath)))
677                                 if (!(objdir=chdir_verify_path(path, obpath))) {
678                                         snprintf(mdpath, MAXPATHLEN,
679                                                         "%s%s", pathp, curdir);
680                                         if (!(objdir=chdir_verify_path(mdpath,
681                                                                        obpath)))
682                                                 objdir = curdir;
683                                 }
684                 }
685                 else if (!(objdir = chdir_verify_path(path, obpath)))
686                         objdir = curdir;
687         }
688         else {
689                 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
690                 if (!(objdir = chdir_verify_path(mdpath, obpath)))
691                         objdir = curdir;
692         }
693         Dir_InitDot();          /* Initialize the "." directory */
694         if (objdir != curdir)
695                 Path_AddDir(&dirSearchPath, curdir);
696         Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
697         Var_Set(".ST_EXPORT", "YES", VAR_GLOBAL);
698         Var_Set(".CURDIR", curdir, VAR_GLOBAL);
699         Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
700
701         if (getenv("MAKE_JOBS_FIFO") != NULL)
702                 forceJobs = TRUE;
703         /*
704          * Be compatible if user did not specify -j and did not explicitly
705          * turned compatibility on
706          */
707         if (!compatMake && !forceJobs)
708                 compatMake = TRUE;
709
710         /*
711          * Initialize target and suffix modules in preparation for
712          * parsing the makefile(s)
713          */
714         Targ_Init();
715         Suff_Init();
716
717         DEFAULT = NULL;
718         time(&now);
719
720         /*
721          * Set up the .TARGETS variable to contain the list of targets to be
722          * created. If none specified, make the variable empty -- the parser
723          * will fill the thing in with the default or .MAIN target.
724          */
725         if (!Lst_IsEmpty(&create)) {
726                 LstNode *ln;
727
728                 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
729                         char *name = Lst_Datum(ln);
730
731                         Var_Append(".TARGETS", name, VAR_GLOBAL);
732                 }
733         } else
734                 Var_Set(".TARGETS", "", VAR_GLOBAL);
735
736
737         /*
738          * If no user-supplied system path was given (through the -m option)
739          * add the directories from the DEFSYSPATH (more than one may be given
740          * as dir1:...:dirn) to the system include path.
741          */
742         if (TAILQ_EMPTY(&sysIncPath)) {
743                 for (start = syspath; *start != '\0'; start = cp) {
744                         for (cp = start; *cp != '\0' && *cp != ':'; cp++)
745                                 continue;
746                         if (*cp == '\0') {
747                                 Path_AddDir(&sysIncPath, start);
748                         } else {
749                                 *cp++ = '\0';
750                                 Path_AddDir(&sysIncPath, start);
751                         }
752                 }
753         }
754
755         /*
756          * Read in the built-in rules first, followed by the specified
757          * makefile, if it was (makefile != (char *) NULL), or the default
758          * Makefile and makefile, in that order, if it wasn't.
759          */
760         if (!noBuiltins) {
761                 /* Path of sys.mk */
762                 Lst sysMkPath = Lst_Initializer(sysMkPath);
763                 LstNode *ln;
764
765                 Path_Expand(PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
766                 if (Lst_IsEmpty(&sysMkPath))
767                         Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
768                 LST_FOREACH(ln, &sysMkPath) {
769                         if (!ReadMakefile(Lst_Datum(ln)))
770                                 break;
771                 }
772                 if (ln != NULL)
773                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
774                 Lst_Destroy(&sysMkPath, free);
775         }
776
777         if (!Lst_IsEmpty(&makefiles)) {
778                 LstNode *ln;
779
780                 LST_FOREACH(ln, &makefiles) {
781                         if (!ReadMakefile(Lst_Datum(ln)))
782                                 break;
783                 }
784                 if (ln != NULL)
785                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
786         } else if (!ReadMakefile("BSDmakefile"))
787             if (!ReadMakefile("makefile"))
788                 ReadMakefile("Makefile");
789
790         ReadMakefile(".depend");
791
792         /* Install all the flags into the MAKE envariable. */
793         if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
794                 setenv("MAKEFLAGS", p, 1);
795         free(p1);
796
797         /*
798          * For compatibility, look at the directories in the VPATH variable
799          * and add them to the search path, if the variable is defined. The
800          * variable's value is in the same format as the PATH envariable, i.e.
801          * <directory>:<directory>:<directory>...
802          */
803         if (Var_Exists("VPATH", VAR_CMD)) {
804                 /*
805                  * GCC stores string constants in read-only memory, but
806                  * Var_Subst will want to write this thing, so store it
807                  * in an array
808                  */
809                 static char VPATH[] = "${VPATH}";
810                 Buffer  *buf;
811                 char    *vpath;
812                 char    *ptr;
813                 char    savec;
814
815                 buf = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
816
817                 vpath = Buf_Data(buf);
818                 do {
819                         /* skip to end of directory */
820                         for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
821                                 ;
822
823                         /* Save terminator character so know when to stop */
824                         savec = *ptr;
825                         *ptr = '\0';
826
827                         /* Add directory to search path */
828                         Path_AddDir(&dirSearchPath, vpath);
829
830                         vpath = ptr + 1;
831                 } while (savec != '\0');
832
833                 Buf_Destroy(buf, TRUE);
834         }
835
836         /*
837          * Now that all search paths have been read for suffixes et al, it's
838          * time to add the default search path to their lists...
839          */
840         Suff_DoPaths();
841
842         /* print the initial graph, if the user requested it */
843         if (DEBUG(GRAPH1))
844                 Targ_PrintGraph(1);
845
846         /* print the values of any variables requested by the user */
847         if (Lst_IsEmpty(&variables)) {
848                 /*
849                  * Since the user has not requested that any variables
850                  * be printed, we can build targets.
851                  *
852                  * Have read the entire graph and need to make a list of targets
853                  * to create. If none was given on the command line, we consult
854                  * the parsing module to find the main target(s) to create.
855                  */
856                 Lst targs = Lst_Initializer(targs);
857
858                 if (Lst_IsEmpty(&create))
859                         Parse_MainName(&targs);
860                 else
861                         Targ_FindList(&targs, &create, TARG_CREATE);
862
863                 if (compatMake) {
864                         /*
865                          * Compat_Init will take care of creating
866                          * all the targets as well as initializing
867                          * the module.
868                          */
869                         Compat_Run(&targs);
870                         outOfDate = 0;
871                 } else {
872                         /*
873                          * Initialize job module before traversing
874                          * the graph, now that any .BEGIN and .END
875                          * targets have been read.  This is done
876                          * only if the -q flag wasn't given (to
877                          * prevent the .BEGIN from being executed
878                          * should it exist).
879                          */
880                         if (!queryFlag) {
881                                 Job_Init(maxJobs);
882                                 jobsRunning = TRUE;
883                         }
884
885                         /* Traverse the graph, checking on all the targets */
886                         outOfDate = Make_Run(&targs);
887                 }
888                 Lst_Destroy(&targs, NOFREE);
889
890         } else {
891                 /*
892                  * Print the values of any variables requested by
893                  * the user.
894                  */
895                 LstNode *n;
896
897                 LST_FOREACH(n, &variables) {
898                         const char      *name = Lst_Datum(n);
899                         if (expandVars) {
900                                 char            *v;
901                                 char            *value;
902
903                                 v = emalloc(strlen(name) + 1 + 3);
904                                 sprintf(v, "${%s}", name);
905
906                                 value = Buf_Peel(Var_Subst(NULL, v,
907                                     VAR_GLOBAL, FALSE));
908                                 printf("%s\n", value);
909
910                                 free(v);
911                                 free(value);
912                         } else {
913                                 char    *value;
914                                 char    *v;
915                                 value = Var_Value(name, VAR_GLOBAL, &v);
916                                 printf("%s\n", value != NULL ? value : "");
917                                 if (v != NULL)
918                                         free(v);
919                         }
920                 }
921         }
922
923         Lst_Destroy(&variables, free);
924         Lst_Destroy(&makefiles, free);
925         Lst_Destroy(&create, free);
926
927         /* print the graph now it's been processed if the user requested it */
928         if (DEBUG(GRAPH2))
929                 Targ_PrintGraph(2);
930
931         if (queryFlag && outOfDate)
932                 return (1);
933         else
934                 return (0);
935 }
936
937 /**
938  * ReadMakefile
939  *      Open and parse the given makefile.
940  *
941  * Results:
942  *      TRUE if ok. FALSE if couldn't open file.
943  *
944  * Side Effects:
945  *      lots
946  */
947 static Boolean
948 ReadMakefile(const char *p)
949 {
950         char *fname;                    /* makefile to read */
951         FILE *stream;
952         char *name, path[MAXPATHLEN];
953         char *MAKEFILE;
954         int setMAKEFILE;
955
956         /* XXX - remove this once constification is done */
957         fname = estrdup(p);
958
959         if (!strcmp(fname, "-")) {
960                 Parse_File("(stdin)", stdin);
961                 Var_Set("MAKEFILE", "", VAR_GLOBAL);
962         } else {
963                 setMAKEFILE = strcmp(fname, ".depend");
964
965                 /* if we've chdir'd, rebuild the path name */
966                 if (curdir != objdir && *fname != '/') {
967                         snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
968                         /*
969                          * XXX The realpath stuff breaks relative includes
970                          * XXX in some cases.   The problem likely is in
971                          * XXX parse.c where it does special things in
972                          * XXX ParseDoInclude if the file is relateive
973                          * XXX or absolute and not a system file.  There
974                          * XXX it assumes that if the current file that's
975                          * XXX being included is absolute, that any files
976                          * XXX that it includes shouldn't do the -I path
977                          * XXX stuff, which is inconsistant with historical
978                          * XXX behavior.  However, I can't pentrate the mists
979                          * XXX further, so I'm putting this workaround in
980                          * XXX here until such time as the underlying bug
981                          * XXX can be fixed.
982                          */
983 #if THIS_BREAKS_THINGS
984                         if (realpath(path, path) != NULL &&
985                             (stream = fopen(path, "r")) != NULL) {
986                                 MAKEFILE = fname;
987                                 fname = path;
988                                 goto found;
989                         }
990                 } else if (realpath(fname, path) != NULL) {
991                         MAKEFILE = fname;
992                         fname = path;
993                         if ((stream = fopen(fname, "r")) != NULL)
994                                 goto found;
995                 }
996 #else
997                         if ((stream = fopen(path, "r")) != NULL) {
998                                 MAKEFILE = fname;
999                                 fname = path;
1000                                 goto found;
1001                         }
1002                 } else {
1003                         MAKEFILE = fname;
1004                         if ((stream = fopen(fname, "r")) != NULL)
1005                                 goto found;
1006                 }
1007 #endif
1008                 /* look in -I and system include directories. */
1009                 name = Path_FindFile(fname, &parseIncPath);
1010                 if (!name)
1011                         name = Path_FindFile(fname, &sysIncPath);
1012                 if (!name || !(stream = fopen(name, "r")))
1013                         return (FALSE);
1014                 MAKEFILE = fname = name;
1015                 /*
1016                  * set the MAKEFILE variable desired by System V fans -- the
1017                  * placement of the setting here means it gets set to the last
1018                  * makefile specified, as it is set by SysV make.
1019                  */
1020 found:
1021                 if (setMAKEFILE)
1022                         Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1023                 Parse_File(fname, stream);
1024                 fclose(stream);
1025         }
1026         return (TRUE);
1027 }
1028
1029 /**
1030  * Cmd_Exec
1031  *      Execute the command in cmd, and return the output of that command
1032  *      in a string.
1033  *
1034  * Results:
1035  *      A string containing the output of the command, or the empty string
1036  *      If error is not NULL, it contains the reason for the command failure
1037  *
1038  * Side Effects:
1039  *      The string must be freed by the caller.
1040  */
1041 Buffer *
1042 Cmd_Exec(const char *cmd, const char **error)
1043 {
1044         int     fds[2]; /* Pipe streams */
1045         int     cpid;   /* Child PID */
1046         int     pid;    /* PID from wait() */
1047         int     status; /* command exit status */
1048         Buffer  *buf;   /* buffer to store the result */
1049         ssize_t rcnt;
1050
1051         *error = NULL;
1052         buf = Buf_Init(0);
1053
1054         if (shellPath == NULL)
1055                 Shell_Init();
1056         /*
1057          * Open a pipe for fetching its output
1058          */
1059         if (pipe(fds) == -1) {
1060                 *error = "Couldn't create pipe for \"%s\"";
1061                 return (buf);
1062         }
1063
1064         /*
1065          * Fork
1066          */
1067         switch (cpid = vfork()) {
1068           case 0:
1069                 /*
1070                  * Close input side of pipe
1071                  */
1072                 close(fds[0]);
1073
1074                 /*
1075                  * Duplicate the output stream to the shell's output, then
1076                  * shut the extra thing down. Note we don't fetch the error
1077                  * stream...why not? Why?
1078                  */
1079                 dup2(fds[1], 1);
1080                 close(fds[1]);
1081
1082                 {
1083                         char    *args[4];
1084
1085                         /* Set up arguments for shell */
1086                         args[0] = shellName;
1087                         args[1] = "-c";
1088                         args[2] = cmd;
1089                         args[3] = NULL;
1090
1091                         execv(shellPath, args);
1092                         _exit(1);
1093                         /*NOTREACHED*/
1094                 }
1095
1096           case -1:
1097                 *error = "Couldn't exec \"%s\"";
1098                 return (buf);
1099
1100           default:
1101                 /*
1102                  * No need for the writing half
1103                  */
1104                 close(fds[1]);
1105
1106                 do {
1107                         char    result[BUFSIZ];
1108
1109                         rcnt = read(fds[0], result, sizeof(result));
1110                         if (rcnt != -1)
1111                                 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1112                 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1113
1114                 if (rcnt == -1)
1115                         *error = "Error reading shell's output for \"%s\"";
1116
1117                 /*
1118                  * Close the input side of the pipe.
1119                  */
1120                 close(fds[0]);
1121
1122                 /*
1123                  * Wait for the process to exit.
1124                  */
1125                 while (((pid = wait(&status)) != cpid) && (pid >= 0))
1126                         continue;
1127
1128                 if (status)
1129                         *error = "\"%s\" returned non-zero status";
1130
1131                 Buf_StripNewlines(buf);
1132
1133                 break;
1134         }
1135         return (buf);
1136 }
1137
1138 /*
1139  * usage --
1140  *      exit with usage message
1141  */
1142 static void
1143 usage(void)
1144 {
1145         fprintf(stderr, "%s\n%s\n%s\n",
1146 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1147 "            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1148 "            [-m directory] [-V variable] [variable=value] [target ...]");
1149         exit(2);
1150 }