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