271b6bac8ae756742bbe33c4c2d2be409394693d
[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.51 2005/01/31 21:11:26 okumoto Exp $
42  */
43
44 /*-
45  * main.c --
46  *      The main file for this entire program. Exit routines etc
47  *      reside here.
48  *
49  * Utility functions defined in this file:
50  *      Main_ParseArgLine       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/types.h>
61 #include <sys/stat.h>
62 #include <sys/wait.h>
63 #include <err.h>
64 #include <errno.h>
65 #include <signal.h>
66 #include <stdlib.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70 #include <sys/sysctl.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 "GNode.h"
79 #include "job.h"
80 #include "lst.h"
81 #include "make.h"
82 #include "nonints.h"
83 #include "parse.h"
84 #include "pathnames.h"
85 #include "str.h"
86 #include "suff.h"
87 #include "targ.h"
88 #include "util.h"
89 #include "var.h"
90
91 #define WANT_ENV_MKLVL  1
92 #define MKLVL_MAXVAL    500
93 #define MKLVL_ENVVAR    "__MKLVL__"
94
95 #define MAKEFLAGS       ".MAKEFLAGS"
96
97 /* Targets to be made */
98 Lst create = Lst_Initializer(create);
99
100 time_t                  now;            /* Time at start of make */
101 GNode                   *DEFAULT;       /* .DEFAULT node */
102 Boolean                 allPrecious;    /* .PRECIOUS given on line by itself */
103
104 static Boolean          noBuiltins;     /* -r flag */
105
106 /* ordered list of makefiles to read */
107 static Lst makefiles = Lst_Initializer(makefiles);
108
109 static Boolean          expandVars;     /* fully expand printed variables */
110
111 /* list of variables to print */
112 static Lst variables = Lst_Initializer(variables);
113
114 int                     maxJobs;        /* -j argument */
115 static Boolean          forceJobs;      /* -j argument given */
116 Boolean                 compatMake;     /* -B argument */
117 Boolean                 debug;          /* -d flag */
118 Boolean                 noExecute;      /* -n flag */
119 Boolean                 keepgoing;      /* -k flag */
120 Boolean                 queryFlag;      /* -q flag */
121 Boolean                 touchFlag;      /* -t flag */
122 Boolean                 usePipes;       /* !-P flag */
123 Boolean                 ignoreErrors;   /* -i flag */
124 Boolean                 beSilent;       /* -s flag */
125 Boolean                 beVerbose;      /* -v flag */
126 Boolean                 oldVars;        /* variable substitution style */
127 Boolean                 checkEnvFirst;  /* -e flag */
128
129 /* (-E) vars to override from env */
130 Lst envFirstVars = Lst_Initializer(envFirstVars);
131
132 Boolean                 jobsRunning;    /* TRUE if the jobs might be running */
133
134 static void             MainParseArgs(int, char **);
135 char                    *chdir_verify_path(const char *, char *);
136 static int              ReadMakefile(const void *, const void *);
137 static void             usage(void);
138
139 static char *curdir;                    /* startup directory */
140 static char *objdir;                    /* where we chdir'ed to */
141
142 /*
143  * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
144  */
145 static void
146 MFLAGS_append(const char *flag, char *arg)
147 {
148         Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
149         if (arg != NULL) {
150                 char *str = MAKEFLAGS_quote(arg);
151                 Var_Append(MAKEFLAGS, str, VAR_GLOBAL);
152                 free(str);
153         }
154
155         Var_Append("MFLAGS", flag, VAR_GLOBAL);
156         if (arg != NULL) {
157                 char *str = MAKEFLAGS_quote(arg);
158                 Var_Append("MFLAGS", str, VAR_GLOBAL);
159                 free(str);
160         }
161 }
162
163 /*-
164  * MainParseArgs --
165  *      Parse a given argument vector. Called from main() and from
166  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
167  *
168  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
169  *
170  * Results:
171  *      None
172  *
173  * Side Effects:
174  *      Various global and local flags will be set depending on the flags
175  *      given
176  */
177 static void
178 MainParseArgs(int argc, char **argv)
179 {
180         int c;
181
182         optind = 1;     /* since we're called more than once */
183 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
184 rearg:  while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
185                 switch(c) {
186                 case 'C':
187                         if (chdir(optarg) == -1)
188                                 err(1, "chdir %s", optarg);
189                         break;
190                 case 'D':
191                         Var_Set(optarg, "1", VAR_GLOBAL);
192                         MFLAGS_append("-D", optarg);
193                         break;
194                 case 'I':
195                         Parse_AddIncludeDir(optarg);
196                         MFLAGS_append("-I", optarg);
197                         break;
198                 case 'V':
199                         Lst_AtEnd(&variables, estrdup(optarg));
200                         MFLAGS_append("-V", optarg);
201                         break;
202                 case 'X':
203                         expandVars = FALSE;
204                         break;
205                 case 'B':
206                         compatMake = TRUE;
207                         MFLAGS_append("-B", NULL);
208                         unsetenv("MAKE_JOBS_FIFO");
209                         break;
210                 case 'P':
211                         usePipes = FALSE;
212                         MFLAGS_append("-P", NULL);
213                         break;
214                 case 'S':
215                         keepgoing = FALSE;
216                         MFLAGS_append("-S", NULL);
217                         break;
218                 case 'd': {
219                         char *modules = optarg;
220
221                         for (; *modules; ++modules)
222                                 switch (*modules) {
223                                 case 'A':
224                                         debug = ~0;
225                                         break;
226                                 case 'a':
227                                         debug |= DEBUG_ARCH;
228                                         break;
229                                 case 'c':
230                                         debug |= DEBUG_COND;
231                                         break;
232                                 case 'd':
233                                         debug |= DEBUG_DIR;
234                                         break;
235                                 case 'f':
236                                         debug |= DEBUG_FOR;
237                                         break;
238                                 case 'g':
239                                         if (modules[1] == '1') {
240                                                 debug |= DEBUG_GRAPH1;
241                                                 ++modules;
242                                         }
243                                         else if (modules[1] == '2') {
244                                                 debug |= DEBUG_GRAPH2;
245                                                 ++modules;
246                                         }
247                                         break;
248                                 case 'j':
249                                         debug |= DEBUG_JOB;
250                                         break;
251                                 case 'l':
252                                         debug |= DEBUG_LOUD;
253                                         break;
254                                 case 'm':
255                                         debug |= DEBUG_MAKE;
256                                         break;
257                                 case 's':
258                                         debug |= DEBUG_SUFF;
259                                         break;
260                                 case 't':
261                                         debug |= DEBUG_TARG;
262                                         break;
263                                 case 'v':
264                                         debug |= DEBUG_VAR;
265                                         break;
266                                 default:
267                                         warnx("illegal argument to d option -- %c", *modules);
268                                         usage();
269                                 }
270                         MFLAGS_append("-d", optarg);
271                         break;
272                 }
273                 case 'E':
274                         Lst_AtEnd(&envFirstVars, estrdup(optarg));
275                         MFLAGS_append("-E", optarg);
276                         break;
277                 case 'e':
278                         checkEnvFirst = TRUE;
279                         MFLAGS_append("-e", NULL);
280                         break;
281                 case 'f':
282                         Lst_AtEnd(&makefiles, estrdup(optarg));
283                         break;
284                 case 'i':
285                         ignoreErrors = TRUE;
286                         MFLAGS_append("-i", NULL);
287                         break;
288                 case 'j': {
289                         char *endptr;
290
291                         forceJobs = TRUE;
292                         maxJobs = strtol(optarg, &endptr, 10);
293                         if (maxJobs <= 0 || *endptr != '\0') {
294                                 warnx("illegal number, -j argument -- %s",
295                                     optarg);
296                                 usage();
297                         }
298                         MFLAGS_append("-j", optarg);
299                         break;
300                 }
301                 case 'k':
302                         keepgoing = TRUE;
303                         MFLAGS_append("-k", NULL);
304                         break;
305                 case 'm':
306                         Dir_AddDir(&sysIncPath, optarg);
307                         MFLAGS_append("-m", optarg);
308                         break;
309                 case 'n':
310                         noExecute = TRUE;
311                         MFLAGS_append("-n", NULL);
312                         break;
313                 case 'q':
314                         queryFlag = TRUE;
315                         /* Kind of nonsensical, wot? */
316                         MFLAGS_append("-q", NULL);
317                         break;
318                 case 'r':
319                         noBuiltins = TRUE;
320                         MFLAGS_append("-r", NULL);
321                         break;
322                 case 's':
323                         beSilent = TRUE;
324                         MFLAGS_append("-s", NULL);
325                         break;
326                 case 't':
327                         touchFlag = TRUE;
328                         MFLAGS_append("-t", NULL);
329                         break;
330                 case 'v':
331                         beVerbose = TRUE;
332                         MFLAGS_append("-v", NULL);
333                         break;
334                 default:
335                 case '?':
336                         usage();
337                 }
338         }
339
340         oldVars = TRUE;
341
342         /*
343          * See if the rest of the arguments are variable assignments and
344          * perform them if so. Else take them to be targets and stuff them
345          * on the end of the "create" list.
346          */
347         for (argv += optind, argc -= optind; *argv; ++argv, --argc)
348                 if (Parse_IsVar(*argv)) {
349                         char *ptr = MAKEFLAGS_quote(*argv);
350
351                         Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
352                         free(ptr);
353
354                         Parse_DoVar(*argv, VAR_CMD);
355                 } else {
356                         if (!**argv)
357                                 Punt("illegal (null) argument.");
358                         if (**argv == '-') {
359                                 if ((*argv)[1])
360                                         optind = 0;     /* -flag... */
361                                 else
362                                         optind = 1;     /* - */
363                                 goto rearg;
364                         }
365                         Lst_AtEnd(&create, estrdup(*argv));
366                 }
367 }
368
369 /*-
370  * Main_ParseArgLine --
371  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
372  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
373  *      Takes a line of arguments and breaks it into its
374  *      component words and passes those words and the number of them to the
375  *      MainParseArgs function.
376  *      The line should have all its leading whitespace removed.
377  *
378  * Results:
379  *      None
380  *
381  * Side Effects:
382  *      Only those that come from the various arguments.
383  */
384 void
385 Main_ParseArgLine(char *line, int mflags)
386 {
387         char **argv;                    /* Manufactured argument vector */
388         int argc;                       /* Number of arguments in argv */
389
390         if (line == NULL)
391                 return;
392         for (; *line == ' '; ++line)
393                 continue;
394         if (!*line)
395                 return;
396
397         if (mflags)
398                 argv = MAKEFLAGS_break(line, &argc);
399         else
400                 argv = brk_string(line, &argc, TRUE);
401         MainParseArgs(argc, argv);
402 }
403
404 char *
405 chdir_verify_path(const char *path, char *obpath)
406 {
407         struct stat sb;
408
409         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
410                 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
411                         warn("warning: %s", path);
412                         return (0);
413                 }
414                 return (obpath);
415         }
416
417         return (NULL);
418 }
419
420 static void
421 catch_child(int sig __unused)
422 {
423 }
424
425 /*
426  * In lieu of a good way to prevent every possible looping in
427  * make(1), stop there from being more than MKLVL_MAXVAL processes forked
428  * by make(1), to prevent a forkbomb from happening, in a dumb and
429  * mechanical way.
430  */
431 static void
432 check_make_level(void)
433 {
434 #ifdef WANT_ENV_MKLVL
435         char    *value = getenv(MKLVL_ENVVAR);
436         int     level = (value == NULL) ? 0 : atoi(value);
437
438         if (level < 0) {
439                 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
440         } else if (level > MKLVL_MAXVAL) {
441                 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
442         } else {
443                 char new_value[32];
444                 sprintf(new_value, "%d", level + 1);
445                 setenv(MKLVL_ENVVAR, new_value, 1);
446         }
447 #endif /* WANT_ENV_MKLVL */
448 }
449
450 /*-
451  * main --
452  *      The main function, for obvious reasons. Initializes variables
453  *      and a few modules, then parses the arguments give it in the
454  *      environment and on the command line. Reads the system makefile
455  *      followed by either Makefile, makefile or the file given by the
456  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
457  *      flags it has received by then uses either the Make or the Compat
458  *      module to create the initial list of targets.
459  *
460  * Results:
461  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
462  *      0.
463  *
464  * Side Effects:
465  *      The program exits when done. Targets are created. etc. etc. etc.
466  */
467 int
468 main(int argc, char **argv)
469 {
470         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
471         char *p, *p1;
472         const char *pathp;
473         const char *path;
474         char mdpath[MAXPATHLEN];
475         char obpath[MAXPATHLEN];
476         char cdpath[MAXPATHLEN];
477         const char *machine = getenv("MACHINE");
478         const char *machine_arch = getenv("MACHINE_ARCH");
479         const char *machine_cpu = getenv("MACHINE_CPU");
480         char *cp = NULL, *start;
481                                         /* avoid faults on read-only strings */
482         static char syspath[] = _PATH_DEFSYSPATH;
483
484         {
485         /*
486          * Catch SIGCHLD so that we get kicked out of select() when we
487          * need to look at a child.  This is only known to matter for the
488          * -j case (perhaps without -P).
489          *
490          * XXX this is intentionally misplaced.
491          */
492         struct sigaction sa;
493
494         sigemptyset(&sa.sa_mask);
495         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
496         sa.sa_handler = catch_child;
497         sigaction(SIGCHLD, &sa, NULL);
498         }
499
500         check_make_level();
501
502 #if DEFSHELL == 2
503         /*
504          * Turn off ENV to make ksh happier.
505          */
506         unsetenv("ENV");
507 #endif
508
509 #ifdef RLIMIT_NOFILE
510         /*
511          * get rid of resource limit on file descriptors
512          */
513         {
514                 struct rlimit rl;
515                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
516                     rl.rlim_cur != rl.rlim_max) {
517                         rl.rlim_cur = rl.rlim_max;
518                         setrlimit(RLIMIT_NOFILE, &rl);
519                 }
520         }
521 #endif
522
523         /*
524          * PC-98 kernel sets the `i386' string to the utsname.machine and
525          * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
526          * we check machine.ispc98 and adjust the machine variable before
527          * using usname(3) below.
528          * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
529          * __FreeBSD_version was defined as 300003. So, this check can
530          * safely be done with any kernel with version > 300003.
531          */
532         if (!machine) {
533                 int     ispc98;
534                 size_t  len;
535
536                 len = sizeof(ispc98);
537                 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
538                         if (ispc98)
539                                 machine = "pc98";
540                 }
541         }
542
543         /*
544          * Get the name of this type of MACHINE from utsname
545          * so we can share an executable for similar machines.
546          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
547          *
548          * Note that while MACHINE is decided at run-time,
549          * MACHINE_ARCH is always known at compile time.
550          */
551         if (!machine) {
552 #ifndef MACHINE
553             struct utsname utsname;
554
555             if (uname(&utsname) == -1)
556                     err(2, "uname");
557             machine = utsname.machine;
558 #else
559             machine = MACHINE;
560 #endif
561         }
562
563         if (!machine_arch) {
564 #ifndef MACHINE_ARCH
565                 machine_arch = "unknown";
566 #else
567                 machine_arch = MACHINE_ARCH;
568 #endif
569         }
570
571         /*
572          * Set machine_cpu to the minumum supported CPU revision based
573          * on the target architecture, if not already set.
574          */
575         if (!machine_cpu) {
576                 if (!strcmp(machine_arch, "i386"))
577                         machine_cpu = "i386";
578                 else if (!strcmp(machine_arch, "alpha"))
579                         machine_cpu = "ev4";
580                 else
581                         machine_cpu = "unknown";
582         }
583
584         expandVars = TRUE;
585         beSilent = FALSE;               /* Print commands as executed */
586         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
587         noExecute = FALSE;              /* Execute all commands */
588         keepgoing = FALSE;              /* Stop on error */
589         allPrecious = FALSE;            /* Remove targets when interrupted */
590         queryFlag = FALSE;              /* This is not just a check-run */
591         noBuiltins = FALSE;             /* Read the built-in rules */
592         touchFlag = FALSE;              /* Actually update targets */
593         usePipes = TRUE;                /* Catch child output in pipes */
594         debug = 0;                      /* No debug verbosity, please. */
595         jobsRunning = FALSE;
596
597         maxJobs = DEFMAXJOBS;
598         forceJobs = FALSE;              /* No -j flag */
599         compatMake = FALSE;             /* No compat mode */
600
601         /*
602          * Initialize the parsing, directory and variable modules to prepare
603          * for the reading of inclusion paths and variable settings on the
604          * command line
605          */
606         Dir_Init();             /* Initialize directory structures so -I flags
607                                  * can be processed correctly */
608         Parse_Init();           /* Need to initialize the paths of #include
609                                  * directories */
610         Var_Init();             /* As well as the lists of variables for
611                                  * parsing arguments */
612         str_init();
613
614         /*
615          * Initialize various variables.
616          *      MAKE also gets this name, for compatibility
617          *      .MAKEFLAGS gets set to the empty string just in case.
618          *      MFLAGS also gets initialized empty, for compatibility.
619          */
620         Var_Set("MAKE", argv[0], VAR_GLOBAL);
621         Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
622         Var_Set("MFLAGS", "", VAR_GLOBAL);
623         Var_Set("MACHINE", machine, VAR_GLOBAL);
624         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
625         Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
626 #ifdef MAKE_VERSION
627         Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
628 #endif
629
630         /*
631          * First snag any flags out of the MAKE environment variable.
632          * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
633          * in a different format).
634          */
635         Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
636
637         MainParseArgs(argc, argv);
638
639         /*
640          * Find where we are...
641          * All this code is so that we know where we are when we start up
642          * on a different machine with pmake.
643          */
644         curdir = cdpath;
645         if (getcwd(curdir, MAXPATHLEN) == NULL)
646                 err(2, NULL);
647
648         {
649         struct stat sa;
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 }