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