author: ru
[dragonfly.git] / usr.bin / make / main.c
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#) Copyright (c) 1988, 1989, 1990, 1993 The Regents of the University of California.  All rights reserved.
39  * @(#)main.c   8.3 (Berkeley) 3/19/94
40  * $FreeBSD: src/usr.bin/make/main.c,v 1.35.2.10 2003/12/16 08:34:11 des Exp $
41  * $DragonFly: src/usr.bin/make/main.c,v 1.20 2004/11/30 15:22:46 joerg Exp $
42  */
43
44 /*-
45  * main.c --
46  *      The main file for this entire program. Exit routines etc
47  *      reside here.
48  *
49  * Utility functions defined in this file:
50  *      Main_ParseArgLine       Takes a line of arguments, breaks them and
51  *                              treats them as if they were given when first
52  *                              invoked. Used by the parse module to implement
53  *                              the .MFLAGS target.
54  */
55
56 #include <sys/param.h>
57 #include <sys/signal.h>
58 #include <sys/stat.h>
59 #if defined(__i386__)
60 #include <sys/sysctl.h>
61 #endif
62 #include <sys/time.h>
63 #include <sys/resource.h>
64 #ifndef MACHINE
65 #include <sys/utsname.h>
66 #endif
67 #include <sys/wait.h>
68
69 #include <err.h>
70 #include <errno.h>
71 #include <fcntl.h>
72 #include <signal.h>
73 #include <stdarg.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <sysexits.h>
77 #include <unistd.h>
78
79 #include "make.h"
80 #include "hash.h"
81 #include "dir.h"
82 #include "job.h"
83 #include "pathnames.h"
84
85 #define WANT_ENV_MKLVL  1
86
87 #ifndef DEFMAXLOCAL
88 #define DEFMAXLOCAL DEFMAXJOBS
89 #endif  /* DEFMAXLOCAL */
90
91 #define MAKEFLAGS       ".MAKEFLAGS"
92
93 Lst                     create;         /* Targets to be made */
94 time_t                  now;            /* Time at start of make */
95 GNode                   *DEFAULT;       /* .DEFAULT node */
96 Boolean                 allPrecious;    /* .PRECIOUS given on line by itself */
97
98 static Boolean          noBuiltins;     /* -r flag */
99 static Lst              makefiles;      /* ordered list of makefiles to read */
100 static Boolean          expandVars;     /* fully expand printed variables */
101 static Lst              variables;      /* list of variables to print */
102 int                     maxJobs;        /* -j argument */
103 static Boolean          forceJobs;      /* -j argument given */
104 static int              maxLocal;       /* -L argument */
105 Boolean                 compatMake;     /* -B argument */
106 Boolean                 debug;          /* -d flag */
107 Boolean                 noExecute;      /* -n flag */
108 Boolean                 keepgoing;      /* -k flag */
109 Boolean                 queryFlag;      /* -q flag */
110 Boolean                 touchFlag;      /* -t flag */
111 Boolean                 usePipes;       /* !-P flag */
112 Boolean                 ignoreErrors;   /* -i flag */
113 Boolean                 beSilent;       /* -s flag */
114 Boolean                 beVerbose;      /* -v flag */
115 Boolean                 oldVars;        /* variable substitution style */
116 Boolean                 checkEnvFirst;  /* -e flag */
117 Lst                     envFirstVars;   /* (-E) vars to override from env */
118 Boolean                 jobsRunning;    /* TRUE if the jobs might be running */
119
120 static void             MainParseArgs(int, char **);
121 char *                  chdir_verify_path(char *, char *);
122 static int              ReadMakefile(void *, void *);
123 static void             usage(void);
124 static void             catch_child(int sig __unused);
125
126 static char *curdir;                    /* startup directory */
127 static char *objdir;                    /* where we chdir'ed to */
128
129
130 /*-
131  * MainParseArgs --
132  *      Parse a given argument vector. Called from main() and from
133  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
134  *
135  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
136  *
137  * Results:
138  *      None
139  *
140  * Side Effects:
141  *      Various global and local flags will be set depending on the flags
142  *      given
143  */
144 static void
145 MainParseArgs(int argc, char **argv)
146 {
147         char *p;
148         int c;
149
150         optind = 1;     /* since we're called more than once */
151 #ifdef REMOTE
152 # define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
153 #else
154 # define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
155 #endif
156 rearg:  while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
157                 switch(c) {
158                 case 'C':
159                         if (chdir(optarg) == -1)
160                                 err(1, "chdir %s", optarg);
161                         break;
162                 case 'D':
163                         Var_Set(optarg, "1", VAR_GLOBAL);
164                         Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
165                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
166                         break;
167                 case 'I':
168                         Parse_AddIncludeDir(optarg);
169                         Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
170                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
171                         break;
172                 case 'V':
173                         (void)Lst_AtEnd(variables, (void *)optarg);
174                         Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
175                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
176                         break;
177                 case 'X':
178                         expandVars = FALSE;
179                         break;
180                 case 'B':
181                         compatMake = TRUE;
182                         Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
183                         break;
184 #ifdef REMOTE
185                 case 'L': {
186                         char *endptr;
187
188                         maxLocal = strtol(optarg, &endptr, 10);
189                         if (maxLocal < 0 || *endptr != '\0') {
190                                 warnx("illegal number, -L argument -- %s",
191                                     optarg);
192                                 usage();
193                         }
194                         Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
195                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
196                         break;
197                 }
198 #endif
199                 case 'P':
200                         usePipes = FALSE;
201                         Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
202                         break;
203                 case 'S':
204                         keepgoing = FALSE;
205                         Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
206                         break;
207                 case 'd': {
208                         char *modules = optarg;
209
210                         for (; *modules; ++modules)
211                                 switch (*modules) {
212                                 case 'A':
213                                         debug = ~0;
214                                         break;
215                                 case 'a':
216                                         debug |= DEBUG_ARCH;
217                                         break;
218                                 case 'c':
219                                         debug |= DEBUG_COND;
220                                         break;
221                                 case 'd':
222                                         debug |= DEBUG_DIR;
223                                         break;
224                                 case 'f':
225                                         debug |= DEBUG_FOR;
226                                         break;
227                                 case 'g':
228                                         if (modules[1] == '1') {
229                                                 debug |= DEBUG_GRAPH1;
230                                                 ++modules;
231                                         }
232                                         else if (modules[1] == '2') {
233                                                 debug |= DEBUG_GRAPH2;
234                                                 ++modules;
235                                         }
236                                         break;
237                                 case 'j':
238                                         debug |= DEBUG_JOB;
239                                         break;
240                                 case 'l':
241                                         debug |= DEBUG_LOUD;
242                                         break;
243                                 case 'm':
244                                         debug |= DEBUG_MAKE;
245                                         break;
246                                 case 's':
247                                         debug |= DEBUG_SUFF;
248                                         break;
249                                 case 't':
250                                         debug |= DEBUG_TARG;
251                                         break;
252                                 case 'v':
253                                         debug |= DEBUG_VAR;
254                                         break;
255                                 default:
256                                         warnx("illegal argument to d option -- %c", *modules);
257                                         usage();
258                                 }
259                         Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
260                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
261                         break;
262                 }
263                 case 'E':
264                         p = emalloc(strlen(optarg) + 1);
265                         (void)strcpy(p, optarg);
266                         (void)Lst_AtEnd(envFirstVars, (void *)p);
267                         Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
268                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
269                         break;
270                 case 'e':
271                         checkEnvFirst = TRUE;
272                         Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
273                         break;
274                 case 'f':
275                         (void)Lst_AtEnd(makefiles, (void *)optarg);
276                         break;
277                 case 'i':
278                         ignoreErrors = TRUE;
279                         Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
280                         break;
281                 case 'j': {
282                         char *endptr;
283
284                         forceJobs = TRUE;
285                         maxJobs = strtol(optarg, &endptr, 10);
286                         if (maxJobs <= 0 || *endptr != '\0') {
287                                 warnx("illegal number, -j argument -- %s",
288                                     optarg);
289                                 usage();
290                         }
291 #ifndef REMOTE
292                         maxLocal = maxJobs;
293 #endif
294                         Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
295                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
296                         break;
297                 }
298                 case 'k':
299                         keepgoing = TRUE;
300                         Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
301                         break;
302                 case 'm':
303                         Dir_AddDir(sysIncPath, optarg);
304                         Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
305                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
306                         break;
307                 case 'n':
308                         noExecute = TRUE;
309                         Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
310                         break;
311                 case 'q':
312                         queryFlag = TRUE;
313                         /* Kind of nonsensical, wot? */
314                         Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
315                         break;
316                 case 'r':
317                         noBuiltins = TRUE;
318                         Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
319                         break;
320                 case 's':
321                         beSilent = TRUE;
322                         Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
323                         break;
324                 case 't':
325                         touchFlag = TRUE;
326                         Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
327                         break;
328                 case 'v':
329                         beVerbose = TRUE;
330                         Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
331                         break;
332                 default:
333                 case '?':
334                         usage();
335                 }
336         }
337
338         oldVars = TRUE;
339
340         /*
341          * See if the rest of the arguments are variable assignments and
342          * perform them if so. Else take them to be targets and stuff them
343          * on the end of the "create" list.
344          */
345         for (argv += optind, argc -= optind; *argv; ++argv, --argc)
346                 if (Parse_IsVar(*argv))
347                         Parse_DoVar(*argv, VAR_CMD);
348                 else {
349                         if (!**argv)
350                                 Punt("illegal (null) argument.");
351                         if (**argv == '-') {
352                                 if ((*argv)[1])
353                                         optind = 0;     /* -flag... */
354                                 else
355                                         optind = 1;     /* - */
356                                 goto rearg;
357                         }
358                         (void)Lst_AtEnd(create, (void *)estrdup(*argv));
359                 }
360 }
361
362 /*-
363  * Main_ParseArgLine --
364  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
365  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
366  *      Takes a line of arguments and breaks it into its
367  *      component words and passes those words and the number of them to the
368  *      MainParseArgs function.
369  *      The line should have all its leading whitespace removed.
370  *
371  * Results:
372  *      None
373  *
374  * Side Effects:
375  *      Only those that come from the various arguments.
376  */
377 void
378 Main_ParseArgLine(char *line)
379 {
380         char **argv;                    /* Manufactured argument vector */
381         int argc;                       /* Number of arguments in argv */
382
383         if (line == NULL)
384                 return;
385         for (; *line == ' '; ++line)
386                 continue;
387         if (!*line)
388                 return;
389
390         argv = brk_string(line, &argc, TRUE);
391         MainParseArgs(argc, argv);
392 }
393
394 char *
395 chdir_verify_path(char *path, char *obpath)
396 {
397         struct stat sb;
398
399         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
400                 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
401                         warn("warning: %s", path);
402                         return 0;
403                 }
404                 return obpath;
405         }
406
407         return 0;
408 }
409
410
411 /*-
412  * main --
413  *      The main function, for obvious reasons. Initializes variables
414  *      and a few modules, then parses the arguments give it in the
415  *      environment and on the command line. Reads the system makefile
416  *      followed by either Makefile, makefile or the file given by the
417  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
418  *      flags it has received by then uses either the Make or the Compat
419  *      module to create the initial list of targets.
420  *
421  * Results:
422  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
423  *      0.
424  *
425  * Side Effects:
426  *      The program exits when done. Targets are created. etc. etc. etc.
427  */
428 int
429 main(int argc, char **argv)
430 {
431         Lst targs;      /* target nodes to create -- passed to Make_Init */
432         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
433         struct stat sa;
434         char *p, *p1, *path, *pathp;
435 #ifdef WANT_ENV_MKLVL
436 #define MKLVL_MAXVAL    500
437 #define MKLVL_ENVVAR    "__MKLVL__"
438         int iMkLvl = 0;
439         char *szMkLvl = getenv(MKLVL_ENVVAR);
440 #endif  /* WANT_ENV_MKLVL */
441         char mdpath[MAXPATHLEN];
442         char obpath[MAXPATHLEN];
443         char cdpath[MAXPATHLEN];
444         char *machine = getenv("MACHINE");
445         char *machine_arch = getenv("MACHINE_ARCH");
446         char *machine_cpu = getenv("MACHINE_CPU");
447         Lst sysMkPath;                  /* Path of sys.mk */
448         char *cp = NULL, *start;
449                                         /* avoid faults on read-only strings */
450         static char syspath[] = _PATH_DEFSYSPATH;
451
452         {
453         /*
454          * Catch SIGCHLD so that we get kicked out of select() when we
455          * need to look at a child.  This is only known to matter for the
456          * -j case (perhaps without -P).
457          *
458          * XXX this is intentionally misplaced.
459          */
460         struct sigaction sa;
461
462 #ifdef WANT_ENV_MKLVL
463         if ((iMkLvl = szMkLvl ? atoi(szMkLvl) : 0) < 0) {
464           iMkLvl = 0;
465         }
466         if (iMkLvl++ > MKLVL_MAXVAL) {
467           errc(2, EAGAIN, 
468                "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
469         }
470         bzero(szMkLvl = emalloc(32), 32);
471         sprintf(szMkLvl, "%d", iMkLvl);
472         setenv(MKLVL_ENVVAR, szMkLvl, 1);
473 #endif /* WANT_ENV_MKLVL */
474
475         sigemptyset(&sa.sa_mask);
476         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
477         sa.sa_handler = catch_child;
478         sigaction(SIGCHLD, &sa, NULL);
479         }
480
481 #ifdef RLIMIT_NOFILE
482         /*
483          * get rid of resource limit on file descriptors
484          */
485         {
486                 struct rlimit rl;
487                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
488                     rl.rlim_cur != rl.rlim_max) {
489                         rl.rlim_cur = rl.rlim_max;
490                         (void) setrlimit(RLIMIT_NOFILE, &rl);
491                 }
492         }
493 #endif
494
495         /*
496          * PC-98 kernel sets the `i386' string to the utsname.machine and
497          * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
498          * we check machine.ispc98 and adjust the machine variable before
499          * using usname(3) below.
500          * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
501          * __FreeBSD_version was defined as 300003. So, this check can
502          * safely be done with any kernel with version > 300003.
503          */
504         if (!machine) {
505                 int     ispc98;
506                 size_t  len;
507
508                 len = sizeof(ispc98);
509                 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
510                         if (ispc98)
511                                 machine = "pc98";
512                 }
513         }
514
515         /*
516          * Get the name of this type of MACHINE from utsname
517          * so we can share an executable for similar machines.
518          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
519          *
520          * Note that while MACHINE is decided at run-time,
521          * MACHINE_ARCH is always known at compile time.
522          */
523         if (!machine) {
524 #ifndef MACHINE
525             struct utsname utsname;
526
527             if (uname(&utsname) == -1)
528                     err(2, "uname");
529             machine = utsname.machine;
530 #else
531             machine = MACHINE;
532 #endif
533         }
534
535         if (!machine_arch) {
536 #ifndef MACHINE_ARCH
537                 machine_arch = "unknown";
538 #else
539                 machine_arch = MACHINE_ARCH;
540 #endif
541         }
542
543         /*
544          * Set machine_cpu to the minumum supported CPU revision based
545          * on the target architecture, if not already set.
546          */
547         if (!machine_cpu) {
548                 if (!strcmp(machine_arch, "i386"))
549                         machine_cpu = "i386";
550                 else if (!strcmp(machine_arch, "alpha"))
551                         machine_cpu = "ev4";
552                 else
553                         machine_cpu = "unknown";
554         }
555
556         create = Lst_Init(FALSE);
557         makefiles = Lst_Init(FALSE);
558         envFirstVars = Lst_Init(FALSE);
559         expandVars = TRUE;
560         variables = Lst_Init(FALSE);
561         beSilent = FALSE;               /* Print commands as executed */
562         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
563         noExecute = FALSE;              /* Execute all commands */
564         keepgoing = FALSE;              /* Stop on error */
565         allPrecious = FALSE;            /* Remove targets when interrupted */
566         queryFlag = FALSE;              /* This is not just a check-run */
567         noBuiltins = FALSE;             /* Read the built-in rules */
568         touchFlag = FALSE;              /* Actually update targets */
569         usePipes = TRUE;                /* Catch child output in pipes */
570         debug = 0;                      /* No debug verbosity, please. */
571         jobsRunning = FALSE;
572
573         maxLocal = DEFMAXLOCAL;         /* Set default local max concurrency */
574 #ifdef REMOTE
575         maxJobs = DEFMAXJOBS;           /* Set default max concurrency */
576 #else
577         maxJobs = maxLocal;
578 #endif
579         forceJobs = FALSE;              /* No -j flag */
580         compatMake = FALSE;             /* No compat mode */
581
582
583         /*
584          * Initialize the parsing, directory and variable modules to prepare
585          * for the reading of inclusion paths and variable settings on the
586          * command line
587          */
588         Dir_Init();             /* Initialize directory structures so -I flags
589                                  * can be processed correctly */
590         Parse_Init();           /* Need to initialize the paths of #include
591                                  * directories */
592         Var_Init();             /* As well as the lists of variables for
593                                  * parsing arguments */
594         str_init();
595
596         /*
597          * Initialize various variables.
598          *      MAKE also gets this name, for compatibility
599          *      .MAKEFLAGS gets set to the empty string just in case.
600          *      MFLAGS also gets initialized empty, for compatibility.
601          */
602         Var_Set("MAKE", argv[0], VAR_GLOBAL);
603         Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
604         Var_Set("MFLAGS", "", VAR_GLOBAL);
605         Var_Set("MACHINE", machine, VAR_GLOBAL);
606         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
607         Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
608 #ifdef MAKE_VERSION
609         Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
610 #endif
611
612         /*
613          * First snag any flags out of the MAKE environment variable.
614          * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
615          * in a different format).
616          */
617 #ifdef POSIX
618         Main_ParseArgLine(getenv("MAKEFLAGS"));
619 #else
620         Main_ParseArgLine(getenv("MAKE"));
621 #endif
622
623         MainParseArgs(argc, argv);
624
625         /*
626          * Find where we are...
627          * All this code is so that we know where we are when we start up
628          * on a different machine with pmake.
629          */
630         curdir = cdpath;
631         if (getcwd(curdir, MAXPATHLEN) == NULL)
632                 err(2, NULL);
633
634         if (stat(curdir, &sa) == -1)
635             err(2, "%s", curdir);
636
637         /*
638          * The object directory location is determined using the
639          * following order of preference:
640          *
641          *      1. MAKEOBJDIRPREFIX`cwd`
642          *      2. MAKEOBJDIR
643          *      3. _PATH_OBJDIR.${MACHINE}
644          *      4. _PATH_OBJDIR
645          *      5. _PATH_OBJDIRPREFIX`cwd`
646          *
647          * If one of the first two fails, use the current directory.
648          * If the remaining three all fail, use the current directory.
649          *
650          * Once things are initted,
651          * have to add the original directory to the search path,
652          * and modify the paths for the Makefiles apropriately.  The
653          * current directory is also placed as a variable for make scripts.
654          */
655         if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
656                 if (!(path = getenv("MAKEOBJDIR"))) {
657                         path = _PATH_OBJDIR;
658                         pathp = _PATH_OBJDIRPREFIX;
659                         (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
660                                         path, machine);
661                         if (!(objdir = chdir_verify_path(mdpath, obpath)))
662                                 if (!(objdir=chdir_verify_path(path, obpath))) {
663                                         (void) snprintf(mdpath, MAXPATHLEN,
664                                                         "%s%s", pathp, curdir);
665                                         if (!(objdir=chdir_verify_path(mdpath,
666                                                                        obpath)))
667                                                 objdir = curdir;
668                                 }
669                 }
670                 else if (!(objdir = chdir_verify_path(path, obpath)))
671                         objdir = curdir;
672         }
673         else {
674                 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
675                 if (!(objdir = chdir_verify_path(mdpath, obpath)))
676                         objdir = curdir;
677         }
678         Dir_InitDot();          /* Initialize the "." directory */
679         if (objdir != curdir)
680                 Dir_AddDir(dirSearchPath, curdir);
681         Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
682         Var_Set(".CURDIR", curdir, VAR_GLOBAL);
683         Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
684
685         /*
686          * Be compatible if user did not specify -j and did not explicitly
687          * turned compatibility on
688          */
689         if (!compatMake && !forceJobs)
690                 compatMake = TRUE;
691
692         /*
693          * Initialize archive, target and suffix modules in preparation for
694          * parsing the makefile(s)
695          */
696         Arch_Init();
697         Targ_Init();
698         Suff_Init();
699
700         DEFAULT = NULL;
701         (void)time(&now);
702
703         /*
704          * Set up the .TARGETS variable to contain the list of targets to be
705          * created. If none specified, make the variable empty -- the parser
706          * will fill the thing in with the default or .MAIN target.
707          */
708         if (!Lst_IsEmpty(create)) {
709                 LstNode ln;
710
711                 for (ln = Lst_First(create); ln != NULL;
712                     ln = Lst_Succ(ln)) {
713                         char *name = (char *)Lst_Datum(ln);
714
715                         Var_Append(".TARGETS", name, VAR_GLOBAL);
716                 }
717         } else
718                 Var_Set(".TARGETS", "", VAR_GLOBAL);
719
720
721         /*
722          * If no user-supplied system path was given (through the -m option)
723          * add the directories from the DEFSYSPATH (more than one may be given
724          * as dir1:...:dirn) to the system include path.
725          */
726         if (Lst_IsEmpty(sysIncPath)) {
727                 for (start = syspath; *start != '\0'; start = cp) {
728                         for (cp = start; *cp != '\0' && *cp != ':'; cp++)
729                                 continue;
730                         if (*cp == '\0') {
731                                 Dir_AddDir(sysIncPath, start);
732                         } else {
733                                 *cp++ = '\0';
734                                 Dir_AddDir(sysIncPath, start);
735                         }
736                 }
737         }
738
739         /*
740          * Read in the built-in rules first, followed by the specified
741          * makefile, if it was (makefile != (char *) NULL), or the default
742          * Makefile and makefile, in that order, if it wasn't.
743          */
744         if (!noBuiltins) {
745                 LstNode ln;
746
747                 sysMkPath = Lst_Init (FALSE);
748                 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
749                 if (Lst_IsEmpty(sysMkPath))
750                         Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
751                 ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile);
752                 if (ln != NULL)
753                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
754         }
755
756         if (!Lst_IsEmpty(makefiles)) {
757                 LstNode ln;
758
759                 ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
760                 if (ln != NULL)
761                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
762         } else if (!ReadMakefile("BSDmakefile", NULL))
763             if (!ReadMakefile("makefile", NULL))
764                 (void)ReadMakefile("Makefile", NULL);
765
766         (void)ReadMakefile(".depend", NULL);
767
768         Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
769         free(p1);
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                 }
877                 Lst_Destroy(targs, NOFREE);
878         }
879
880         Lst_Destroy(variables, NOFREE);
881         Lst_Destroy(makefiles, NOFREE);
882         Lst_Destroy(create, (void (*) (void *)) free);
883
884         /* print the graph now it's been processed if the user requested it */
885         if (DEBUG(GRAPH2))
886                 Targ_PrintGraph(2);
887
888         Suff_End();
889         Targ_End();
890         Arch_End();
891         str_end();
892         Var_End();
893         Parse_End();
894         Dir_End();
895
896         if (queryFlag && outOfDate)
897                 return(1);
898         else
899                 return(0);
900 }
901
902 /*-
903  * ReadMakefile  --
904  *      Open and parse the given makefile.
905  *
906  * Results:
907  *      TRUE if ok. FALSE if couldn't open file.
908  *
909  * Side Effects:
910  *      lots
911  */
912 static Boolean
913 ReadMakefile(void *p, void *q __unused)
914 {
915         char *fname;            /* makefile to read */
916         FILE *stream;
917         char *name, path[MAXPATHLEN];
918         char *MAKEFILE;
919         int setMAKEFILE;
920
921         fname = p;
922
923         if (!strcmp(fname, "-")) {
924                 Parse_File("(stdin)", stdin);
925                 Var_Set("MAKEFILE", "", VAR_GLOBAL);
926         } else {
927                 setMAKEFILE = strcmp(fname, ".depend");
928
929                 /* if we've chdir'd, rebuild the path name */
930                 if (curdir != objdir && *fname != '/') {
931                         (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
932                         /*
933                          * XXX The realpath stuff breaks relative includes
934                          * XXX in some cases.   The problem likely is in
935                          * XXX parse.c where it does special things in
936                          * XXX ParseDoInclude if the file is relateive
937                          * XXX or absolute and not a system file.  There
938                          * XXX it assumes that if the current file that's
939                          * XXX being included is absolute, that any files
940                          * XXX that it includes shouldn't do the -I path
941                          * XXX stuff, which is inconsistant with historical
942                          * XXX behavior.  However, I can't pentrate the mists
943                          * XXX further, so I'm putting this workaround in
944                          * XXX here until such time as the underlying bug
945                          * XXX can be fixed.
946                          */
947 #if THIS_BREAKS_THINGS
948                         if (realpath(path, path) != NULL &&
949                             (stream = fopen(path, "r")) != NULL) {
950                                 MAKEFILE = fname;
951                                 fname = path;
952                                 goto found;
953                         }
954                 } else if (realpath(fname, path) != NULL) {
955                         MAKEFILE = fname;
956                         fname = path;
957                         if ((stream = fopen(fname, "r")) != NULL)
958                                 goto found;
959                 }
960 #else
961                         if ((stream = fopen(path, "r")) != NULL) {
962                                 MAKEFILE = fname;
963                                 fname = path;
964                                 goto found;
965                         }
966                 } else {
967                         MAKEFILE = fname;
968                         if ((stream = fopen(fname, "r")) != NULL)
969                                 goto found;
970                 }
971 #endif
972                 /* look in -I and system include directories. */
973                 name = Dir_FindFile(fname, parseIncPath);
974                 if (!name)
975                         name = Dir_FindFile(fname, sysIncPath);
976                 if (!name || !(stream = fopen(name, "r")))
977                         return(FALSE);
978                 MAKEFILE = fname = name;
979                 /*
980                  * set the MAKEFILE variable desired by System V fans -- the
981                  * placement of the setting here means it gets set to the last
982                  * makefile specified, as it is set by SysV make.
983                  */
984 found:
985                 if (setMAKEFILE)
986                         Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
987                 Parse_File(fname, stream);
988                 (void)fclose(stream);
989         }
990         return(TRUE);
991 }
992
993 /*-
994  * Cmd_Exec --
995  *      Execute the command in cmd, and return the output of that command
996  *      in a string.
997  *
998  * Results:
999  *      A string containing the output of the command, or the empty string
1000  *      If error is not NULL, it contains the reason for the command failure
1001  *
1002  * Side Effects:
1003  *      The string must be freed by the caller.
1004  */
1005 char *
1006 Cmd_Exec(char *cmd, char **error)
1007 {
1008     char        *args[4];       /* Args for invoking the shell */
1009     int         fds[2];         /* Pipe streams */
1010     int         cpid;           /* Child PID */
1011     int         pid;            /* PID from wait() */
1012     char        *res;           /* result */
1013     int         status;         /* command exit status */
1014     Buffer      buf;            /* buffer to store the result */
1015     char        *cp;
1016     int         cc;
1017
1018     *error = NULL;
1019
1020     /*
1021      * Set up arguments for shell
1022      */
1023     args[0] = "sh";
1024     args[1] = "-c";
1025     args[2] = cmd;
1026     args[3] = NULL;
1027
1028     /*
1029      * Open a pipe for fetching its output
1030      */
1031     if (pipe(fds) == -1) {
1032         *error = "Couldn't create pipe for \"%s\"";
1033         goto bad;
1034     }
1035
1036     /*
1037      * Fork
1038      */
1039     switch (cpid = vfork()) {
1040     case 0:
1041         /*
1042          * Close input side of pipe
1043          */
1044         (void) close(fds[0]);
1045
1046         /*
1047          * Duplicate the output stream to the shell's output, then
1048          * shut the extra thing down. Note we don't fetch the error
1049          * stream...why not? Why?
1050          */
1051         (void) dup2(fds[1], 1);
1052         (void) close(fds[1]);
1053
1054         (void) execv("/bin/sh", args);
1055         _exit(1);
1056         /*NOTREACHED*/
1057
1058     case -1:
1059         *error = "Couldn't exec \"%s\"";
1060         goto bad;
1061
1062     default:
1063         /*
1064          * No need for the writing half
1065          */
1066         (void) close(fds[1]);
1067
1068         buf = Buf_Init (MAKE_BSIZE);
1069
1070         do {
1071             char   result[BUFSIZ];
1072             cc = read(fds[0], result, sizeof(result));
1073             if (cc > 0)
1074                 Buf_AddBytes(buf, cc, (Byte *) result);
1075         }
1076         while (cc > 0 || (cc == -1 && errno == EINTR));
1077
1078         /*
1079          * Close the input side of the pipe.
1080          */
1081         (void) close(fds[0]);
1082
1083         /*
1084          * Wait for the process to exit.
1085          */
1086         while(((pid = wait(&status)) != cpid) && (pid >= 0))
1087             continue;
1088
1089         if (cc == -1)
1090             *error = "Error reading shell's output for \"%s\"";
1091
1092         res = (char *)Buf_GetAll (buf, &cc);
1093         Buf_Destroy (buf, FALSE);
1094
1095         if (status)
1096             *error = "\"%s\" returned non-zero status";
1097
1098         /*
1099          * Null-terminate the result, convert newlines to spaces and
1100          * install it in the variable.
1101          */
1102         res[cc] = '\0';
1103         cp = &res[cc] - 1;
1104
1105         if (*cp == '\n') {
1106             /*
1107              * A final newline is just stripped
1108              */
1109             *cp-- = '\0';
1110         }
1111         while (cp >= res) {
1112             if (*cp == '\n') {
1113                 *cp = ' ';
1114             }
1115             cp--;
1116         }
1117         break;
1118     }
1119     return res;
1120 bad:
1121     res = emalloc(1);
1122     *res = '\0';
1123     return res;
1124 }
1125  
1126 /*
1127  * usage --
1128  *      exit with usage message
1129  */
1130 static void
1131 usage(void)
1132 {
1133         (void)fprintf(stderr, "%s\n%s\n%s\n",
1134 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1135 "            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1136 "            [-m directory] [-V variable] [variable=value] [target ...]");
1137         exit(2);
1138 }
1139
1140 static
1141 void
1142 catch_child(int sig __unused)
1143 {
1144 }
1145