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