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