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