Merge from vendor branch LIBARCHIVE:
[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.7 2004/10/24 22:43:58 dillon Exp $
42  */
43
44 static
45 void
46 catch_child(int sig)
47 {
48 }
49
50 /*-
51  * main.c --
52  *      The main file for this entire program. Exit routines etc
53  *      reside here.
54  *
55  * Utility functions defined in this file:
56  *      Main_ParseArgLine       Takes a line of arguments, breaks them and
57  *                              treats them as if they were given when first
58  *                              invoked. Used by the parse module to implement
59  *                              the .MFLAGS target.
60  *
61  *      Error                   Print a tagged error message. The global
62  *                              MAKE variable must have been defined. This
63  *                              takes a format string and two optional
64  *                              arguments for it.
65  *
66  *      Fatal                   Print an error message and exit. Also takes
67  *                              a format string and two arguments.
68  *
69  *      Punt                    Aborts all jobs and exits with a message. Also
70  *                              takes a format string and two arguments.
71  *
72  *      Finish                  Finish things up by printing the number of
73  *                              errors which occured, as passed to it, and
74  *                              exiting.
75  */
76
77 #include <sys/types.h>
78 #include <sys/time.h>
79 #include <sys/param.h>
80 #include <sys/resource.h>
81 #include <sys/signal.h>
82 #include <sys/stat.h>
83 #if defined(__i386__)
84 #include <sys/sysctl.h>
85 #endif
86 #ifndef MACHINE
87 #include <sys/utsname.h>
88 #endif
89 #include <sys/wait.h>
90 #include <err.h>
91 #include <stdlib.h>
92 #include <errno.h>
93 #include <fcntl.h>
94 #include <stdio.h>
95 #include <sysexits.h>
96 #ifdef __STDC__
97 #include <stdarg.h>
98 #else
99 #include <varargs.h>
100 #endif
101 #include "make.h"
102 #include "hash.h"
103 #include "dir.h"
104 #include "job.h"
105 #include "pathnames.h"
106
107 #ifndef DEFMAXLOCAL
108 #define DEFMAXLOCAL DEFMAXJOBS
109 #endif  /* DEFMAXLOCAL */
110
111 #define MAKEFLAGS       ".MAKEFLAGS"
112
113 Lst                     create;         /* Targets to be made */
114 time_t                  now;            /* Time at start of make */
115 GNode                   *DEFAULT;       /* .DEFAULT node */
116 Boolean                 allPrecious;    /* .PRECIOUS given on line by itself */
117
118 static Boolean          noBuiltins;     /* -r flag */
119 static Lst              makefiles;      /* ordered list of makefiles to read */
120 static Boolean          printVars;      /* print value of one or more vars */
121 static Boolean          expandVars;     /* fully expand printed variables */
122 static Lst              variables;      /* list of variables to print */
123 int                     maxJobs;        /* -j argument */
124 static Boolean          forceJobs;      /* -j argument given */
125 static int              maxLocal;       /* -L argument */
126 Boolean                 compatMake;     /* -B argument */
127 Boolean                 debug;          /* -d flag */
128 Boolean                 noExecute;      /* -n flag */
129 Boolean                 keepgoing;      /* -k flag */
130 Boolean                 queryFlag;      /* -q flag */
131 Boolean                 touchFlag;      /* -t flag */
132 Boolean                 usePipes;       /* !-P flag */
133 Boolean                 ignoreErrors;   /* -i flag */
134 Boolean                 beSilent;       /* -s flag */
135 Boolean                 beVerbose;      /* -v flag */
136 Boolean                 oldVars;        /* variable substitution style */
137 Boolean                 checkEnvFirst;  /* -e flag */
138 Lst                     envFirstVars;   /* (-E) vars to override from env */
139 static Boolean          jobsRunning;    /* TRUE if the jobs might be running */
140
141 static void             MainParseArgs(int, char **);
142 char *                  chdir_verify_path(char *, char *);
143 static int              ReadMakefile(ClientData, ClientData);
144 static void             usage(void);
145
146 static char *curdir;                    /* startup directory */
147 static char *objdir;                    /* where we chdir'ed to */
148
149 /*-
150  * MainParseArgs --
151  *      Parse a given argument vector. Called from main() and from
152  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
153  *
154  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
155  *
156  * Results:
157  *      None
158  *
159  * Side Effects:
160  *      Various global and local flags will be set depending on the flags
161  *      given
162  */
163 static void
164 MainParseArgs(argc, argv)
165         int argc;
166         char **argv;
167 {
168         extern int optind;
169         extern char *optarg;
170         char *p;
171         int c;
172
173         optind = 1;     /* since we're called more than once */
174 #ifdef REMOTE
175 # define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
176 #else
177 # define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
178 #endif
179 rearg:  while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
180                 switch(c) {
181                 case 'C':
182                         if (chdir(optarg) == -1)
183                                 err(1, "chdir %s", optarg);
184                         break;
185                 case 'D':
186                         Var_Set(optarg, "1", VAR_GLOBAL);
187                         Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
188                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
189                         break;
190                 case 'I':
191                         Parse_AddIncludeDir(optarg);
192                         Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
193                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
194                         break;
195                 case 'V':
196                         printVars = TRUE;
197                         (void)Lst_AtEnd(variables, (ClientData)optarg);
198                         Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
199                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
200                         break;
201                 case 'X':
202                         expandVars = FALSE;
203                         break;
204                 case 'B':
205                         compatMake = TRUE;
206                         Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
207                         break;
208 #ifdef REMOTE
209                 case 'L': {
210                         char *endptr;
211
212                         maxLocal = strtol(optarg, &endptr, 10);
213                         if (maxLocal < 0 || *endptr != '\0') {
214                                 warnx("illegal number, -L argument -- %s",
215                                     optarg);
216                                 usage();
217                         }
218                         Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
219                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
220                         break;
221                 }
222 #endif
223                 case 'P':
224                         usePipes = FALSE;
225                         Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
226                         break;
227                 case 'S':
228                         keepgoing = FALSE;
229                         Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
230                         break;
231                 case 'd': {
232                         char *modules = optarg;
233
234                         for (; *modules; ++modules)
235                                 switch (*modules) {
236                                 case 'A':
237                                         debug = ~0;
238                                         break;
239                                 case 'a':
240                                         debug |= DEBUG_ARCH;
241                                         break;
242                                 case 'c':
243                                         debug |= DEBUG_COND;
244                                         break;
245                                 case 'd':
246                                         debug |= DEBUG_DIR;
247                                         break;
248                                 case 'f':
249                                         debug |= DEBUG_FOR;
250                                         break;
251                                 case 'g':
252                                         if (modules[1] == '1') {
253                                                 debug |= DEBUG_GRAPH1;
254                                                 ++modules;
255                                         }
256                                         else if (modules[1] == '2') {
257                                                 debug |= DEBUG_GRAPH2;
258                                                 ++modules;
259                                         }
260                                         break;
261                                 case 'j':
262                                         debug |= DEBUG_JOB;
263                                         break;
264                                 case 'l':
265                                         debug |= DEBUG_LOUD;
266                                         break;
267                                 case 'm':
268                                         debug |= DEBUG_MAKE;
269                                         break;
270                                 case 's':
271                                         debug |= DEBUG_SUFF;
272                                         break;
273                                 case 't':
274                                         debug |= DEBUG_TARG;
275                                         break;
276                                 case 'v':
277                                         debug |= DEBUG_VAR;
278                                         break;
279                                 default:
280                                         warnx("illegal argument to d option -- %c", *modules);
281                                         usage();
282                                 }
283                         Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
284                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
285                         break;
286                 }
287                 case 'E':
288                         p = malloc(strlen(optarg) + 1);
289                         if (!p)
290                                 Punt("make: cannot allocate memory.");
291                         (void)strcpy(p, optarg);
292                         (void)Lst_AtEnd(envFirstVars, (ClientData)p);
293                         Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
294                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
295                         break;
296                 case 'e':
297                         checkEnvFirst = TRUE;
298                         Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
299                         break;
300                 case 'f':
301                         (void)Lst_AtEnd(makefiles, (ClientData)optarg);
302                         break;
303                 case 'i':
304                         ignoreErrors = TRUE;
305                         Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
306                         break;
307                 case 'j': {
308                         char *endptr;
309
310                         forceJobs = TRUE;
311                         maxJobs = strtol(optarg, &endptr, 10);
312                         if (maxJobs <= 0 || *endptr != '\0') {
313                                 warnx("illegal number, -j argument -- %s",
314                                     optarg);
315                                 usage();
316                         }
317 #ifndef REMOTE
318                         maxLocal = maxJobs;
319 #endif
320                         Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
321                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
322                         break;
323                 }
324                 case 'k':
325                         keepgoing = TRUE;
326                         Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
327                         break;
328                 case 'm':
329                         Dir_AddDir(sysIncPath, optarg);
330                         Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
331                         Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
332                         break;
333                 case 'n':
334                         noExecute = TRUE;
335                         Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
336                         break;
337                 case 'q':
338                         queryFlag = TRUE;
339                         /* Kind of nonsensical, wot? */
340                         Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
341                         break;
342                 case 'r':
343                         noBuiltins = TRUE;
344                         Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
345                         break;
346                 case 's':
347                         beSilent = TRUE;
348                         Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
349                         break;
350                 case 't':
351                         touchFlag = TRUE;
352                         Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
353                         break;
354                 case 'v':
355                         beVerbose = TRUE;
356                         Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
357                         break;
358                 default:
359                 case '?':
360                         usage();
361                 }
362         }
363
364         oldVars = TRUE;
365
366         /*
367          * See if the rest of the arguments are variable assignments and
368          * perform them if so. Else take them to be targets and stuff them
369          * on the end of the "create" list.
370          */
371         for (argv += optind, argc -= optind; *argv; ++argv, --argc)
372                 if (Parse_IsVar(*argv))
373                         Parse_DoVar(*argv, VAR_CMD);
374                 else {
375                         if (!**argv)
376                                 Punt("illegal (null) argument.");
377                         if (**argv == '-') {
378                                 if ((*argv)[1])
379                                         optind = 0;     /* -flag... */
380                                 else
381                                         optind = 1;     /* - */
382                                 goto rearg;
383                         }
384                         (void)Lst_AtEnd(create, (ClientData)estrdup(*argv));
385                 }
386 }
387
388 /*-
389  * Main_ParseArgLine --
390  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
391  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
392  *      Takes a line of arguments and breaks it into its
393  *      component words and passes those words and the number of them to the
394  *      MainParseArgs function.
395  *      The line should have all its leading whitespace removed.
396  *
397  * Results:
398  *      None
399  *
400  * Side Effects:
401  *      Only those that come from the various arguments.
402  */
403 void
404 Main_ParseArgLine(line)
405         char *line;                     /* Line to fracture */
406 {
407         char **argv;                    /* Manufactured argument vector */
408         int argc;                       /* Number of arguments in argv */
409
410         if (line == NULL)
411                 return;
412         for (; *line == ' '; ++line)
413                 continue;
414         if (!*line)
415                 return;
416
417         argv = brk_string(line, &argc, TRUE);
418         MainParseArgs(argc, argv);
419 }
420
421 char *
422 chdir_verify_path(path, obpath)
423         char *path;
424         char *obpath;
425 {
426         struct stat sb;
427
428         if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
429                 if (chdir(path)) {
430                         warn("warning: %s", path);
431                         return 0;
432                 }
433                 else {
434                         if (path[0] != '/') {
435                                 (void) snprintf(obpath, MAXPATHLEN, "%s/%s",
436                                                 curdir, path);
437                                 return obpath;
438                         }
439                         else
440                                 return path;
441                 }
442         }
443
444         return 0;
445 }
446
447
448 /*-
449  * main --
450  *      The main function, for obvious reasons. Initializes variables
451  *      and a few modules, then parses the arguments give it in the
452  *      environment and on the command line. Reads the system makefile
453  *      followed by either Makefile, makefile or the file given by the
454  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
455  *      flags it has received by then uses either the Make or the Compat
456  *      module to create the initial list of targets.
457  *
458  * Results:
459  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
460  *      0.
461  *
462  * Side Effects:
463  *      The program exits when done. Targets are created. etc. etc. etc.
464  */
465 int
466 main(argc, argv)
467         int argc;
468         char **argv;
469 {
470         Lst targs;      /* target nodes to create -- passed to Make_Init */
471         Boolean outOfDate = TRUE;       /* FALSE if all targets up to date */
472         struct stat sa;
473         char *p, *p1, *path, *pathp;
474 #ifdef WANT_ENV_PWD
475         struct stat sb;
476         char *pwd;
477 #endif
478         char mdpath[MAXPATHLEN + 1];
479         char obpath[MAXPATHLEN + 1];
480         char cdpath[MAXPATHLEN + 1];
481         char *machine = getenv("MACHINE");
482         char *machine_arch = getenv("MACHINE_ARCH");
483         char *machine_cpu = getenv("MACHINE_CPU");
484         Lst sysMkPath;                  /* Path of sys.mk */
485         char *cp = NULL, *start;
486                                         /* avoid faults on read-only strings */
487         static char syspath[] = _PATH_DEFSYSPATH;
488
489         {
490         /*
491          * Catch SIGCHLD so that we get kicked out of select() when we
492          * need to look at a child.  This is only known to matter for the
493          * -j case (perhaps without -P).
494          *
495          * XXX this is intentionally misplaced.
496          */
497         struct sigaction sa;
498
499         sigemptyset(&sa.sa_mask);
500         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
501         sa.sa_handler = catch_child;
502         sigaction(SIGCHLD, &sa, NULL);
503         }
504
505 #ifdef RLIMIT_NOFILE
506         /*
507          * get rid of resource limit on file descriptors
508          */
509         {
510                 struct rlimit rl;
511                 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
512                     rl.rlim_cur != rl.rlim_max) {
513                         rl.rlim_cur = rl.rlim_max;
514                         (void) setrlimit(RLIMIT_NOFILE, &rl);
515                 }
516         }
517 #endif
518         /*
519          * Find where we are and take care of PWD for the automounter...
520          * All this code is so that we know where we are when we start up
521          * on a different machine with pmake.
522          */
523         curdir = cdpath;
524         if (getcwd(curdir, MAXPATHLEN) == NULL)
525                 err(2, NULL);
526
527         if (stat(curdir, &sa) == -1)
528             err(2, "%s", curdir);
529
530 #ifdef WANT_ENV_PWD
531         if ((pwd = getenv("PWD")) != NULL) {
532             if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
533                 sa.st_dev == sb.st_dev)
534                 (void) strcpy(curdir, pwd);
535         }
536 #endif
537
538 #if defined(__i386__) && defined(__DragonFly_version)
539         /*
540          * PC-98 kernel sets the `i386' string to the utsname.machine and
541          * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
542          * we check machine.ispc98 and adjust the machine variable before
543          * using usname(3) below.
544          * NOTE: machdep.ispc98 was defined on 1998/8/31.
545          */
546         if (!machine) {
547                 int     ispc98;
548                 size_t  len;
549
550                 len = sizeof(ispc98);
551                 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
552                         if (ispc98)
553                                 machine = "pc98";
554                 }
555         }
556 #endif
557
558         /*
559          * Get the name of this type of MACHINE from utsname
560          * so we can share an executable for similar machines.
561          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
562          *
563          * Note that while MACHINE is decided at run-time,
564          * MACHINE_ARCH is always known at compile time.
565          */
566         if (!machine) {
567 #ifndef MACHINE
568             struct utsname utsname;
569
570             if (uname(&utsname) == -1)
571                     err(2, "uname");
572             machine = utsname.machine;
573 #else
574             machine = MACHINE;
575 #endif
576         }
577
578         if (!machine_arch) {
579 #ifndef MACHINE_ARCH
580                 machine_arch = "unknown";
581 #else
582                 machine_arch = MACHINE_ARCH;
583 #endif
584         }
585
586         /*
587          * Set machine_cpu to the minumum supported CPU revision based
588          * on the target architecture, if not already set.
589          */
590         if (!machine_cpu) {
591                 if (!strcmp(machine_arch, "i386"))
592                         machine_cpu = "i386";
593                 else if (!strcmp(machine_arch, "alpha"))
594                         machine_cpu = "ev4";
595                 else
596                         machine_cpu = "unknown";
597         }
598         
599         /*
600          * The object directory location is determined using the
601          * following order of preference:
602          *
603          *      1. MAKEOBJDIRPREFIX`cwd`
604          *      2. MAKEOBJDIR
605          *      3. _PATH_OBJDIR.${MACHINE}
606          *      4. _PATH_OBJDIR
607          *      5. _PATH_OBJDIRPREFIX`cwd`
608          *
609          * If one of the first two fails, use the current directory.
610          * If the remaining three all fail, use the current directory.
611          *
612          * Once things are initted,
613          * have to add the original directory to the search path,
614          * and modify the paths for the Makefiles apropriately.  The
615          * current directory is also placed as a variable for make scripts.
616          */
617         if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
618                 if (!(path = getenv("MAKEOBJDIR"))) {
619                         path = _PATH_OBJDIR;
620                         pathp = _PATH_OBJDIRPREFIX;
621                         (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
622                                         path, machine);
623                         if (!(objdir = chdir_verify_path(mdpath, obpath)))
624                                 if (!(objdir=chdir_verify_path(path, obpath))) {
625                                         (void) snprintf(mdpath, MAXPATHLEN,
626                                                         "%s%s", pathp, curdir);
627                                         if (!(objdir=chdir_verify_path(mdpath,
628                                                                        obpath)))
629                                                 objdir = curdir;
630                                 }
631                 }
632                 else if (!(objdir = chdir_verify_path(path, obpath)))
633                         objdir = curdir;
634         }
635         else {
636                 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
637                 if (!(objdir = chdir_verify_path(mdpath, obpath)))
638                         objdir = curdir;
639         }
640
641 #ifdef WANT_ENV_PWD
642         setenv("PWD", objdir, 1);
643 #endif
644
645         create = Lst_Init(FALSE);
646         makefiles = Lst_Init(FALSE);
647         envFirstVars = Lst_Init(FALSE);
648         printVars = FALSE;
649         expandVars = TRUE;
650         variables = Lst_Init(FALSE);
651         beSilent = FALSE;               /* Print commands as executed */
652         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
653         noExecute = FALSE;              /* Execute all commands */
654         keepgoing = FALSE;              /* Stop on error */
655         allPrecious = FALSE;            /* Remove targets when interrupted */
656         queryFlag = FALSE;              /* This is not just a check-run */
657         noBuiltins = FALSE;             /* Read the built-in rules */
658         touchFlag = FALSE;              /* Actually update targets */
659         usePipes = TRUE;                /* Catch child output in pipes */
660         debug = 0;                      /* No debug verbosity, please. */
661         jobsRunning = FALSE;
662
663         maxLocal = DEFMAXLOCAL;         /* Set default local max concurrency */
664 #ifdef REMOTE
665         maxJobs = DEFMAXJOBS;           /* Set default max concurrency */
666 #else
667         maxJobs = maxLocal;
668 #endif
669         forceJobs = FALSE;              /* No -j flag */
670         compatMake = FALSE;             /* No compat mode */
671
672
673         /*
674          * Initialize the parsing, directory and variable modules to prepare
675          * for the reading of inclusion paths and variable settings on the
676          * command line
677          */
678         Dir_Init();             /* Initialize directory structures so -I flags
679                                  * can be processed correctly */
680         Parse_Init();           /* Need to initialize the paths of #include
681                                  * directories */
682         Var_Init();             /* As well as the lists of variables for
683                                  * parsing arguments */
684         str_init();
685         if (objdir != curdir)
686                 Dir_AddDir(dirSearchPath, curdir);
687         Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
688         Var_Set(".CURDIR", curdir, VAR_GLOBAL);
689         Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
690
691         /*
692          * Initialize various variables.
693          *      MAKE also gets this name, for compatibility
694          *      .MAKEFLAGS gets set to the empty string just in case.
695          *      MFLAGS also gets initialized empty, for compatibility.
696          */
697         Var_Set("MAKE", argv[0], VAR_GLOBAL);
698         Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
699         Var_Set("MFLAGS", "", VAR_GLOBAL);
700         Var_Set("MACHINE", machine, VAR_GLOBAL);
701         Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
702         Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
703
704         /*
705          * First snag any flags out of the MAKE environment variable.
706          * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
707          * in a different format).
708          */
709 #ifdef POSIX
710         Main_ParseArgLine(getenv("MAKEFLAGS"));
711 #else
712         Main_ParseArgLine(getenv("MAKE"));
713 #endif
714
715         MainParseArgs(argc, argv);
716
717         /*
718          * Be compatible if user did not specify -j and did not explicitly
719          * turned compatibility on
720          */
721         if (!compatMake && !forceJobs)
722                 compatMake = TRUE;
723
724         /*
725          * Initialize archive, target and suffix modules in preparation for
726          * parsing the makefile(s)
727          */
728         Arch_Init();
729         Targ_Init();
730         Suff_Init();
731
732         DEFAULT = NILGNODE;
733         (void)time(&now);
734
735         /*
736          * Set up the .TARGETS variable to contain the list of targets to be
737          * created. If none specified, make the variable empty -- the parser
738          * will fill the thing in with the default or .MAIN target.
739          */
740         if (!Lst_IsEmpty(create)) {
741                 LstNode ln;
742
743                 for (ln = Lst_First(create); ln != NILLNODE;
744                     ln = Lst_Succ(ln)) {
745                         char *name = (char *)Lst_Datum(ln);
746
747                         Var_Append(".TARGETS", name, VAR_GLOBAL);
748                 }
749         } else
750                 Var_Set(".TARGETS", "", VAR_GLOBAL);
751
752
753         /*
754          * If no user-supplied system path was given (through the -m option)
755          * add the directories from the DEFSYSPATH (more than one may be given
756          * as dir1:...:dirn) to the system include path.
757          */
758         if (Lst_IsEmpty(sysIncPath)) {
759                 for (start = syspath; *start != '\0'; start = cp) {
760                         for (cp = start; *cp != '\0' && *cp != ':'; cp++)
761                                 continue;
762                         if (*cp == '\0') {
763                                 Dir_AddDir(sysIncPath, start);
764                         } else {
765                                 *cp++ = '\0';
766                                 Dir_AddDir(sysIncPath, start);
767                         }
768                 }
769         }
770
771         /*
772          * Read in the built-in rules first, followed by the specified
773          * makefile, if it was (makefile != (char *) NULL), or the default
774          * Makefile and makefile, in that order, if it wasn't.
775          */
776         if (!noBuiltins) {
777                 LstNode ln;
778
779                 sysMkPath = Lst_Init (FALSE);
780                 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
781                 if (Lst_IsEmpty(sysMkPath))
782                         Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
783                 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
784                 if (ln != NILLNODE)
785                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
786         }
787
788         if (!Lst_IsEmpty(makefiles)) {
789                 LstNode ln;
790
791                 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
792                 if (ln != NILLNODE)
793                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
794         } else if (!ReadMakefile("makefile", NULL))
795                 (void)ReadMakefile("Makefile", NULL);
796
797         (void)ReadMakefile(".depend", NULL);
798
799         Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
800         efree(p1);
801
802         /* Install all the flags into the MAKE envariable. */
803         if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
804 #ifdef POSIX
805                 setenv("MAKEFLAGS", p, 1);
806 #else
807                 setenv("MAKE", p, 1);
808 #endif
809         efree(p1);
810
811         /*
812          * For compatibility, look at the directories in the VPATH variable
813          * and add them to the search path, if the variable is defined. The
814          * variable's value is in the same format as the PATH envariable, i.e.
815          * <directory>:<directory>:<directory>...
816          */
817         if (Var_Exists("VPATH", VAR_CMD)) {
818                 char *vpath, *path, *cp, savec;
819                 /*
820                  * GCC stores string constants in read-only memory, but
821                  * Var_Subst will want to write this thing, so store it
822                  * in an array
823                  */
824                 static char VPATH[] = "${VPATH}";
825
826                 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
827                 path = vpath;
828                 do {
829                         /* skip to end of directory */
830                         for (cp = path; *cp != ':' && *cp != '\0'; cp++)
831                                 continue;
832                         /* Save terminator character so know when to stop */
833                         savec = *cp;
834                         *cp = '\0';
835                         /* Add directory to search path */
836                         Dir_AddDir(dirSearchPath, path);
837                         *cp = savec;
838                         path = cp + 1;
839                 } while (savec == ':');
840                 (void)free((Address)vpath);
841         }
842
843         /*
844          * Now that all search paths have been read for suffixes et al, it's
845          * time to add the default search path to their lists...
846          */
847         Suff_DoPaths();
848
849         /* print the initial graph, if the user requested it */
850         if (DEBUG(GRAPH1))
851                 Targ_PrintGraph(1);
852
853         /* print the values of any variables requested by the user */
854         if (printVars) {
855                 LstNode ln;
856
857                 for (ln = Lst_First(variables); ln != NILLNODE;
858                     ln = Lst_Succ(ln)) {
859                         char *value;
860                         if (expandVars) {
861                                 p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
862                                 if (!p1)
863                                         Punt("make: cannot allocate memory.");
864                                 /* This sprintf is safe, because of the malloc above */
865                                 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
866                                 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
867                         } else {
868                                 value = Var_Value((char *)Lst_Datum(ln),
869                                                   VAR_GLOBAL, &p1);
870                         }
871                         printf("%s\n", value ? value : "");
872                         if (p1)
873                                 free(p1);
874                 }
875         }
876
877         /*
878          * Have now read the entire graph and need to make a list of targets
879          * to create. If none was given on the command line, we consult the
880          * parsing module to find the main target(s) to create.
881          */
882         if (Lst_IsEmpty(create))
883                 targs = Parse_MainName();
884         else
885                 targs = Targ_FindList(create, TARG_CREATE);
886
887         if (!compatMake && !printVars) {
888                 /*
889                  * Initialize job module before traversing the graph, now that
890                  * any .BEGIN and .END targets have been read.  This is done
891                  * only if the -q flag wasn't given (to prevent the .BEGIN from
892                  * being executed should it exist).
893                  */
894                 if (!queryFlag) {
895                         if (maxLocal == -1)
896                                 maxLocal = maxJobs;
897                         Job_Init(maxJobs, maxLocal);
898                         jobsRunning = TRUE;
899                 }
900
901                 /* Traverse the graph, checking on all the targets */
902                 outOfDate = Make_Run(targs);
903         } else if (!printVars) {
904                 /*
905                  * Compat_Init will take care of creating all the targets as
906                  * well as initializing the module.
907                  */
908                 Compat_Run(targs);
909         }
910
911         Lst_Destroy(targs, NOFREE);
912         Lst_Destroy(variables, NOFREE);
913         Lst_Destroy(makefiles, NOFREE);
914         Lst_Destroy(create, (void (*)(ClientData)) free);
915
916         /* print the graph now it's been processed if the user requested it */
917         if (DEBUG(GRAPH2))
918                 Targ_PrintGraph(2);
919
920         Suff_End();
921         Targ_End();
922         Arch_End();
923         str_end();
924         Var_End();
925         Parse_End();
926         Dir_End();
927
928         if (queryFlag && outOfDate)
929                 return(1);
930         else
931                 return(0);
932 }
933
934 /*-
935  * ReadMakefile  --
936  *      Open and parse the given makefile.
937  *
938  * Results:
939  *      TRUE if ok. FALSE if couldn't open file.
940  *
941  * Side Effects:
942  *      lots
943  */
944 static Boolean
945 ReadMakefile(p, q)
946         ClientData p, q;
947 {
948         char *fname = p;                /* makefile to read */
949         extern Lst parseIncPath;
950         FILE *stream;
951         char *name, path[MAXPATHLEN + 1];
952         char *MAKEFILE;
953         int setMAKEFILE;
954
955         if (!strcmp(fname, "-")) {
956                 Parse_File("(stdin)", stdin);
957                 Var_Set("MAKEFILE", "", VAR_GLOBAL);
958         } else {
959                 setMAKEFILE = strcmp(fname, ".depend");
960
961                 /* if we've chdir'd, rebuild the path name */
962                 if (curdir != objdir && *fname != '/') {
963                         (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
964                         /*
965                          * XXX The realpath stuff breaks relative includes
966                          * XXX in some cases.   The problem likely is in
967                          * XXX parse.c where it does special things in
968                          * XXX ParseDoInclude if the file is relateive
969                          * XXX or absolute and not a system file.  There
970                          * XXX it assumes that if the current file that's
971                          * XXX being included is absolute, that any files
972                          * XXX that it includes shouldn't do the -I path
973                          * XXX stuff, which is inconsistant with historical
974                          * XXX behavior.  However, I can't pentrate the mists
975                          * XXX further, so I'm putting this workaround in
976                          * XXX here until such time as the underlying bug
977                          * XXX can be fixed.
978                          */
979 #if THIS_BREAKS_THINGS
980                         if (realpath(path, path) != NULL &&
981                             (stream = fopen(path, "r")) != NULL) {
982                                 MAKEFILE = fname;
983                                 fname = path;
984                                 goto found;
985                         }
986                 } else if (realpath(fname, path) != NULL) {
987                         MAKEFILE = fname;
988                         fname = path;
989                         if ((stream = fopen(fname, "r")) != NULL)
990                                 goto found;
991                 }
992 #else
993                         if ((stream = fopen(path, "r")) != NULL) {
994                                 MAKEFILE = fname;
995                                 fname = path;
996                                 goto found;
997                         }
998                 } else {
999                         MAKEFILE = fname;
1000                         if ((stream = fopen(fname, "r")) != NULL)
1001                                 goto found;
1002                 }
1003 #endif
1004                 /* look in -I and system include directories. */
1005                 name = Dir_FindFile(fname, parseIncPath);
1006                 if (!name)
1007                         name = Dir_FindFile(fname, sysIncPath);
1008                 if (!name || !(stream = fopen(name, "r")))
1009                         return(FALSE);
1010                 MAKEFILE = fname = name;
1011                 /*
1012                  * set the MAKEFILE variable desired by System V fans -- the
1013                  * placement of the setting here means it gets set to the last
1014                  * makefile specified, as it is set by SysV make.
1015                  */
1016 found:
1017                 if (setMAKEFILE)
1018                         Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1019                 Parse_File(fname, stream);
1020                 (void)fclose(stream);
1021         }
1022         return(TRUE);
1023 }
1024
1025 /*-
1026  * Cmd_Exec --
1027  *      Execute the command in cmd, and return the output of that command
1028  *      in a string.
1029  *
1030  * Results:
1031  *      A string containing the output of the command, or the empty string
1032  *      If err is not NULL, it contains the reason for the command failure
1033  *
1034  * Side Effects:
1035  *      The string must be freed by the caller.
1036  */
1037 char *
1038 Cmd_Exec(cmd, err)
1039     char *cmd;
1040     char **err;
1041 {
1042     char        *args[4];       /* Args for invoking the shell */
1043     int         fds[2];         /* Pipe streams */
1044     int         cpid;           /* Child PID */
1045     int         pid;            /* PID from wait() */
1046     char        *res;           /* result */
1047     int         status;         /* command exit status */
1048     Buffer      buf;            /* buffer to store the result */
1049     char        *cp;
1050     int         cc;
1051
1052
1053     *err = NULL;
1054
1055     /*
1056      * Set up arguments for shell
1057      */
1058     args[0] = "sh";
1059     args[1] = "-c";
1060     args[2] = cmd;
1061     args[3] = NULL;
1062
1063     /*
1064      * Open a pipe for fetching its output
1065      */
1066     if (pipe(fds) == -1) {
1067         *err = "Couldn't create pipe for \"%s\"";
1068         goto bad;
1069     }
1070
1071     /*
1072      * Fork
1073      */
1074     switch (cpid = vfork()) {
1075     case 0:
1076         /*
1077          * Close input side of pipe
1078          */
1079         (void) close(fds[0]);
1080
1081         /*
1082          * Duplicate the output stream to the shell's output, then
1083          * shut the extra thing down. Note we don't fetch the error
1084          * stream...why not? Why?
1085          */
1086         (void) dup2(fds[1], 1);
1087         (void) close(fds[1]);
1088
1089         (void) execv("/bin/sh", args);
1090         _exit(1);
1091         /*NOTREACHED*/
1092
1093     case -1:
1094         *err = "Couldn't exec \"%s\"";
1095         goto bad;
1096
1097     default:
1098         /*
1099          * No need for the writing half
1100          */
1101         (void) close(fds[1]);
1102
1103         buf = Buf_Init (MAKE_BSIZE);
1104
1105         do {
1106             char   result[BUFSIZ];
1107             cc = read(fds[0], result, sizeof(result));
1108             if (cc > 0)
1109                 Buf_AddBytes(buf, cc, (Byte *) result);
1110         }
1111         while (cc > 0 || (cc == -1 && errno == EINTR));
1112
1113         /*
1114          * Close the input side of the pipe.
1115          */
1116         (void) close(fds[0]);
1117
1118         /*
1119          * Wait for the process to exit.
1120          */
1121         while(((pid = wait(&status)) != cpid) && (pid >= 0))
1122             continue;
1123
1124         if (cc == -1)
1125             *err = "Error reading shell's output for \"%s\"";
1126
1127         res = (char *)Buf_GetAll (buf, &cc);
1128         Buf_Destroy (buf, FALSE);
1129
1130         if (status)
1131             *err = "\"%s\" returned non-zero status";
1132
1133         /*
1134          * Null-terminate the result, convert newlines to spaces and
1135          * install it in the variable.
1136          */
1137         res[cc] = '\0';
1138         cp = &res[cc] - 1;
1139
1140         if (*cp == '\n') {
1141             /*
1142              * A final newline is just stripped
1143              */
1144             *cp-- = '\0';
1145         }
1146         while (cp >= res) {
1147             if (*cp == '\n') {
1148                 *cp = ' ';
1149             }
1150             cp--;
1151         }
1152         break;
1153     }
1154     return res;
1155 bad:
1156     res = emalloc(1);
1157     *res = '\0';
1158     return res;
1159 }
1160
1161 /*-
1162  * Error --
1163  *      Print an error message given its format.
1164  *
1165  * Results:
1166  *      None.
1167  *
1168  * Side Effects:
1169  *      The message is printed.
1170  */
1171 /* VARARGS */
1172 void
1173 #ifdef __STDC__
1174 Error(char *fmt, ...)
1175 #else
1176 Error(va_alist)
1177         va_dcl
1178 #endif
1179 {
1180         va_list ap;
1181 #ifdef __STDC__
1182         va_start(ap, fmt);
1183 #else
1184         char *fmt;
1185
1186         va_start(ap);
1187         fmt = va_arg(ap, char *);
1188 #endif
1189         (void)vfprintf(stderr, fmt, ap);
1190         va_end(ap);
1191         (void)fprintf(stderr, "\n");
1192         (void)fflush(stderr);
1193 }
1194
1195 /*-
1196  * Fatal --
1197  *      Produce a Fatal error message. If jobs are running, waits for them
1198  *      to finish.
1199  *
1200  * Results:
1201  *      None
1202  *
1203  * Side Effects:
1204  *      The program exits
1205  */
1206 /* VARARGS */
1207 void
1208 #ifdef __STDC__
1209 Fatal(char *fmt, ...)
1210 #else
1211 Fatal(va_alist)
1212         va_dcl
1213 #endif
1214 {
1215         va_list ap;
1216 #ifdef __STDC__
1217         va_start(ap, fmt);
1218 #else
1219         char *fmt;
1220
1221         va_start(ap);
1222         fmt = va_arg(ap, char *);
1223 #endif
1224         if (jobsRunning)
1225                 Job_Wait();
1226
1227         (void)vfprintf(stderr, fmt, ap);
1228         va_end(ap);
1229         (void)fprintf(stderr, "\n");
1230         (void)fflush(stderr);
1231
1232         if (DEBUG(GRAPH2))
1233                 Targ_PrintGraph(2);
1234         exit(2);                /* Not 1 so -q can distinguish error */
1235 }
1236
1237 /*
1238  * Punt --
1239  *      Major exception once jobs are being created. Kills all jobs, prints
1240  *      a message and exits.
1241  *
1242  * Results:
1243  *      None
1244  *
1245  * Side Effects:
1246  *      All children are killed indiscriminately and the program Lib_Exits
1247  */
1248 /* VARARGS */
1249 void
1250 #ifdef __STDC__
1251 Punt(char *fmt, ...)
1252 #else
1253 Punt(va_alist)
1254         va_dcl
1255 #endif
1256 {
1257         va_list ap;
1258 #if __STDC__
1259         va_start(ap, fmt);
1260 #else
1261         char *fmt;
1262
1263         va_start(ap);
1264         fmt = va_arg(ap, char *);
1265 #endif
1266
1267         (void)fprintf(stderr, "make: ");
1268         (void)vfprintf(stderr, fmt, ap);
1269         va_end(ap);
1270         (void)fprintf(stderr, "\n");
1271         (void)fflush(stderr);
1272
1273         DieHorribly();
1274 }
1275
1276 /*-
1277  * DieHorribly --
1278  *      Exit without giving a message.
1279  *
1280  * Results:
1281  *      None
1282  *
1283  * Side Effects:
1284  *      A big one...
1285  */
1286 void
1287 DieHorribly()
1288 {
1289         if (jobsRunning)
1290                 Job_AbortAll();
1291         if (DEBUG(GRAPH2))
1292                 Targ_PrintGraph(2);
1293         exit(2);                /* Not 1, so -q can distinguish error */
1294 }
1295
1296 /*
1297  * Finish --
1298  *      Called when aborting due to errors in child shell to signal
1299  *      abnormal exit.
1300  *
1301  * Results:
1302  *      None
1303  *
1304  * Side Effects:
1305  *      The program exits
1306  */
1307 void
1308 Finish(errors)
1309         int errors;     /* number of errors encountered in Make_Make */
1310 {
1311         Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1312 }
1313
1314 /*
1315  * emalloc --
1316  *      malloc, but die on error.
1317  */
1318 void *
1319 emalloc(len)
1320         size_t len;
1321 {
1322         void *p;
1323
1324         if ((p = malloc(len)) == NULL)
1325                 enomem();
1326         return(p);
1327 }
1328
1329 /*
1330  * estrdup --
1331  *      strdup, but die on error.
1332  */
1333 char *
1334 estrdup(str)
1335         const char *str;
1336 {
1337         char *p;
1338
1339         if ((p = strdup(str)) == NULL)
1340                 enomem();
1341         return(p);
1342 }
1343
1344 /*
1345  * erealloc --
1346  *      realloc, but die on error.
1347  */
1348 void *
1349 erealloc(ptr, size)
1350         void *ptr;
1351         size_t size;
1352 {
1353         if ((ptr = realloc(ptr, size)) == NULL)
1354                 enomem();
1355         return(ptr);
1356 }
1357
1358 /*
1359  * enomem --
1360  *      die when out of memory.
1361  */
1362 void
1363 enomem()
1364 {
1365         err(2, NULL);
1366 }
1367
1368 /*
1369  * enunlink --
1370  *      Remove a file carefully, avoiding directories.
1371  */
1372 int
1373 eunlink(file)
1374         const char *file;
1375 {
1376         struct stat st;
1377
1378         if (lstat(file, &st) == -1)
1379                 return -1;
1380
1381         if (S_ISDIR(st.st_mode)) {
1382                 errno = EISDIR;
1383                 return -1;
1384         }
1385         return unlink(file);
1386 }
1387
1388 /*
1389  * usage --
1390  *      exit with usage message
1391  */
1392 static void
1393 usage()
1394 {
1395         (void)fprintf(stderr, "%s\n%s\n%s\n",
1396 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1397 "            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1398 "            [-m directory] [-V variable] [variable=value] [target ...]");
1399         exit(2);
1400 }
1401
1402
1403 int
1404 PrintAddr(a, b)
1405     ClientData a;
1406     ClientData b;
1407 {
1408     printf("%lx ", (unsigned long) a);
1409     return b ? 0 : 0;
1410 }