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