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.6 2004/07/23 07:11:03 asmodai 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)
550 machine = utsname.machine;
558 machine_arch = "unknown";
560 machine_arch = MACHINE_ARCH;
565 * Set machine_cpu to the minumum supported CPU revision based
566 * on the target architecture, if not already set.
569 if (!strcmp(machine_arch, "i386"))
570 machine_cpu = "i386";
571 else if (!strcmp(machine_arch, "alpha"))
574 machine_cpu = "unknown";
578 * The object directory location is determined using the
579 * following order of preference:
581 * 1. MAKEOBJDIRPREFIX`cwd`
583 * 3. _PATH_OBJDIR.${MACHINE}
585 * 5. _PATH_OBJDIRPREFIX`cwd`
587 * If one of the first two fails, use the current directory.
588 * If the remaining three all fail, use the current directory.
590 * Once things are initted,
591 * have to add the original directory to the search path,
592 * and modify the paths for the Makefiles apropriately. The
593 * current directory is also placed as a variable for make scripts.
595 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
596 if (!(path = getenv("MAKEOBJDIR"))) {
598 pathp = _PATH_OBJDIRPREFIX;
599 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
601 if (!(objdir = chdir_verify_path(mdpath, obpath)))
602 if (!(objdir=chdir_verify_path(path, obpath))) {
603 (void) snprintf(mdpath, MAXPATHLEN,
604 "%s%s", pathp, curdir);
605 if (!(objdir=chdir_verify_path(mdpath,
610 else if (!(objdir = chdir_verify_path(path, obpath)))
614 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
615 if (!(objdir = chdir_verify_path(mdpath, obpath)))
620 setenv("PWD", objdir, 1);
623 create = Lst_Init(FALSE);
624 makefiles = Lst_Init(FALSE);
625 envFirstVars = Lst_Init(FALSE);
628 variables = Lst_Init(FALSE);
629 beSilent = FALSE; /* Print commands as executed */
630 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
631 noExecute = FALSE; /* Execute all commands */
632 keepgoing = FALSE; /* Stop on error */
633 allPrecious = FALSE; /* Remove targets when interrupted */
634 queryFlag = FALSE; /* This is not just a check-run */
635 noBuiltins = FALSE; /* Read the built-in rules */
636 touchFlag = FALSE; /* Actually update targets */
637 usePipes = TRUE; /* Catch child output in pipes */
638 debug = 0; /* No debug verbosity, please. */
641 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
643 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
647 forceJobs = FALSE; /* No -j flag */
648 compatMake = FALSE; /* No compat mode */
652 * Initialize the parsing, directory and variable modules to prepare
653 * for the reading of inclusion paths and variable settings on the
656 Dir_Init(); /* Initialize directory structures so -I flags
657 * can be processed correctly */
658 Parse_Init(); /* Need to initialize the paths of #include
660 Var_Init(); /* As well as the lists of variables for
661 * parsing arguments */
663 if (objdir != curdir)
664 Dir_AddDir(dirSearchPath, curdir);
665 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
666 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
667 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
670 * Initialize various variables.
671 * MAKE also gets this name, for compatibility
672 * .MAKEFLAGS gets set to the empty string just in case.
673 * MFLAGS also gets initialized empty, for compatibility.
675 Var_Set("MAKE", argv[0], VAR_GLOBAL);
676 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
677 Var_Set("MFLAGS", "", VAR_GLOBAL);
678 Var_Set("MACHINE", machine, VAR_GLOBAL);
679 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
680 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
683 * First snag any flags out of the MAKE environment variable.
684 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
685 * in a different format).
688 Main_ParseArgLine(getenv("MAKEFLAGS"));
690 Main_ParseArgLine(getenv("MAKE"));
693 MainParseArgs(argc, argv);
696 * Be compatible if user did not specify -j and did not explicitly
697 * turned compatibility on
699 if (!compatMake && !forceJobs)
703 * Initialize archive, target and suffix modules in preparation for
704 * parsing the makefile(s)
714 * Set up the .TARGETS variable to contain the list of targets to be
715 * created. If none specified, make the variable empty -- the parser
716 * will fill the thing in with the default or .MAIN target.
718 if (!Lst_IsEmpty(create)) {
721 for (ln = Lst_First(create); ln != NILLNODE;
723 char *name = (char *)Lst_Datum(ln);
725 Var_Append(".TARGETS", name, VAR_GLOBAL);
728 Var_Set(".TARGETS", "", VAR_GLOBAL);
732 * If no user-supplied system path was given (through the -m option)
733 * add the directories from the DEFSYSPATH (more than one may be given
734 * as dir1:...:dirn) to the system include path.
736 if (Lst_IsEmpty(sysIncPath)) {
737 for (start = syspath; *start != '\0'; start = cp) {
738 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
741 Dir_AddDir(sysIncPath, start);
744 Dir_AddDir(sysIncPath, start);
750 * Read in the built-in rules first, followed by the specified
751 * makefile, if it was (makefile != (char *) NULL), or the default
752 * Makefile and makefile, in that order, if it wasn't.
757 sysMkPath = Lst_Init (FALSE);
758 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
759 if (Lst_IsEmpty(sysMkPath))
760 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
761 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
763 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
766 if (!Lst_IsEmpty(makefiles)) {
769 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
771 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
772 } else if (!ReadMakefile("makefile", NULL))
773 (void)ReadMakefile("Makefile", NULL);
775 (void)ReadMakefile(".depend", NULL);
777 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
780 /* Install all the flags into the MAKE envariable. */
781 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
783 setenv("MAKEFLAGS", p, 1);
785 setenv("MAKE", p, 1);
790 * For compatibility, look at the directories in the VPATH variable
791 * and add them to the search path, if the variable is defined. The
792 * variable's value is in the same format as the PATH envariable, i.e.
793 * <directory>:<directory>:<directory>...
795 if (Var_Exists("VPATH", VAR_CMD)) {
796 char *vpath, *path, *cp, savec;
798 * GCC stores string constants in read-only memory, but
799 * Var_Subst will want to write this thing, so store it
802 static char VPATH[] = "${VPATH}";
804 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
807 /* skip to end of directory */
808 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
810 /* Save terminator character so know when to stop */
813 /* Add directory to search path */
814 Dir_AddDir(dirSearchPath, path);
817 } while (savec == ':');
818 (void)free((Address)vpath);
822 * Now that all search paths have been read for suffixes et al, it's
823 * time to add the default search path to their lists...
827 /* print the initial graph, if the user requested it */
831 /* print the values of any variables requested by the user */
835 for (ln = Lst_First(variables); ln != NILLNODE;
839 p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
841 Punt("make: cannot allocate memory.");
842 /* This sprintf is safe, because of the malloc above */
843 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
844 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
846 value = Var_Value((char *)Lst_Datum(ln),
849 printf("%s\n", value ? value : "");
856 * Have now read the entire graph and need to make a list of targets
857 * to create. If none was given on the command line, we consult the
858 * parsing module to find the main target(s) to create.
860 if (Lst_IsEmpty(create))
861 targs = Parse_MainName();
863 targs = Targ_FindList(create, TARG_CREATE);
865 if (!compatMake && !printVars) {
867 * Initialize job module before traversing the graph, now that
868 * any .BEGIN and .END targets have been read. This is done
869 * only if the -q flag wasn't given (to prevent the .BEGIN from
870 * being executed should it exist).
875 Job_Init(maxJobs, maxLocal);
879 /* Traverse the graph, checking on all the targets */
880 outOfDate = Make_Run(targs);
881 } else if (!printVars) {
883 * Compat_Init will take care of creating all the targets as
884 * well as initializing the module.
889 Lst_Destroy(targs, NOFREE);
890 Lst_Destroy(variables, NOFREE);
891 Lst_Destroy(makefiles, NOFREE);
892 Lst_Destroy(create, (void (*)(ClientData)) free);
894 /* print the graph now it's been processed if the user requested it */
906 if (queryFlag && outOfDate)
914 * Open and parse the given makefile.
917 * TRUE if ok. FALSE if couldn't open file.
926 char *fname = p; /* makefile to read */
927 extern Lst parseIncPath;
929 char *name, path[MAXPATHLEN + 1];
933 if (!strcmp(fname, "-")) {
934 Parse_File("(stdin)", stdin);
935 Var_Set("MAKEFILE", "", VAR_GLOBAL);
937 setMAKEFILE = strcmp(fname, ".depend");
939 /* if we've chdir'd, rebuild the path name */
940 if (curdir != objdir && *fname != '/') {
941 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
943 * XXX The realpath stuff breaks relative includes
944 * XXX in some cases. The problem likely is in
945 * XXX parse.c where it does special things in
946 * XXX ParseDoInclude if the file is relateive
947 * XXX or absolute and not a system file. There
948 * XXX it assumes that if the current file that's
949 * XXX being included is absolute, that any files
950 * XXX that it includes shouldn't do the -I path
951 * XXX stuff, which is inconsistant with historical
952 * XXX behavior. However, I can't pentrate the mists
953 * XXX further, so I'm putting this workaround in
954 * XXX here until such time as the underlying bug
957 #if THIS_BREAKS_THINGS
958 if (realpath(path, path) != NULL &&
959 (stream = fopen(path, "r")) != NULL) {
964 } else if (realpath(fname, path) != NULL) {
967 if ((stream = fopen(fname, "r")) != NULL)
971 if ((stream = fopen(path, "r")) != NULL) {
978 if ((stream = fopen(fname, "r")) != NULL)
982 /* look in -I and system include directories. */
983 name = Dir_FindFile(fname, parseIncPath);
985 name = Dir_FindFile(fname, sysIncPath);
986 if (!name || !(stream = fopen(name, "r")))
988 MAKEFILE = fname = name;
990 * set the MAKEFILE variable desired by System V fans -- the
991 * placement of the setting here means it gets set to the last
992 * makefile specified, as it is set by SysV make.
996 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
997 Parse_File(fname, stream);
998 (void)fclose(stream);
1005 * Execute the command in cmd, and return the output of that command
1009 * A string containing the output of the command, or the empty string
1010 * If err is not NULL, it contains the reason for the command failure
1013 * The string must be freed by the caller.
1020 char *args[4]; /* Args for invoking the shell */
1021 int fds[2]; /* Pipe streams */
1022 int cpid; /* Child PID */
1023 int pid; /* PID from wait() */
1024 char *res; /* result */
1025 int status; /* command exit status */
1026 Buffer buf; /* buffer to store the result */
1034 * Set up arguments for shell
1042 * Open a pipe for fetching its output
1044 if (pipe(fds) == -1) {
1045 *err = "Couldn't create pipe for \"%s\"";
1052 switch (cpid = vfork()) {
1055 * Close input side of pipe
1057 (void) close(fds[0]);
1060 * Duplicate the output stream to the shell's output, then
1061 * shut the extra thing down. Note we don't fetch the error
1062 * stream...why not? Why?
1064 (void) dup2(fds[1], 1);
1065 (void) close(fds[1]);
1067 (void) execv("/bin/sh", args);
1072 *err = "Couldn't exec \"%s\"";
1077 * No need for the writing half
1079 (void) close(fds[1]);
1081 buf = Buf_Init (MAKE_BSIZE);
1084 char result[BUFSIZ];
1085 cc = read(fds[0], result, sizeof(result));
1087 Buf_AddBytes(buf, cc, (Byte *) result);
1089 while (cc > 0 || (cc == -1 && errno == EINTR));
1092 * Close the input side of the pipe.
1094 (void) close(fds[0]);
1097 * Wait for the process to exit.
1099 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1103 *err = "Error reading shell's output for \"%s\"";
1105 res = (char *)Buf_GetAll (buf, &cc);
1106 Buf_Destroy (buf, FALSE);
1109 *err = "\"%s\" returned non-zero status";
1112 * Null-terminate the result, convert newlines to spaces and
1113 * install it in the variable.
1120 * A final newline is just stripped
1141 * Print an error message given its format.
1147 * The message is printed.
1152 Error(char *fmt, ...)
1165 fmt = va_arg(ap, char *);
1167 (void)vfprintf(stderr, fmt, ap);
1169 (void)fprintf(stderr, "\n");
1170 (void)fflush(stderr);
1175 * Produce a Fatal error message. If jobs are running, waits for them
1187 Fatal(char *fmt, ...)
1200 fmt = va_arg(ap, char *);
1205 (void)vfprintf(stderr, fmt, ap);
1207 (void)fprintf(stderr, "\n");
1208 (void)fflush(stderr);
1212 exit(2); /* Not 1 so -q can distinguish error */
1217 * Major exception once jobs are being created. Kills all jobs, prints
1218 * a message and exits.
1224 * All children are killed indiscriminately and the program Lib_Exits
1229 Punt(char *fmt, ...)
1242 fmt = va_arg(ap, char *);
1245 (void)fprintf(stderr, "make: ");
1246 (void)vfprintf(stderr, fmt, ap);
1248 (void)fprintf(stderr, "\n");
1249 (void)fflush(stderr);
1256 * Exit without giving a message.
1271 exit(2); /* Not 1, so -q can distinguish error */
1276 * Called when aborting due to errors in child shell to signal
1287 int errors; /* number of errors encountered in Make_Make */
1289 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1294 * malloc, but die on error.
1302 if ((p = malloc(len)) == NULL)
1309 * strdup, but die on error.
1317 if ((p = strdup(str)) == NULL)
1324 * realloc, but die on error.
1331 if ((ptr = realloc(ptr, size)) == NULL)
1338 * die when out of memory.
1348 * Remove a file carefully, avoiding directories.
1356 if (lstat(file, &st) == -1)
1359 if (S_ISDIR(st.st_mode)) {
1363 return unlink(file);
1368 * exit with usage message
1373 (void)fprintf(stderr, "%s\n%s\n%s\n",
1374 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1375 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1376 " [-m directory] [-V variable] [variable=value] [target ...]");
1386 printf("%lx ", (unsigned long) a);