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