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