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
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
38 * @(#) Copyright (c) 1988, 1989, 1990, 1993 The Regents of the University of California. All rights reserved.
39 * @(#)main.c 8.3 (Berkeley) 3/19/94
40 * $FreeBSD: src/usr.bin/make/main.c,v 1.35.2.9 2003/04/15 14:37:35 ru Exp $
41 * $DragonFly: src/usr.bin/make/main.c,v 1.5 2004/01/29 22:40:36 dillon Exp $
46 * The main file for this entire program. Exit routines etc
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
55 * Error Print a tagged error message. The global
56 * MAKE variable must have been defined. This
57 * takes a format string and two optional
60 * Fatal Print an error message and exit. Also takes
61 * a format string and two arguments.
63 * Punt Aborts all jobs and exits with a message. Also
64 * takes a format string and two arguments.
66 * Finish Finish things up by printing the number of
67 * errors which occured, as passed to it, and
71 #include <sys/types.h>
73 #include <sys/param.h>
74 #include <sys/resource.h>
75 #include <sys/signal.h>
78 #include <sys/sysctl.h>
81 #include <sys/utsname.h>
99 #include "pathnames.h"
102 #define DEFMAXLOCAL DEFMAXJOBS
103 #endif /* DEFMAXLOCAL */
105 #define MAKEFLAGS ".MAKEFLAGS"
107 Lst create; /* Targets to be made */
108 time_t now; /* Time at start of make */
109 GNode *DEFAULT; /* .DEFAULT node */
110 Boolean allPrecious; /* .PRECIOUS given on line by itself */
112 static Boolean noBuiltins; /* -r flag */
113 static Lst makefiles; /* ordered list of makefiles to read */
114 static Boolean printVars; /* print value of one or more vars */
115 static Boolean expandVars; /* fully expand printed variables */
116 static Lst variables; /* list of variables to print */
117 int maxJobs; /* -j argument */
118 static Boolean forceJobs; /* -j argument given */
119 static int maxLocal; /* -L argument */
120 Boolean compatMake; /* -B argument */
121 Boolean debug; /* -d flag */
122 Boolean noExecute; /* -n flag */
123 Boolean keepgoing; /* -k flag */
124 Boolean queryFlag; /* -q flag */
125 Boolean touchFlag; /* -t flag */
126 Boolean usePipes; /* !-P flag */
127 Boolean ignoreErrors; /* -i flag */
128 Boolean beSilent; /* -s flag */
129 Boolean beVerbose; /* -v flag */
130 Boolean oldVars; /* variable substitution style */
131 Boolean checkEnvFirst; /* -e flag */
132 Lst envFirstVars; /* (-E) vars to override from env */
133 static Boolean jobsRunning; /* TRUE if the jobs might be running */
135 static void MainParseArgs(int, char **);
136 char * chdir_verify_path(char *, char *);
137 static int ReadMakefile(ClientData, ClientData);
138 static void usage(void);
140 static char *curdir; /* startup directory */
141 static char *objdir; /* where we chdir'ed to */
145 * Parse a given argument vector. Called from main() and from
146 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
148 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
154 * Various global and local flags will be set depending on the flags
158 MainParseArgs(argc, argv)
167 optind = 1; /* since we're called more than once */
169 # define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
171 # define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
173 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
176 if (chdir(optarg) == -1)
177 err(1, "chdir %s", optarg);
180 Var_Set(optarg, "1", VAR_GLOBAL);
181 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
182 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
185 Parse_AddIncludeDir(optarg);
186 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
187 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
191 (void)Lst_AtEnd(variables, (ClientData)optarg);
192 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
193 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
200 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
206 maxLocal = strtol(optarg, &endptr, 10);
207 if (maxLocal < 0 || *endptr != '\0') {
208 warnx("illegal number, -L argument -- %s",
212 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
213 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
219 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
223 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
226 char *modules = optarg;
228 for (; *modules; ++modules)
246 if (modules[1] == '1') {
247 debug |= DEBUG_GRAPH1;
250 else if (modules[1] == '2') {
251 debug |= DEBUG_GRAPH2;
274 warnx("illegal argument to d option -- %c", *modules);
277 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
278 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
282 p = malloc(strlen(optarg) + 1);
284 Punt("make: cannot allocate memory.");
285 (void)strcpy(p, optarg);
286 (void)Lst_AtEnd(envFirstVars, (ClientData)p);
287 Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
288 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
291 checkEnvFirst = TRUE;
292 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
295 (void)Lst_AtEnd(makefiles, (ClientData)optarg);
299 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
305 maxJobs = strtol(optarg, &endptr, 10);
306 if (maxJobs <= 0 || *endptr != '\0') {
307 warnx("illegal number, -j argument -- %s",
314 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
315 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
320 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
323 Dir_AddDir(sysIncPath, optarg);
324 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
325 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
329 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
333 /* Kind of nonsensical, wot? */
334 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
338 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
342 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
346 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
350 Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
361 * See if the rest of the arguments are variable assignments and
362 * perform them if so. Else take them to be targets and stuff them
363 * on the end of the "create" list.
365 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
366 if (Parse_IsVar(*argv))
367 Parse_DoVar(*argv, VAR_CMD);
370 Punt("illegal (null) argument.");
373 optind = 0; /* -flag... */
378 (void)Lst_AtEnd(create, (ClientData)estrdup(*argv));
383 * Main_ParseArgLine --
384 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
385 * is encountered and by main() when reading the .MAKEFLAGS envariable.
386 * Takes a line of arguments and breaks it into its
387 * component words and passes those words and the number of them to the
388 * MainParseArgs function.
389 * The line should have all its leading whitespace removed.
395 * Only those that come from the various arguments.
398 Main_ParseArgLine(line)
399 char *line; /* Line to fracture */
401 char **argv; /* Manufactured argument vector */
402 int argc; /* Number of arguments in argv */
406 for (; *line == ' '; ++line)
411 argv = brk_string(line, &argc, TRUE);
412 MainParseArgs(argc, argv);
416 chdir_verify_path(path, obpath)
422 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
424 warn("warning: %s", path);
428 if (path[0] != '/') {
429 (void) snprintf(obpath, MAXPATHLEN, "%s/%s",
444 * The main function, for obvious reasons. Initializes variables
445 * and a few modules, then parses the arguments give it in the
446 * environment and on the command line. Reads the system makefile
447 * followed by either Makefile, makefile or the file given by the
448 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
449 * flags it has received by then uses either the Make or the Compat
450 * module to create the initial list of targets.
453 * If -q was given, exits -1 if anything was out-of-date. Else it exits
457 * The program exits when done. Targets are created. etc. etc. etc.
464 Lst targs; /* target nodes to create -- passed to Make_Init */
465 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
467 char *p, *p1, *path, *pathp;
472 char mdpath[MAXPATHLEN + 1];
473 char obpath[MAXPATHLEN + 1];
474 char cdpath[MAXPATHLEN + 1];
475 char *machine = getenv("MACHINE");
476 char *machine_arch = getenv("MACHINE_ARCH");
477 char *machine_cpu = getenv("MACHINE_CPU");
478 Lst sysMkPath; /* Path of sys.mk */
479 char *cp = NULL, *start;
480 /* avoid faults on read-only strings */
481 static char syspath[] = _PATH_DEFSYSPATH;
485 * get rid of resource limit on file descriptors
489 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
490 rl.rlim_cur != rl.rlim_max) {
491 rl.rlim_cur = rl.rlim_max;
492 (void) setrlimit(RLIMIT_NOFILE, &rl);
497 * Find where we are and take care of PWD for the automounter...
498 * All this code is so that we know where we are when we start up
499 * on a different machine with pmake.
502 if (getcwd(curdir, MAXPATHLEN) == NULL)
505 if (stat(curdir, &sa) == -1)
506 err(2, "%s", curdir);
509 if ((pwd = getenv("PWD")) != NULL) {
510 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
511 sa.st_dev == sb.st_dev)
512 (void) strcpy(curdir, pwd);
516 #if defined(__i386__) && defined(__DragonFly_version)
518 * PC-98 kernel sets the `i386' string to the utsname.machine and
519 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
520 * we check machine.ispc98 and adjust the machine variable before
521 * using usname(3) below.
522 * NOTE: machdep.ispc98 was defined on 1998/8/31.
528 len = sizeof(ispc98);
529 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
537 * Get the name of this type of MACHINE from utsname
538 * so we can share an executable for similar machines.
539 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
541 * Note that while MACHINE is decided at run-time,
542 * MACHINE_ARCH is always known at compile time.
546 struct utsname utsname;
548 if (uname(&utsname) == -1) {
549 perror("make: uname");
552 machine = utsname.machine;
560 machine_arch = "unknown";
562 machine_arch = MACHINE_ARCH;
567 * Set machine_cpu to the minumum supported CPU revision based
568 * on the target architecture, if not already set.
571 if (!strcmp(machine_arch, "i386"))
572 machine_cpu = "i386";
573 else if (!strcmp(machine_arch, "alpha"))
576 machine_cpu = "unknown";
580 * The object directory location is determined using the
581 * following order of preference:
583 * 1. MAKEOBJDIRPREFIX`cwd`
585 * 3. _PATH_OBJDIR.${MACHINE}
587 * 5. _PATH_OBJDIRPREFIX`cwd`
589 * If one of the first two fails, use the current directory.
590 * If the remaining three all fail, use the current directory.
592 * Once things are initted,
593 * have to add the original directory to the search path,
594 * and modify the paths for the Makefiles apropriately. The
595 * current directory is also placed as a variable for make scripts.
597 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
598 if (!(path = getenv("MAKEOBJDIR"))) {
600 pathp = _PATH_OBJDIRPREFIX;
601 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
603 if (!(objdir = chdir_verify_path(mdpath, obpath)))
604 if (!(objdir=chdir_verify_path(path, obpath))) {
605 (void) snprintf(mdpath, MAXPATHLEN,
606 "%s%s", pathp, curdir);
607 if (!(objdir=chdir_verify_path(mdpath,
612 else if (!(objdir = chdir_verify_path(path, obpath)))
616 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
617 if (!(objdir = chdir_verify_path(mdpath, obpath)))
622 setenv("PWD", objdir, 1);
625 create = Lst_Init(FALSE);
626 makefiles = Lst_Init(FALSE);
627 envFirstVars = Lst_Init(FALSE);
630 variables = Lst_Init(FALSE);
631 beSilent = FALSE; /* Print commands as executed */
632 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
633 noExecute = FALSE; /* Execute all commands */
634 keepgoing = FALSE; /* Stop on error */
635 allPrecious = FALSE; /* Remove targets when interrupted */
636 queryFlag = FALSE; /* This is not just a check-run */
637 noBuiltins = FALSE; /* Read the built-in rules */
638 touchFlag = FALSE; /* Actually update targets */
639 usePipes = TRUE; /* Catch child output in pipes */
640 debug = 0; /* No debug verbosity, please. */
643 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
645 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
649 forceJobs = FALSE; /* No -j flag */
650 compatMake = FALSE; /* No compat mode */
654 * Initialize the parsing, directory and variable modules to prepare
655 * for the reading of inclusion paths and variable settings on the
658 Dir_Init(); /* Initialize directory structures so -I flags
659 * can be processed correctly */
660 Parse_Init(); /* Need to initialize the paths of #include
662 Var_Init(); /* As well as the lists of variables for
663 * parsing arguments */
665 if (objdir != curdir)
666 Dir_AddDir(dirSearchPath, curdir);
667 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
668 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
669 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
672 * Initialize various variables.
673 * MAKE also gets this name, for compatibility
674 * .MAKEFLAGS gets set to the empty string just in case.
675 * MFLAGS also gets initialized empty, for compatibility.
677 Var_Set("MAKE", argv[0], VAR_GLOBAL);
678 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
679 Var_Set("MFLAGS", "", VAR_GLOBAL);
680 Var_Set("MACHINE", machine, VAR_GLOBAL);
681 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
682 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
685 * First snag any flags out of the MAKE environment variable.
686 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
687 * in a different format).
690 Main_ParseArgLine(getenv("MAKEFLAGS"));
692 Main_ParseArgLine(getenv("MAKE"));
695 MainParseArgs(argc, argv);
698 * Be compatible if user did not specify -j and did not explicitly
699 * turned compatibility on
701 if (!compatMake && !forceJobs)
705 * Initialize archive, target and suffix modules in preparation for
706 * parsing the makefile(s)
716 * Set up the .TARGETS variable to contain the list of targets to be
717 * created. If none specified, make the variable empty -- the parser
718 * will fill the thing in with the default or .MAIN target.
720 if (!Lst_IsEmpty(create)) {
723 for (ln = Lst_First(create); ln != NILLNODE;
725 char *name = (char *)Lst_Datum(ln);
727 Var_Append(".TARGETS", name, VAR_GLOBAL);
730 Var_Set(".TARGETS", "", VAR_GLOBAL);
734 * If no user-supplied system path was given (through the -m option)
735 * add the directories from the DEFSYSPATH (more than one may be given
736 * as dir1:...:dirn) to the system include path.
738 if (Lst_IsEmpty(sysIncPath)) {
739 for (start = syspath; *start != '\0'; start = cp) {
740 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
743 Dir_AddDir(sysIncPath, start);
746 Dir_AddDir(sysIncPath, start);
752 * Read in the built-in rules first, followed by the specified
753 * makefile, if it was (makefile != (char *) NULL), or the default
754 * Makefile and makefile, in that order, if it wasn't.
759 sysMkPath = Lst_Init (FALSE);
760 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
761 if (Lst_IsEmpty(sysMkPath))
762 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
763 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
765 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
768 if (!Lst_IsEmpty(makefiles)) {
771 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
773 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
774 } else if (!ReadMakefile("makefile", NULL))
775 (void)ReadMakefile("Makefile", NULL);
777 (void)ReadMakefile(".depend", NULL);
779 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
782 /* Install all the flags into the MAKE envariable. */
783 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
785 setenv("MAKEFLAGS", p, 1);
787 setenv("MAKE", p, 1);
792 * For compatibility, look at the directories in the VPATH variable
793 * and add them to the search path, if the variable is defined. The
794 * variable's value is in the same format as the PATH envariable, i.e.
795 * <directory>:<directory>:<directory>...
797 if (Var_Exists("VPATH", VAR_CMD)) {
798 char *vpath, *path, *cp, savec;
800 * GCC stores string constants in read-only memory, but
801 * Var_Subst will want to write this thing, so store it
804 static char VPATH[] = "${VPATH}";
806 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
809 /* skip to end of directory */
810 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
812 /* Save terminator character so know when to stop */
815 /* Add directory to search path */
816 Dir_AddDir(dirSearchPath, path);
819 } while (savec == ':');
820 (void)free((Address)vpath);
824 * Now that all search paths have been read for suffixes et al, it's
825 * time to add the default search path to their lists...
829 /* print the initial graph, if the user requested it */
833 /* print the values of any variables requested by the user */
837 for (ln = Lst_First(variables); ln != NILLNODE;
841 p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
843 Punt("make: cannot allocate memory.");
844 /* This sprintf is safe, because of the malloc above */
845 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
846 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
848 value = Var_Value((char *)Lst_Datum(ln),
851 printf("%s\n", value ? value : "");
858 * Have now read the entire graph and need to make a list of targets
859 * to create. If none was given on the command line, we consult the
860 * parsing module to find the main target(s) to create.
862 if (Lst_IsEmpty(create))
863 targs = Parse_MainName();
865 targs = Targ_FindList(create, TARG_CREATE);
867 if (!compatMake && !printVars) {
869 * Initialize job module before traversing the graph, now that
870 * any .BEGIN and .END targets have been read. This is done
871 * only if the -q flag wasn't given (to prevent the .BEGIN from
872 * being executed should it exist).
877 Job_Init(maxJobs, maxLocal);
881 /* Traverse the graph, checking on all the targets */
882 outOfDate = Make_Run(targs);
883 } else if (!printVars) {
885 * Compat_Init will take care of creating all the targets as
886 * well as initializing the module.
891 Lst_Destroy(targs, NOFREE);
892 Lst_Destroy(variables, NOFREE);
893 Lst_Destroy(makefiles, NOFREE);
894 Lst_Destroy(create, (void (*)(ClientData)) free);
896 /* print the graph now it's been processed if the user requested it */
908 if (queryFlag && outOfDate)
916 * Open and parse the given makefile.
919 * TRUE if ok. FALSE if couldn't open file.
928 char *fname = p; /* makefile to read */
929 extern Lst parseIncPath;
931 char *name, path[MAXPATHLEN + 1];
935 if (!strcmp(fname, "-")) {
936 Parse_File("(stdin)", stdin);
937 Var_Set("MAKEFILE", "", VAR_GLOBAL);
939 setMAKEFILE = strcmp(fname, ".depend");
941 /* if we've chdir'd, rebuild the path name */
942 if (curdir != objdir && *fname != '/') {
943 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
945 * XXX The realpath stuff breaks relative includes
946 * XXX in some cases. The problem likely is in
947 * XXX parse.c where it does special things in
948 * XXX ParseDoInclude if the file is relateive
949 * XXX or absolute and not a system file. There
950 * XXX it assumes that if the current file that's
951 * XXX being included is absolute, that any files
952 * XXX that it includes shouldn't do the -I path
953 * XXX stuff, which is inconsistant with historical
954 * XXX behavior. However, I can't pentrate the mists
955 * XXX further, so I'm putting this workaround in
956 * XXX here until such time as the underlying bug
959 #if THIS_BREAKS_THINGS
960 if (realpath(path, path) != NULL &&
961 (stream = fopen(path, "r")) != NULL) {
966 } else if (realpath(fname, path) != NULL) {
969 if ((stream = fopen(fname, "r")) != NULL)
973 if ((stream = fopen(path, "r")) != NULL) {
980 if ((stream = fopen(fname, "r")) != NULL)
984 /* look in -I and system include directories. */
985 name = Dir_FindFile(fname, parseIncPath);
987 name = Dir_FindFile(fname, sysIncPath);
988 if (!name || !(stream = fopen(name, "r")))
990 MAKEFILE = fname = name;
992 * set the MAKEFILE variable desired by System V fans -- the
993 * placement of the setting here means it gets set to the last
994 * makefile specified, as it is set by SysV make.
998 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
999 Parse_File(fname, stream);
1000 (void)fclose(stream);
1007 * Execute the command in cmd, and return the output of that command
1011 * A string containing the output of the command, or the empty string
1012 * If err is not NULL, it contains the reason for the command failure
1015 * The string must be freed by the caller.
1022 char *args[4]; /* Args for invoking the shell */
1023 int fds[2]; /* Pipe streams */
1024 int cpid; /* Child PID */
1025 int pid; /* PID from wait() */
1026 char *res; /* result */
1027 int status; /* command exit status */
1028 Buffer buf; /* buffer to store the result */
1036 * Set up arguments for shell
1044 * Open a pipe for fetching its output
1046 if (pipe(fds) == -1) {
1047 *err = "Couldn't create pipe for \"%s\"";
1054 switch (cpid = vfork()) {
1057 * Close input side of pipe
1059 (void) close(fds[0]);
1062 * Duplicate the output stream to the shell's output, then
1063 * shut the extra thing down. Note we don't fetch the error
1064 * stream...why not? Why?
1066 (void) dup2(fds[1], 1);
1067 (void) close(fds[1]);
1069 (void) execv("/bin/sh", args);
1074 *err = "Couldn't exec \"%s\"";
1079 * No need for the writing half
1081 (void) close(fds[1]);
1083 buf = Buf_Init (MAKE_BSIZE);
1086 char result[BUFSIZ];
1087 cc = read(fds[0], result, sizeof(result));
1089 Buf_AddBytes(buf, cc, (Byte *) result);
1091 while (cc > 0 || (cc == -1 && errno == EINTR));
1094 * Close the input side of the pipe.
1096 (void) close(fds[0]);
1099 * Wait for the process to exit.
1101 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1105 *err = "Error reading shell's output for \"%s\"";
1107 res = (char *)Buf_GetAll (buf, &cc);
1108 Buf_Destroy (buf, FALSE);
1111 *err = "\"%s\" returned non-zero status";
1114 * Null-terminate the result, convert newlines to spaces and
1115 * install it in the variable.
1122 * A final newline is just stripped
1143 * Print an error message given its format.
1149 * The message is printed.
1154 Error(char *fmt, ...)
1167 fmt = va_arg(ap, char *);
1169 (void)vfprintf(stderr, fmt, ap);
1171 (void)fprintf(stderr, "\n");
1172 (void)fflush(stderr);
1177 * Produce a Fatal error message. If jobs are running, waits for them
1189 Fatal(char *fmt, ...)
1202 fmt = va_arg(ap, char *);
1207 (void)vfprintf(stderr, fmt, ap);
1209 (void)fprintf(stderr, "\n");
1210 (void)fflush(stderr);
1214 exit(2); /* Not 1 so -q can distinguish error */
1219 * Major exception once jobs are being created. Kills all jobs, prints
1220 * a message and exits.
1226 * All children are killed indiscriminately and the program Lib_Exits
1231 Punt(char *fmt, ...)
1244 fmt = va_arg(ap, char *);
1247 (void)fprintf(stderr, "make: ");
1248 (void)vfprintf(stderr, fmt, ap);
1250 (void)fprintf(stderr, "\n");
1251 (void)fflush(stderr);
1258 * Exit without giving a message.
1273 exit(2); /* Not 1, so -q can distinguish error */
1278 * Called when aborting due to errors in child shell to signal
1289 int errors; /* number of errors encountered in Make_Make */
1291 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1296 * malloc, but die on error.
1304 if ((p = malloc(len)) == NULL)
1311 * strdup, but die on error.
1319 if ((p = strdup(str)) == NULL)
1326 * realloc, but die on error.
1333 if ((ptr = realloc(ptr, size)) == NULL)
1340 * die when out of memory.
1350 * Remove a file carefully, avoiding directories.
1358 if (lstat(file, &st) == -1)
1361 if (S_ISDIR(st.st_mode)) {
1365 return unlink(file);
1370 * exit with usage message
1375 (void)fprintf(stderr, "%s\n%s\n%s\n",
1376 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1377 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1378 " [-m directory] [-V variable] [variable=value] [target ...]");
1388 printf("%lx ", (unsigned long) a);