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