Make the DEBUGF() macro portable by (ugh) adding a Debug() function, which
[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.12 2004/11/12 22:42:36 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(void *, void *);
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, (void *)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, (void *)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, (void *)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, (void *)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 = NULL;
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 != NULL;
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, (void *)NULL, ReadMakefile);
784                 if (ln != NULL)
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, (void *)NULL, ReadMakefile);
792                 if (ln != NULL)
793                         Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
794         } else if (!ReadMakefile("BSDmakefile", NULL))
795             if (!ReadMakefile("makefile", NULL))
796                 (void)ReadMakefile("Makefile", NULL);
797
798         (void)ReadMakefile(".depend", NULL);
799
800         Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
801         free(p1);
802
803         /* Install all the flags into the MAKE envariable. */
804         if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
805 #ifdef POSIX
806                 setenv("MAKEFLAGS", p, 1);
807 #else
808                 setenv("MAKE", p, 1);
809 #endif
810         free(p1);
811
812         /*
813          * For compatibility, look at the directories in the VPATH variable
814          * and add them to the search path, if the variable is defined. The
815          * variable's value is in the same format as the PATH envariable, i.e.
816          * <directory>:<directory>:<directory>...
817          */
818         if (Var_Exists("VPATH", VAR_CMD)) {
819                 char *vpath, *path, *cp, savec;
820                 /*
821                  * GCC stores string constants in read-only memory, but
822                  * Var_Subst will want to write this thing, so store it
823                  * in an array
824                  */
825                 static char VPATH[] = "${VPATH}";
826
827                 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
828                 path = vpath;
829                 do {
830                         /* skip to end of directory */
831                         for (cp = path; *cp != ':' && *cp != '\0'; cp++)
832                                 continue;
833                         /* Save terminator character so know when to stop */
834                         savec = *cp;
835                         *cp = '\0';
836                         /* Add directory to search path */
837                         Dir_AddDir(dirSearchPath, path);
838                         *cp = savec;
839                         path = cp + 1;
840                 } while (savec == ':');
841                 (void)free(vpath);
842         }
843
844         /*
845          * Now that all search paths have been read for suffixes et al, it's
846          * time to add the default search path to their lists...
847          */
848         Suff_DoPaths();
849
850         /* print the initial graph, if the user requested it */
851         if (DEBUG(GRAPH1))
852                 Targ_PrintGraph(1);
853
854         /* print the values of any variables requested by the user */
855         if (printVars) {
856                 LstNode ln;
857
858                 for (ln = Lst_First(variables); ln != NULL;
859                     ln = Lst_Succ(ln)) {
860                         char *value;
861                         if (expandVars) {
862                                 p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
863                                 if (!p1)
864                                         Punt("make: cannot allocate memory.");
865                                 /* This sprintf is safe, because of the malloc above */
866                                 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
867                                 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
868                         } else {
869                                 value = Var_Value((char *)Lst_Datum(ln),
870                                                   VAR_GLOBAL, &p1);
871                         }
872                         printf("%s\n", value ? value : "");
873                         if (p1)
874                                 free(p1);
875                 }
876         }
877
878         /*
879          * Have now read the entire graph and need to make a list of targets
880          * to create. If none was given on the command line, we consult the
881          * parsing module to find the main target(s) to create.
882          */
883         if (Lst_IsEmpty(create))
884                 targs = Parse_MainName();
885         else
886                 targs = Targ_FindList(create, TARG_CREATE);
887
888         if (!compatMake && !printVars) {
889                 /*
890                  * Initialize job module before traversing the graph, now that
891                  * any .BEGIN and .END targets have been read.  This is done
892                  * only if the -q flag wasn't given (to prevent the .BEGIN from
893                  * being executed should it exist).
894                  */
895                 if (!queryFlag) {
896                         if (maxLocal == -1)
897                                 maxLocal = maxJobs;
898                         Job_Init(maxJobs, maxLocal);
899                         jobsRunning = TRUE;
900                 }
901
902                 /* Traverse the graph, checking on all the targets */
903                 outOfDate = Make_Run(targs);
904         } else if (!printVars) {
905                 /*
906                  * Compat_Init will take care of creating all the targets as
907                  * well as initializing the module.
908                  */
909                 Compat_Run(targs);
910         }
911
912         Lst_Destroy(targs, NOFREE);
913         Lst_Destroy(variables, NOFREE);
914         Lst_Destroy(makefiles, NOFREE);
915         Lst_Destroy(create, (void (*) (void *)) free);
916
917         /* print the graph now it's been processed if the user requested it */
918         if (DEBUG(GRAPH2))
919                 Targ_PrintGraph(2);
920
921         Suff_End();
922         Targ_End();
923         Arch_End();
924         str_end();
925         Var_End();
926         Parse_End();
927         Dir_End();
928
929         if (queryFlag && outOfDate)
930                 return(1);
931         else
932                 return(0);
933 }
934
935 /*-
936  * ReadMakefile  --
937  *      Open and parse the given makefile.
938  *
939  * Results:
940  *      TRUE if ok. FALSE if couldn't open file.
941  *
942  * Side Effects:
943  *      lots
944  */
945 static Boolean
946 ReadMakefile(p, q)
947         void *p;
948         void *q __unused;
949 {
950         char *fname = p;                /* makefile to read */
951         extern Lst parseIncPath;
952         FILE *stream;
953         char *name, path[MAXPATHLEN + 1];
954         char *MAKEFILE;
955         int setMAKEFILE;
956
957         if (!strcmp(fname, "-")) {
958                 Parse_File("(stdin)", stdin);
959                 Var_Set("MAKEFILE", "", VAR_GLOBAL);
960         } else {
961                 setMAKEFILE = strcmp(fname, ".depend");
962
963                 /* if we've chdir'd, rebuild the path name */
964                 if (curdir != objdir && *fname != '/') {
965                         (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
966                         /*
967                          * XXX The realpath stuff breaks relative includes
968                          * XXX in some cases.   The problem likely is in
969                          * XXX parse.c where it does special things in
970                          * XXX ParseDoInclude if the file is relateive
971                          * XXX or absolute and not a system file.  There
972                          * XXX it assumes that if the current file that's
973                          * XXX being included is absolute, that any files
974                          * XXX that it includes shouldn't do the -I path
975                          * XXX stuff, which is inconsistant with historical
976                          * XXX behavior.  However, I can't pentrate the mists
977                          * XXX further, so I'm putting this workaround in
978                          * XXX here until such time as the underlying bug
979                          * XXX can be fixed.
980                          */
981 #if THIS_BREAKS_THINGS
982                         if (realpath(path, path) != NULL &&
983                             (stream = fopen(path, "r")) != NULL) {
984                                 MAKEFILE = fname;
985                                 fname = path;
986                                 goto found;
987                         }
988                 } else if (realpath(fname, path) != NULL) {
989                         MAKEFILE = fname;
990                         fname = path;
991                         if ((stream = fopen(fname, "r")) != NULL)
992                                 goto found;
993                 }
994 #else
995                         if ((stream = fopen(path, "r")) != NULL) {
996                                 MAKEFILE = fname;
997                                 fname = path;
998                                 goto found;
999                         }
1000                 } else {
1001                         MAKEFILE = fname;
1002                         if ((stream = fopen(fname, "r")) != NULL)
1003                                 goto found;
1004                 }
1005 #endif
1006                 /* look in -I and system include directories. */
1007                 name = Dir_FindFile(fname, parseIncPath);
1008                 if (!name)
1009                         name = Dir_FindFile(fname, sysIncPath);
1010                 if (!name || !(stream = fopen(name, "r")))
1011                         return(FALSE);
1012                 MAKEFILE = fname = name;
1013                 /*
1014                  * set the MAKEFILE variable desired by System V fans -- the
1015                  * placement of the setting here means it gets set to the last
1016                  * makefile specified, as it is set by SysV make.
1017                  */
1018 found:
1019                 if (setMAKEFILE)
1020                         Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1021                 Parse_File(fname, stream);
1022                 (void)fclose(stream);
1023         }
1024         return(TRUE);
1025 }
1026
1027 /*-
1028  * Cmd_Exec --
1029  *      Execute the command in cmd, and return the output of that command
1030  *      in a string.
1031  *
1032  * Results:
1033  *      A string containing the output of the command, or the empty string
1034  *      If err is not NULL, it contains the reason for the command failure
1035  *
1036  * Side Effects:
1037  *      The string must be freed by the caller.
1038  */
1039 char *
1040 Cmd_Exec(cmd, err)
1041     char *cmd;
1042     char **err;
1043 {
1044     char        *args[4];       /* Args for invoking the shell */
1045     int         fds[2];         /* Pipe streams */
1046     int         cpid;           /* Child PID */
1047     int         pid;            /* PID from wait() */
1048     char        *res;           /* result */
1049     int         status;         /* command exit status */
1050     Buffer      buf;            /* buffer to store the result */
1051     char        *cp;
1052     int         cc;
1053
1054
1055     *err = NULL;
1056
1057     /*
1058      * Set up arguments for shell
1059      */
1060     args[0] = "sh";
1061     args[1] = "-c";
1062     args[2] = cmd;
1063     args[3] = NULL;
1064
1065     /*
1066      * Open a pipe for fetching its output
1067      */
1068     if (pipe(fds) == -1) {
1069         *err = "Couldn't create pipe for \"%s\"";
1070         goto bad;
1071     }
1072
1073     /*
1074      * Fork
1075      */
1076     switch (cpid = vfork()) {
1077     case 0:
1078         /*
1079          * Close input side of pipe
1080          */
1081         (void) close(fds[0]);
1082
1083         /*
1084          * Duplicate the output stream to the shell's output, then
1085          * shut the extra thing down. Note we don't fetch the error
1086          * stream...why not? Why?
1087          */
1088         (void) dup2(fds[1], 1);
1089         (void) close(fds[1]);
1090
1091         (void) execv("/bin/sh", args);
1092         _exit(1);
1093         /*NOTREACHED*/
1094
1095     case -1:
1096         *err = "Couldn't exec \"%s\"";
1097         goto bad;
1098
1099     default:
1100         /*
1101          * No need for the writing half
1102          */
1103         (void) close(fds[1]);
1104
1105         buf = Buf_Init (MAKE_BSIZE);
1106
1107         do {
1108             char   result[BUFSIZ];
1109             cc = read(fds[0], result, sizeof(result));
1110             if (cc > 0)
1111                 Buf_AddBytes(buf, cc, (Byte *) result);
1112         }
1113         while (cc > 0 || (cc == -1 && errno == EINTR));
1114
1115         /*
1116          * Close the input side of the pipe.
1117          */
1118         (void) close(fds[0]);
1119
1120         /*
1121          * Wait for the process to exit.
1122          */
1123         while(((pid = wait(&status)) != cpid) && (pid >= 0))
1124             continue;
1125
1126         if (cc == -1)
1127             *err = "Error reading shell's output for \"%s\"";
1128
1129         res = (char *)Buf_GetAll (buf, &cc);
1130         Buf_Destroy (buf, FALSE);
1131
1132         if (status)
1133             *err = "\"%s\" returned non-zero status";
1134
1135         /*
1136          * Null-terminate the result, convert newlines to spaces and
1137          * install it in the variable.
1138          */
1139         res[cc] = '\0';
1140         cp = &res[cc] - 1;
1141
1142         if (*cp == '\n') {
1143             /*
1144              * A final newline is just stripped
1145              */
1146             *cp-- = '\0';
1147         }
1148         while (cp >= res) {
1149             if (*cp == '\n') {
1150                 *cp = ' ';
1151             }
1152             cp--;
1153         }
1154         break;
1155     }
1156     return res;
1157 bad:
1158     res = emalloc(1);
1159     *res = '\0';
1160     return res;
1161 }
1162  
1163 /*-
1164  * Debug --
1165  *      Print a debugging message given its format.
1166  *
1167  * Results:
1168  *      None.
1169  *
1170  * Side Effects:
1171  *      The message is printed.
1172  */
1173 /* VARARGS */
1174 void
1175 Debug(const char *fmt, ...)
1176 {
1177         va_list ap;
1178
1179         va_start(ap, fmt);
1180         (void)vfprintf(stderr, fmt, ap);
1181         va_end(ap);
1182         (void)fflush(stderr);
1183 }
1184
1185 /*-
1186  * Error --
1187  *      Print an error message given its format.
1188  *
1189  * Results:
1190  *      None.
1191  *
1192  * Side Effects:
1193  *      The message is printed.
1194  */
1195 /* VARARGS */
1196 void
1197 Error(const char *fmt, ...)
1198 {
1199         va_list ap;
1200         va_start(ap, fmt);
1201         (void)vfprintf(stderr, fmt, ap);
1202         va_end(ap);
1203         (void)fprintf(stderr, "\n");
1204         (void)fflush(stderr);
1205 }
1206
1207 /*-
1208  * Fatal --
1209  *      Produce a Fatal error message. If jobs are running, waits for them
1210  *      to finish.
1211  *
1212  * Results:
1213  *      None
1214  *
1215  * Side Effects:
1216  *      The program exits
1217  */
1218 /* VARARGS */
1219 void
1220 Fatal(const char *fmt, ...)
1221 {
1222         va_list ap;
1223         va_start(ap, fmt);
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 Punt(const char *fmt, ...)
1251 {
1252         va_list ap;
1253         va_start(ap, fmt);
1254
1255         (void)fprintf(stderr, "make: ");
1256         (void)vfprintf(stderr, fmt, ap);
1257         va_end(ap);
1258         (void)fprintf(stderr, "\n");
1259         (void)fflush(stderr);
1260
1261         DieHorribly();
1262 }
1263
1264 /*-
1265  * DieHorribly --
1266  *      Exit without giving a message.
1267  *
1268  * Results:
1269  *      None
1270  *
1271  * Side Effects:
1272  *      A big one...
1273  */
1274 void
1275 DieHorribly()
1276 {
1277         if (jobsRunning)
1278                 Job_AbortAll();
1279         if (DEBUG(GRAPH2))
1280                 Targ_PrintGraph(2);
1281         exit(2);                /* Not 1, so -q can distinguish error */
1282 }
1283
1284 /*
1285  * Finish --
1286  *      Called when aborting due to errors in child shell to signal
1287  *      abnormal exit.
1288  *
1289  * Results:
1290  *      None
1291  *
1292  * Side Effects:
1293  *      The program exits
1294  */
1295 void
1296 Finish(errors)
1297         int errors;     /* number of errors encountered in Make_Make */
1298 {
1299         Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1300 }
1301
1302 /*
1303  * emalloc --
1304  *      malloc, but die on error.
1305  */
1306 void *
1307 emalloc(len)
1308         size_t len;
1309 {
1310         void *p;
1311
1312         if ((p = malloc(len)) == NULL)
1313                 enomem();
1314         return(p);
1315 }
1316
1317 /*
1318  * estrdup --
1319  *      strdup, but die on error.
1320  */
1321 char *
1322 estrdup(str)
1323         const char *str;
1324 {
1325         char *p;
1326
1327         if ((p = strdup(str)) == NULL)
1328                 enomem();
1329         return(p);
1330 }
1331
1332 /*
1333  * erealloc --
1334  *      realloc, but die on error.
1335  */
1336 void *
1337 erealloc(ptr, size)
1338         void *ptr;
1339         size_t size;
1340 {
1341         if ((ptr = realloc(ptr, size)) == NULL)
1342                 enomem();
1343         return(ptr);
1344 }
1345
1346 /*
1347  * enomem --
1348  *      die when out of memory.
1349  */
1350 void
1351 enomem()
1352 {
1353         err(2, NULL);
1354 }
1355
1356 /*
1357  * enunlink --
1358  *      Remove a file carefully, avoiding directories.
1359  */
1360 int
1361 eunlink(file)
1362         const char *file;
1363 {
1364         struct stat st;
1365
1366         if (lstat(file, &st) == -1)
1367                 return -1;
1368
1369         if (S_ISDIR(st.st_mode)) {
1370                 errno = EISDIR;
1371                 return -1;
1372         }
1373         return unlink(file);
1374 }
1375
1376 /*
1377  * usage --
1378  *      exit with usage message
1379  */
1380 static void
1381 usage()
1382 {
1383         (void)fprintf(stderr, "%s\n%s\n%s\n",
1384 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1385 "            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1386 "            [-m directory] [-V variable] [variable=value] [target ...]");
1387         exit(2);
1388 }
1389
1390
1391 int
1392 PrintAddr(a, b)
1393     void * a;
1394     void * b;
1395 {
1396     printf("%lx ", (unsigned long) a);
1397     return b ? 0 : 0;
1398 }