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