Merge from vendor branch NCURSES:
[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.60 2005/03/12 11:29:33 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         char *str;
147
148         Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
149         if (arg != NULL) {
150                 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                 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
402         MainParseArgs(argc, argv);
403 }
404
405 char *
406 chdir_verify_path(const char *path, char *obpath)
407 {
408         struct stat sb;
409
410         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
411                 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
412                         warn("warning: %s", path);
413                         return (NULL);
414                 }
415                 return (obpath);
416         }
417
418         return (NULL);
419 }
420
421 static void
422 catch_child(int sig __unused)
423 {
424 }
425
426 /*
427  * In lieu of a good way to prevent every possible looping in
428  * make(1), stop there from being more than MKLVL_MAXVAL processes forked
429  * by make(1), to prevent a forkbomb from happening, in a dumb and
430  * mechanical way.
431  */
432 static void
433 check_make_level(void)
434 {
435 #ifdef WANT_ENV_MKLVL
436         char    *value = getenv(MKLVL_ENVVAR);
437         int     level = (value == NULL) ? 0 : atoi(value);
438
439         if (level < 0) {
440                 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
441         } else if (level > MKLVL_MAXVAL) {
442                 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
443         } else {
444                 char new_value[32];
445                 sprintf(new_value, "%d", level + 1);
446                 setenv(MKLVL_ENVVAR, new_value, 1);
447         }
448 #endif /* WANT_ENV_MKLVL */
449 }
450
451 /*-
452  * main --
453  *      The main function, for obvious reasons. Initializes variables
454  *      and a few modules, then parses the arguments give it in the
455  *      environment and on the command line. Reads the system makefile
456  *      followed by either Makefile, makefile or the file given by the
457  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
458  *      flags it has received by then uses either the Make or the Compat
459  *      module to create the initial list of targets.
460  *
461  * Results:
462  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
463  *      0.
464  *
465  * Side Effects:
466  *      The program exits when done. Targets are created. etc. etc. etc.
467  */
468 int
469 main(int argc, char **argv)
470 {
471         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
472         char *p, *p1;
473         const char *pathp;
474         const char *path;
475         char mdpath[MAXPATHLEN];
476         char obpath[MAXPATHLEN];
477         char cdpath[MAXPATHLEN];
478         const char *machine = getenv("MACHINE");
479         const char *machine_arch = getenv("MACHINE_ARCH");
480         const char *machine_cpu = getenv("MACHINE_CPU");
481         char *cp = NULL, *start;
482
483                                         /* avoid faults on read-only strings */
484         static char syspath[] = PATH_DEFSYSPATH;
485
486         {
487         /*
488          * Catch SIGCHLD so that we get kicked out of select() when we
489          * need to look at a child.  This is only known to matter for the
490          * -j case (perhaps without -P).
491          *
492          * XXX this is intentionally misplaced.
493          */
494         struct sigaction sa;
495
496         sigemptyset(&sa.sa_mask);
497         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
498         sa.sa_handler = catch_child;
499         sigaction(SIGCHLD, &sa, NULL);
500         }
501
502         check_make_level();
503
504 #if DEFSHELL == 2
505         /*
506          * Turn off ENV to make ksh happier.
507          */
508         unsetenv("ENV");
509 #endif
510
511 #ifdef RLIMIT_NOFILE
512         /*
513          * get rid of resource limit on file descriptors
514          */
515         {
516                 struct rlimit rl;
517                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
518                     rl.rlim_cur != rl.rlim_max) {
519                         rl.rlim_cur = rl.rlim_max;
520                         setrlimit(RLIMIT_NOFILE, &rl);
521                 }
522         }
523 #endif
524
525         /*
526          * PC-98 kernel sets the `i386' string to the utsname.machine and
527          * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
528          * we check machine.ispc98 and adjust the machine variable before
529          * using usname(3) below.
530          * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
531          * __FreeBSD_version was defined as 300003. So, this check can
532          * safely be done with any kernel with version > 300003.
533          */
534         if (!machine) {
535                 int     ispc98;
536                 size_t  len;
537
538                 len = sizeof(ispc98);
539                 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
540                         if (ispc98)
541                                 machine = "pc98";
542                 }
543         }
544
545         /*
546          * Get the name of this type of MACHINE from utsname
547          * so we can share an executable for similar machines.
548          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
549          *
550          * Note that while MACHINE is decided at run-time,
551          * MACHINE_ARCH is always known at compile time.
552          */
553         if (!machine) {
554 #ifndef MACHINE
555             struct utsname utsname;
556
557             if (uname(&utsname) == -1)
558                     err(2, "uname");
559             machine = utsname.machine;
560 #else
561             machine = MACHINE;
562 #endif
563         }
564
565         if (!machine_arch) {
566 #ifndef MACHINE_ARCH
567                 machine_arch = "unknown";
568 #else
569                 machine_arch = MACHINE_ARCH;
570 #endif
571         }
572
573         /*
574          * Set machine_cpu to the minumum supported CPU revision based
575          * on the target architecture, if not already set.
576          */
577         if (!machine_cpu) {
578                 if (!strcmp(machine_arch, "i386"))
579                         machine_cpu = "i386";
580                 else if (!strcmp(machine_arch, "alpha"))
581                         machine_cpu = "ev4";
582                 else
583                         machine_cpu = "unknown";
584         }
585
586         expandVars = TRUE;
587         beSilent = FALSE;               /* Print commands as executed */
588         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
589         noExecute = FALSE;              /* Execute all commands */
590         keepgoing = FALSE;              /* Stop on error */
591         allPrecious = FALSE;            /* Remove targets when interrupted */
592         queryFlag = FALSE;              /* This is not just a check-run */
593         noBuiltins = FALSE;             /* Read the built-in rules */
594         touchFlag = FALSE;              /* Actually update targets */
595         usePipes = TRUE;                /* Catch child output in pipes */
596         debug = 0;                      /* No debug verbosity, please. */
597         jobsRunning = FALSE;
598
599         maxJobs = DEFMAXJOBS;
600         forceJobs = FALSE;              /* No -j flag */
601         compatMake = FALSE;             /* No compat mode */
602
603         /*
604          * Initialize the parsing, directory and variable modules to prepare
605          * for the reading of inclusion paths and variable settings on the
606          * command line
607          */
608         Dir_Init();             /* Initialize directory structures so -I flags
609                                  * can be processed correctly */
610         Parse_Init();           /* Need to initialize the paths of #include
611                                  * directories */
612         Var_Init();             /* As well as the lists of variables for
613                                  * parsing arguments */
614         str_init();
615
616         /*
617          * Initialize various variables.
618          *      MAKE also gets this name, for compatibility
619          *      .MAKEFLAGS gets set to the empty string just in case.
620          *      MFLAGS also gets initialized empty, for compatibility.
621          */
622         Var_Set("MAKE", argv[0], VAR_GLOBAL);
623         Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
624         Var_Set("MFLAGS", "", VAR_GLOBAL);
625         Var_Set("MACHINE", machine, VAR_GLOBAL);
626         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
627         Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
628 #ifdef MAKE_VERSION
629         Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
630 #endif
631
632         /*
633          * First snag any flags out of the MAKE environment variable.
634          * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
635          * in a different format).
636          */
637         Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
638
639         MainParseArgs(argc, argv);
640
641         /*
642          * Find where we are...
643          * All this code is so that we know where we are when we start up
644          * on a different machine with pmake.
645          */
646         curdir = cdpath;
647         if (getcwd(curdir, MAXPATHLEN) == NULL)
648                 err(2, NULL);
649
650         {
651         struct stat sa;
652
653         if (stat(curdir, &sa) == -1)
654             err(2, "%s", curdir);
655         }
656
657         /*
658          * The object directory location is determined using the
659          * following order of preference:
660          *
661          *      1. MAKEOBJDIRPREFIX`cwd`
662          *      2. MAKEOBJDIR
663          *      3. PATH_OBJDIR.${MACHINE}
664          *      4. PATH_OBJDIR
665          *      5. PATH_OBJDIRPREFIX`cwd`
666          *
667          * If one of the first two fails, use the current directory.
668          * If the remaining three all fail, use the current directory.
669          *
670          * Once things are initted,
671          * have to add the original directory to the search path,
672          * and modify the paths for the Makefiles apropriately.  The
673          * current directory is also placed as a variable for make scripts.
674          */
675         if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
676                 if (!(path = getenv("MAKEOBJDIR"))) {
677                         path = PATH_OBJDIR;
678                         pathp = PATH_OBJDIRPREFIX;
679                         snprintf(mdpath, MAXPATHLEN, "%s.%s",
680                                         path, machine);
681                         if (!(objdir = chdir_verify_path(mdpath, obpath)))
682                                 if (!(objdir=chdir_verify_path(path, obpath))) {
683                                         snprintf(mdpath, MAXPATHLEN,
684                                                         "%s%s", pathp, curdir);
685                                         if (!(objdir=chdir_verify_path(mdpath,
686                                                                        obpath)))
687                                                 objdir = curdir;
688                                 }
689                 }
690                 else if (!(objdir = chdir_verify_path(path, obpath)))
691                         objdir = curdir;
692         }
693         else {
694                 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
695                 if (!(objdir = chdir_verify_path(mdpath, obpath)))
696                         objdir = curdir;
697         }
698         Dir_InitDot();          /* Initialize the "." directory */
699         if (objdir != curdir)
700                 Dir_AddDir(&dirSearchPath, curdir);
701         Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
702         Var_Set(".CURDIR", curdir, VAR_GLOBAL);
703         Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
704
705         if (getenv("MAKE_JOBS_FIFO") != NULL)
706                 forceJobs = TRUE;
707         /*
708          * Be compatible if user did not specify -j and did not explicitly
709          * turned compatibility on
710          */
711         if (!compatMake && !forceJobs)
712                 compatMake = TRUE;
713
714         /*
715          * Initialize archive, target and suffix modules in preparation for
716          * parsing the makefile(s)
717          */
718         Arch_Init();
719         Targ_Init();
720         Suff_Init();
721
722         DEFAULT = NULL;
723         time(&now);
724
725         /*
726          * Set up the .TARGETS variable to contain the list of targets to be
727          * created. If none specified, make the variable empty -- the parser
728          * will fill the thing in with the default or .MAIN target.
729          */
730         if (!Lst_IsEmpty(&create)) {
731                 LstNode *ln;
732
733                 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
734                         char *name = Lst_Datum(ln);
735
736                         Var_Append(".TARGETS", name, VAR_GLOBAL);
737                 }
738         } else
739                 Var_Set(".TARGETS", "", VAR_GLOBAL);
740
741
742         /*
743          * If no user-supplied system path was given (through the -m option)
744          * add the directories from the DEFSYSPATH (more than one may be given
745          * as dir1:...:dirn) to the system include path.
746          */
747         if (Lst_IsEmpty(&sysIncPath)) {
748                 for (start = syspath; *start != '\0'; start = cp) {
749                         for (cp = start; *cp != '\0' && *cp != ':'; cp++)
750                                 continue;
751                         if (*cp == '\0') {
752                                 Dir_AddDir(&sysIncPath, start);
753                         } else {
754                                 *cp++ = '\0';
755                                 Dir_AddDir(&sysIncPath, start);
756                         }
757                 }
758         }
759
760         /*
761          * Read in the built-in rules first, followed by the specified
762          * makefile, if it was (makefile != (char *) NULL), or the default
763          * Makefile and makefile, in that order, if it wasn't.
764          */
765         if (!noBuiltins) {
766                 /* Path of sys.mk */
767                 Lst sysMkPath = Lst_Initializer(sysMkPath);
768                 LstNode *ln;
769
770                 Dir_Expand(PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
771                 if (Lst_IsEmpty(&sysMkPath))
772                         Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
773                 ln = Lst_Find(&sysMkPath, NULL, ReadMakefile);
774                 if (ln != NULL)
775                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
776                 Lst_Destroy(&sysMkPath, free);
777         }
778
779         if (!Lst_IsEmpty(&makefiles)) {
780                 LstNode *ln;
781
782                 ln = Lst_Find(&makefiles, NULL, ReadMakefile);
783                 if (ln != NULL)
784                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
785         } else if (!ReadMakefile("BSDmakefile", NULL))
786             if (!ReadMakefile("makefile", NULL))
787                 ReadMakefile("Makefile", NULL);
788
789         ReadMakefile(".depend", NULL);
790
791         /* Install all the flags into the MAKE envariable. */
792         if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
793                 setenv("MAKEFLAGS", p, 1);
794         free(p1);
795
796         /*
797          * For compatibility, look at the directories in the VPATH variable
798          * and add them to the search path, if the variable is defined. The
799          * variable's value is in the same format as the PATH envariable, i.e.
800          * <directory>:<directory>:<directory>...
801          */
802         if (Var_Exists("VPATH", VAR_CMD)) {
803                 /*
804                  * GCC stores string constants in read-only memory, but
805                  * Var_Subst will want to write this thing, so store it
806                  * in an array
807                  */
808                 static char VPATH[] = "${VPATH}";
809                 Buffer  *buf;
810                 char    *vpath;
811                 char    *ptr;
812                 char    savec;
813
814                 buf = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
815
816                 vpath = Buf_GetAll(buf, NULL);
817                 do {
818                         /* skip to end of directory */
819                         for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
820                                 ;
821
822                         /* Save terminator character so know when to stop */
823                         savec = *ptr;
824                         *ptr = '\0';
825
826                         /* Add directory to search path */
827                         Dir_AddDir(&dirSearchPath, vpath);
828
829                         vpath = ptr + 1;
830                 } while (savec != '\0');
831
832                 Buf_Destroy(buf, TRUE);
833         }
834
835         /*
836          * Now that all search paths have been read for suffixes et al, it's
837          * time to add the default search path to their lists...
838          */
839         Suff_DoPaths();
840
841         /* print the initial graph, if the user requested it */
842         if (DEBUG(GRAPH1))
843                 Targ_PrintGraph(1);
844
845         /* print the values of any variables requested by the user */
846         if (Lst_IsEmpty(&variables)) {
847                 /*
848                  * Since the user has not requested that any variables
849                  * be printed, we can build targets.
850                  *
851                  * Have read the entire graph and need to make a list of targets
852                  * to create. If none was given on the command line, we consult
853                  * the parsing module to find the main target(s) to create.
854                  */
855                 Lst targs = Lst_Initializer(targs);
856
857                 if (Lst_IsEmpty(&create))
858                         Parse_MainName(&targs);
859                 else
860                         Targ_FindList(&targs, &create, TARG_CREATE);
861
862                 if (compatMake) {
863                         /*
864                          * Compat_Init will take care of creating
865                          * all the targets as well as initializing
866                          * the module.
867                          */
868                         Compat_Run(&targs);
869                         outOfDate = 0;
870                 } else {
871                         /*
872                          * Initialize job module before traversing
873                          * the graph, now that any .BEGIN and .END
874                          * targets have been read.  This is done
875                          * only if the -q flag wasn't given (to
876                          * prevent the .BEGIN from being executed
877                          * should it exist).
878                          */
879                         if (!queryFlag) {
880                                 Job_Init(maxJobs);
881                                 jobsRunning = TRUE;
882                         }
883
884                         /* Traverse the graph, checking on all the targets */
885                         outOfDate = Make_Run(&targs);
886                 }
887                 Lst_Destroy(&targs, NOFREE);
888
889         } else {
890                 /*
891                  * Print the values of any variables requested by
892                  * the user.
893                  */
894                 LstNode *n;
895
896                 LST_FOREACH(n, &variables) {
897                         const char      *name = Lst_Datum(n);
898                         if (expandVars) {
899                                 char            *v;
900                                 char            *value;
901
902                                 v = emalloc(strlen(name) + 1 + 3);
903                                 sprintf(v, "${%s}", name);
904
905                                 value = Buf_Peel(Var_Subst(NULL, v,
906                                     VAR_GLOBAL, FALSE));
907                                 printf("%s\n", value);
908
909                                 free(v);
910                                 free(value);
911                         } else {
912                                 char    *value;
913                                 char    *v;
914                                 value = Var_Value(name, VAR_GLOBAL, &v);
915                                 printf("%s\n", value != NULL ? value : "");
916                                 if (v != NULL)
917                                         free(v);
918                         }
919                 }
920         }
921
922         Lst_Destroy(&variables, free);
923         Lst_Destroy(&makefiles, free);
924         Lst_Destroy(&create, free);
925
926         /* print the graph now it's been processed if the user requested it */
927         if (DEBUG(GRAPH2))
928                 Targ_PrintGraph(2);
929
930         if (queryFlag && outOfDate)
931                 return (1);
932         else
933                 return (0);
934 }
935
936 /*-
937  * ReadMakefile  --
938  *      Open and parse the given makefile.
939  *
940  * Results:
941  *      TRUE if ok. FALSE if couldn't open file.
942  *
943  * Side Effects:
944  *      lots
945  */
946 static Boolean
947 ReadMakefile(const void *p, const void *q __unused)
948 {
949         char *fname;                    /* makefile to read */
950         FILE *stream;
951         char *name, path[MAXPATHLEN];
952         char *MAKEFILE;
953         int setMAKEFILE;
954
955         /* XXX - remove this once constification is done */
956         fname = estrdup(p);
957
958         if (!strcmp(fname, "-")) {
959                 Parse_File("(stdin)", stdin);
960                 Var_Set("MAKEFILE", "", VAR_GLOBAL);
961         } else {
962                 setMAKEFILE = strcmp(fname, ".depend");
963
964                 /* if we've chdir'd, rebuild the path name */
965                 if (curdir != objdir && *fname != '/') {
966                         snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
967                         /*
968                          * XXX The realpath stuff breaks relative includes
969                          * XXX in some cases.   The problem likely is in
970                          * XXX parse.c where it does special things in
971                          * XXX ParseDoInclude if the file is relateive
972                          * XXX or absolute and not a system file.  There
973                          * XXX it assumes that if the current file that's
974                          * XXX being included is absolute, that any files
975                          * XXX that it includes shouldn't do the -I path
976                          * XXX stuff, which is inconsistant with historical
977                          * XXX behavior.  However, I can't pentrate the mists
978                          * XXX further, so I'm putting this workaround in
979                          * XXX here until such time as the underlying bug
980                          * XXX can be fixed.
981                          */
982 #if THIS_BREAKS_THINGS
983                         if (realpath(path, path) != NULL &&
984                             (stream = fopen(path, "r")) != NULL) {
985                                 MAKEFILE = fname;
986                                 fname = path;
987                                 goto found;
988                         }
989                 } else if (realpath(fname, path) != NULL) {
990                         MAKEFILE = fname;
991                         fname = path;
992                         if ((stream = fopen(fname, "r")) != NULL)
993                                 goto found;
994                 }
995 #else
996                         if ((stream = fopen(path, "r")) != NULL) {
997                                 MAKEFILE = fname;
998                                 fname = path;
999                                 goto found;
1000                         }
1001                 } else {
1002                         MAKEFILE = fname;
1003                         if ((stream = fopen(fname, "r")) != NULL)
1004                                 goto found;
1005                 }
1006 #endif
1007                 /* look in -I and system include directories. */
1008                 name = Dir_FindFile(fname, &parseIncPath);
1009                 if (!name)
1010                         name = Dir_FindFile(fname, &sysIncPath);
1011                 if (!name || !(stream = fopen(name, "r")))
1012                         return (FALSE);
1013                 MAKEFILE = fname = name;
1014                 /*
1015                  * set the MAKEFILE variable desired by System V fans -- the
1016                  * placement of the setting here means it gets set to the last
1017                  * makefile specified, as it is set by SysV make.
1018                  */
1019 found:
1020                 if (setMAKEFILE)
1021                         Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1022                 Parse_File(fname, stream);
1023                 fclose(stream);
1024         }
1025         return (TRUE);
1026 }
1027
1028 /*-
1029  * Cmd_Exec --
1030  *      Execute the command in cmd, and return the output of that command
1031  *      in a string.
1032  *
1033  * Results:
1034  *      A string containing the output of the command, or the empty string
1035  *      If error is not NULL, it contains the reason for the command failure
1036  *
1037  * Side Effects:
1038  *      The string must be freed by the caller.
1039  */
1040 Buffer *
1041 Cmd_Exec(const char *cmd, const char **error)
1042 {
1043     int         fds[2];         /* Pipe streams */
1044     int         cpid;           /* Child PID */
1045     int         pid;            /* PID from wait() */
1046     int         status;         /* command exit status */
1047     Buffer      *buf;           /* buffer to store the result */
1048     ssize_t     rcnt;
1049
1050     *error = NULL;
1051     buf = Buf_Init(0);
1052
1053     if (shellPath == NULL)
1054         Shell_Init();
1055     /*
1056      * Open a pipe for fetching its output
1057      */
1058     if (pipe(fds) == -1) {
1059         *error = "Couldn't create pipe for \"%s\"";
1060         return (buf);
1061     }
1062
1063     /*
1064      * Fork
1065      */
1066     switch (cpid = vfork()) {
1067     case 0:
1068         /*
1069          * Close input side of pipe
1070          */
1071         close(fds[0]);
1072
1073         /*
1074          * Duplicate the output stream to the shell's output, then
1075          * shut the extra thing down. Note we don't fetch the error
1076          * stream...why not? Why?
1077          */
1078         dup2(fds[1], 1);
1079         close(fds[1]);
1080
1081         {
1082             char        *args[4];
1083
1084             /* Set up arguments for shell */
1085             args[0] = shellName;
1086             args[1] = "-c";
1087             args[2] = cmd;
1088             args[3] = NULL;
1089
1090             execv(shellPath, args);
1091             _exit(1);
1092             /*NOTREACHED*/
1093         }
1094
1095     case -1:
1096         *error = "Couldn't exec \"%s\"";
1097         return (buf);
1098
1099     default:
1100         /*
1101          * No need for the writing half
1102          */
1103         close(fds[1]);
1104
1105         do {
1106             char   result[BUFSIZ];
1107             rcnt = read(fds[0], result, sizeof(result));
1108             if (rcnt != -1)
1109                 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1110         } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1111
1112         if (rcnt == -1)
1113             *error = "Error reading shell's output for \"%s\"";
1114
1115         /*
1116          * Close the input side of the pipe.
1117          */
1118         close(fds[0]);
1119
1120         /*
1121          * Wait for the process to exit.
1122          */
1123         while (((pid = wait(&status)) != cpid) && (pid >= 0))
1124             continue;
1125
1126         if (status)
1127             *error = "\"%s\" returned non-zero status";
1128
1129         Buf_StripNewlines(buf);
1130
1131         break;
1132     }
1133     return (buf);
1134 }
1135
1136 /*
1137  * usage --
1138  *      exit with usage message
1139  */
1140 static void
1141 usage(void)
1142 {
1143         fprintf(stderr, "%s\n%s\n%s\n",
1144 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1145 "            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1146 "            [-m directory] [-V variable] [variable=value] [target ...]");
1147         exit(2);
1148 }