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