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.10 2003/12/16 08:34:11 des Exp $
41 * $DragonFly: src/usr.bin/make/main.c,v 1.7 2004/10/24 22:43:58 dillon Exp $
52 * The main file for this entire program. Exit routines etc
55 * Utility functions defined in this file:
56 * Main_ParseArgLine Takes a line of arguments, breaks them and
57 * treats them as if they were given when first
58 * invoked. Used by the parse module to implement
61 * Error Print a tagged error message. The global
62 * MAKE variable must have been defined. This
63 * takes a format string and two optional
66 * Fatal Print an error message and exit. Also takes
67 * a format string and two arguments.
69 * Punt Aborts all jobs and exits with a message. Also
70 * takes a format string and two arguments.
72 * Finish Finish things up by printing the number of
73 * errors which occured, as passed to it, and
77 #include <sys/types.h>
79 #include <sys/param.h>
80 #include <sys/resource.h>
81 #include <sys/signal.h>
84 #include <sys/sysctl.h>
87 #include <sys/utsname.h>
105 #include "pathnames.h"
108 #define DEFMAXLOCAL DEFMAXJOBS
109 #endif /* DEFMAXLOCAL */
111 #define MAKEFLAGS ".MAKEFLAGS"
113 Lst create; /* Targets to be made */
114 time_t now; /* Time at start of make */
115 GNode *DEFAULT; /* .DEFAULT node */
116 Boolean allPrecious; /* .PRECIOUS given on line by itself */
118 static Boolean noBuiltins; /* -r flag */
119 static Lst makefiles; /* ordered list of makefiles to read */
120 static Boolean printVars; /* print value of one or more vars */
121 static Boolean expandVars; /* fully expand printed variables */
122 static Lst variables; /* list of variables to print */
123 int maxJobs; /* -j argument */
124 static Boolean forceJobs; /* -j argument given */
125 static int maxLocal; /* -L argument */
126 Boolean compatMake; /* -B argument */
127 Boolean debug; /* -d flag */
128 Boolean noExecute; /* -n flag */
129 Boolean keepgoing; /* -k flag */
130 Boolean queryFlag; /* -q flag */
131 Boolean touchFlag; /* -t flag */
132 Boolean usePipes; /* !-P flag */
133 Boolean ignoreErrors; /* -i flag */
134 Boolean beSilent; /* -s flag */
135 Boolean beVerbose; /* -v flag */
136 Boolean oldVars; /* variable substitution style */
137 Boolean checkEnvFirst; /* -e flag */
138 Lst envFirstVars; /* (-E) vars to override from env */
139 static Boolean jobsRunning; /* TRUE if the jobs might be running */
141 static void MainParseArgs(int, char **);
142 char * chdir_verify_path(char *, char *);
143 static int ReadMakefile(ClientData, ClientData);
144 static void usage(void);
146 static char *curdir; /* startup directory */
147 static char *objdir; /* where we chdir'ed to */
151 * Parse a given argument vector. Called from main() and from
152 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
154 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
160 * Various global and local flags will be set depending on the flags
164 MainParseArgs(argc, argv)
173 optind = 1; /* since we're called more than once */
175 # define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
177 # define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
179 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
182 if (chdir(optarg) == -1)
183 err(1, "chdir %s", optarg);
186 Var_Set(optarg, "1", VAR_GLOBAL);
187 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
188 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
191 Parse_AddIncludeDir(optarg);
192 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
193 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
197 (void)Lst_AtEnd(variables, (ClientData)optarg);
198 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
199 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
206 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
212 maxLocal = strtol(optarg, &endptr, 10);
213 if (maxLocal < 0 || *endptr != '\0') {
214 warnx("illegal number, -L argument -- %s",
218 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
219 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
225 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
229 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
232 char *modules = optarg;
234 for (; *modules; ++modules)
252 if (modules[1] == '1') {
253 debug |= DEBUG_GRAPH1;
256 else if (modules[1] == '2') {
257 debug |= DEBUG_GRAPH2;
280 warnx("illegal argument to d option -- %c", *modules);
283 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
284 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
288 p = malloc(strlen(optarg) + 1);
290 Punt("make: cannot allocate memory.");
291 (void)strcpy(p, optarg);
292 (void)Lst_AtEnd(envFirstVars, (ClientData)p);
293 Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
294 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
297 checkEnvFirst = TRUE;
298 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
301 (void)Lst_AtEnd(makefiles, (ClientData)optarg);
305 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
311 maxJobs = strtol(optarg, &endptr, 10);
312 if (maxJobs <= 0 || *endptr != '\0') {
313 warnx("illegal number, -j argument -- %s",
320 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
321 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
326 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
329 Dir_AddDir(sysIncPath, optarg);
330 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
331 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
335 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
339 /* Kind of nonsensical, wot? */
340 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
344 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
348 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
352 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
356 Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
367 * See if the rest of the arguments are variable assignments and
368 * perform them if so. Else take them to be targets and stuff them
369 * on the end of the "create" list.
371 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
372 if (Parse_IsVar(*argv))
373 Parse_DoVar(*argv, VAR_CMD);
376 Punt("illegal (null) argument.");
379 optind = 0; /* -flag... */
384 (void)Lst_AtEnd(create, (ClientData)estrdup(*argv));
389 * Main_ParseArgLine --
390 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
391 * is encountered and by main() when reading the .MAKEFLAGS envariable.
392 * Takes a line of arguments and breaks it into its
393 * component words and passes those words and the number of them to the
394 * MainParseArgs function.
395 * The line should have all its leading whitespace removed.
401 * Only those that come from the various arguments.
404 Main_ParseArgLine(line)
405 char *line; /* Line to fracture */
407 char **argv; /* Manufactured argument vector */
408 int argc; /* Number of arguments in argv */
412 for (; *line == ' '; ++line)
417 argv = brk_string(line, &argc, TRUE);
418 MainParseArgs(argc, argv);
422 chdir_verify_path(path, obpath)
428 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
430 warn("warning: %s", path);
434 if (path[0] != '/') {
435 (void) snprintf(obpath, MAXPATHLEN, "%s/%s",
450 * The main function, for obvious reasons. Initializes variables
451 * and a few modules, then parses the arguments give it in the
452 * environment and on the command line. Reads the system makefile
453 * followed by either Makefile, makefile or the file given by the
454 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
455 * flags it has received by then uses either the Make or the Compat
456 * module to create the initial list of targets.
459 * If -q was given, exits -1 if anything was out-of-date. Else it exits
463 * The program exits when done. Targets are created. etc. etc. etc.
470 Lst targs; /* target nodes to create -- passed to Make_Init */
471 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
473 char *p, *p1, *path, *pathp;
478 char mdpath[MAXPATHLEN + 1];
479 char obpath[MAXPATHLEN + 1];
480 char cdpath[MAXPATHLEN + 1];
481 char *machine = getenv("MACHINE");
482 char *machine_arch = getenv("MACHINE_ARCH");
483 char *machine_cpu = getenv("MACHINE_CPU");
484 Lst sysMkPath; /* Path of sys.mk */
485 char *cp = NULL, *start;
486 /* avoid faults on read-only strings */
487 static char syspath[] = _PATH_DEFSYSPATH;
491 * Catch SIGCHLD so that we get kicked out of select() when we
492 * need to look at a child. This is only known to matter for the
493 * -j case (perhaps without -P).
495 * XXX this is intentionally misplaced.
499 sigemptyset(&sa.sa_mask);
500 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
501 sa.sa_handler = catch_child;
502 sigaction(SIGCHLD, &sa, NULL);
507 * get rid of resource limit on file descriptors
511 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
512 rl.rlim_cur != rl.rlim_max) {
513 rl.rlim_cur = rl.rlim_max;
514 (void) setrlimit(RLIMIT_NOFILE, &rl);
519 * Find where we are and take care of PWD for the automounter...
520 * All this code is so that we know where we are when we start up
521 * on a different machine with pmake.
524 if (getcwd(curdir, MAXPATHLEN) == NULL)
527 if (stat(curdir, &sa) == -1)
528 err(2, "%s", curdir);
531 if ((pwd = getenv("PWD")) != NULL) {
532 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
533 sa.st_dev == sb.st_dev)
534 (void) strcpy(curdir, pwd);
538 #if defined(__i386__) && defined(__DragonFly_version)
540 * PC-98 kernel sets the `i386' string to the utsname.machine and
541 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
542 * we check machine.ispc98 and adjust the machine variable before
543 * using usname(3) below.
544 * NOTE: machdep.ispc98 was defined on 1998/8/31.
550 len = sizeof(ispc98);
551 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
559 * Get the name of this type of MACHINE from utsname
560 * so we can share an executable for similar machines.
561 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
563 * Note that while MACHINE is decided at run-time,
564 * MACHINE_ARCH is always known at compile time.
568 struct utsname utsname;
570 if (uname(&utsname) == -1)
572 machine = utsname.machine;
580 machine_arch = "unknown";
582 machine_arch = MACHINE_ARCH;
587 * Set machine_cpu to the minumum supported CPU revision based
588 * on the target architecture, if not already set.
591 if (!strcmp(machine_arch, "i386"))
592 machine_cpu = "i386";
593 else if (!strcmp(machine_arch, "alpha"))
596 machine_cpu = "unknown";
600 * The object directory location is determined using the
601 * following order of preference:
603 * 1. MAKEOBJDIRPREFIX`cwd`
605 * 3. _PATH_OBJDIR.${MACHINE}
607 * 5. _PATH_OBJDIRPREFIX`cwd`
609 * If one of the first two fails, use the current directory.
610 * If the remaining three all fail, use the current directory.
612 * Once things are initted,
613 * have to add the original directory to the search path,
614 * and modify the paths for the Makefiles apropriately. The
615 * current directory is also placed as a variable for make scripts.
617 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
618 if (!(path = getenv("MAKEOBJDIR"))) {
620 pathp = _PATH_OBJDIRPREFIX;
621 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
623 if (!(objdir = chdir_verify_path(mdpath, obpath)))
624 if (!(objdir=chdir_verify_path(path, obpath))) {
625 (void) snprintf(mdpath, MAXPATHLEN,
626 "%s%s", pathp, curdir);
627 if (!(objdir=chdir_verify_path(mdpath,
632 else if (!(objdir = chdir_verify_path(path, obpath)))
636 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
637 if (!(objdir = chdir_verify_path(mdpath, obpath)))
642 setenv("PWD", objdir, 1);
645 create = Lst_Init(FALSE);
646 makefiles = Lst_Init(FALSE);
647 envFirstVars = Lst_Init(FALSE);
650 variables = Lst_Init(FALSE);
651 beSilent = FALSE; /* Print commands as executed */
652 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
653 noExecute = FALSE; /* Execute all commands */
654 keepgoing = FALSE; /* Stop on error */
655 allPrecious = FALSE; /* Remove targets when interrupted */
656 queryFlag = FALSE; /* This is not just a check-run */
657 noBuiltins = FALSE; /* Read the built-in rules */
658 touchFlag = FALSE; /* Actually update targets */
659 usePipes = TRUE; /* Catch child output in pipes */
660 debug = 0; /* No debug verbosity, please. */
663 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
665 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
669 forceJobs = FALSE; /* No -j flag */
670 compatMake = FALSE; /* No compat mode */
674 * Initialize the parsing, directory and variable modules to prepare
675 * for the reading of inclusion paths and variable settings on the
678 Dir_Init(); /* Initialize directory structures so -I flags
679 * can be processed correctly */
680 Parse_Init(); /* Need to initialize the paths of #include
682 Var_Init(); /* As well as the lists of variables for
683 * parsing arguments */
685 if (objdir != curdir)
686 Dir_AddDir(dirSearchPath, curdir);
687 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
688 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
689 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
692 * Initialize various variables.
693 * MAKE also gets this name, for compatibility
694 * .MAKEFLAGS gets set to the empty string just in case.
695 * MFLAGS also gets initialized empty, for compatibility.
697 Var_Set("MAKE", argv[0], VAR_GLOBAL);
698 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
699 Var_Set("MFLAGS", "", VAR_GLOBAL);
700 Var_Set("MACHINE", machine, VAR_GLOBAL);
701 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
702 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
705 * First snag any flags out of the MAKE environment variable.
706 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
707 * in a different format).
710 Main_ParseArgLine(getenv("MAKEFLAGS"));
712 Main_ParseArgLine(getenv("MAKE"));
715 MainParseArgs(argc, argv);
718 * Be compatible if user did not specify -j and did not explicitly
719 * turned compatibility on
721 if (!compatMake && !forceJobs)
725 * Initialize archive, target and suffix modules in preparation for
726 * parsing the makefile(s)
736 * Set up the .TARGETS variable to contain the list of targets to be
737 * created. If none specified, make the variable empty -- the parser
738 * will fill the thing in with the default or .MAIN target.
740 if (!Lst_IsEmpty(create)) {
743 for (ln = Lst_First(create); ln != NILLNODE;
745 char *name = (char *)Lst_Datum(ln);
747 Var_Append(".TARGETS", name, VAR_GLOBAL);
750 Var_Set(".TARGETS", "", VAR_GLOBAL);
754 * If no user-supplied system path was given (through the -m option)
755 * add the directories from the DEFSYSPATH (more than one may be given
756 * as dir1:...:dirn) to the system include path.
758 if (Lst_IsEmpty(sysIncPath)) {
759 for (start = syspath; *start != '\0'; start = cp) {
760 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
763 Dir_AddDir(sysIncPath, start);
766 Dir_AddDir(sysIncPath, start);
772 * Read in the built-in rules first, followed by the specified
773 * makefile, if it was (makefile != (char *) NULL), or the default
774 * Makefile and makefile, in that order, if it wasn't.
779 sysMkPath = Lst_Init (FALSE);
780 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
781 if (Lst_IsEmpty(sysMkPath))
782 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
783 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
785 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
788 if (!Lst_IsEmpty(makefiles)) {
791 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
793 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
794 } else if (!ReadMakefile("makefile", NULL))
795 (void)ReadMakefile("Makefile", NULL);
797 (void)ReadMakefile(".depend", NULL);
799 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
802 /* Install all the flags into the MAKE envariable. */
803 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
805 setenv("MAKEFLAGS", p, 1);
807 setenv("MAKE", p, 1);
812 * For compatibility, look at the directories in the VPATH variable
813 * and add them to the search path, if the variable is defined. The
814 * variable's value is in the same format as the PATH envariable, i.e.
815 * <directory>:<directory>:<directory>...
817 if (Var_Exists("VPATH", VAR_CMD)) {
818 char *vpath, *path, *cp, savec;
820 * GCC stores string constants in read-only memory, but
821 * Var_Subst will want to write this thing, so store it
824 static char VPATH[] = "${VPATH}";
826 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
829 /* skip to end of directory */
830 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
832 /* Save terminator character so know when to stop */
835 /* Add directory to search path */
836 Dir_AddDir(dirSearchPath, path);
839 } while (savec == ':');
840 (void)free((Address)vpath);
844 * Now that all search paths have been read for suffixes et al, it's
845 * time to add the default search path to their lists...
849 /* print the initial graph, if the user requested it */
853 /* print the values of any variables requested by the user */
857 for (ln = Lst_First(variables); ln != NILLNODE;
861 p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
863 Punt("make: cannot allocate memory.");
864 /* This sprintf is safe, because of the malloc above */
865 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
866 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
868 value = Var_Value((char *)Lst_Datum(ln),
871 printf("%s\n", value ? value : "");
878 * Have now read the entire graph and need to make a list of targets
879 * to create. If none was given on the command line, we consult the
880 * parsing module to find the main target(s) to create.
882 if (Lst_IsEmpty(create))
883 targs = Parse_MainName();
885 targs = Targ_FindList(create, TARG_CREATE);
887 if (!compatMake && !printVars) {
889 * Initialize job module before traversing the graph, now that
890 * any .BEGIN and .END targets have been read. This is done
891 * only if the -q flag wasn't given (to prevent the .BEGIN from
892 * being executed should it exist).
897 Job_Init(maxJobs, maxLocal);
901 /* Traverse the graph, checking on all the targets */
902 outOfDate = Make_Run(targs);
903 } else if (!printVars) {
905 * Compat_Init will take care of creating all the targets as
906 * well as initializing the module.
911 Lst_Destroy(targs, NOFREE);
912 Lst_Destroy(variables, NOFREE);
913 Lst_Destroy(makefiles, NOFREE);
914 Lst_Destroy(create, (void (*)(ClientData)) free);
916 /* print the graph now it's been processed if the user requested it */
928 if (queryFlag && outOfDate)
936 * Open and parse the given makefile.
939 * TRUE if ok. FALSE if couldn't open file.
948 char *fname = p; /* makefile to read */
949 extern Lst parseIncPath;
951 char *name, path[MAXPATHLEN + 1];
955 if (!strcmp(fname, "-")) {
956 Parse_File("(stdin)", stdin);
957 Var_Set("MAKEFILE", "", VAR_GLOBAL);
959 setMAKEFILE = strcmp(fname, ".depend");
961 /* if we've chdir'd, rebuild the path name */
962 if (curdir != objdir && *fname != '/') {
963 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
965 * XXX The realpath stuff breaks relative includes
966 * XXX in some cases. The problem likely is in
967 * XXX parse.c where it does special things in
968 * XXX ParseDoInclude if the file is relateive
969 * XXX or absolute and not a system file. There
970 * XXX it assumes that if the current file that's
971 * XXX being included is absolute, that any files
972 * XXX that it includes shouldn't do the -I path
973 * XXX stuff, which is inconsistant with historical
974 * XXX behavior. However, I can't pentrate the mists
975 * XXX further, so I'm putting this workaround in
976 * XXX here until such time as the underlying bug
979 #if THIS_BREAKS_THINGS
980 if (realpath(path, path) != NULL &&
981 (stream = fopen(path, "r")) != NULL) {
986 } else if (realpath(fname, path) != NULL) {
989 if ((stream = fopen(fname, "r")) != NULL)
993 if ((stream = fopen(path, "r")) != NULL) {
1000 if ((stream = fopen(fname, "r")) != NULL)
1004 /* look in -I and system include directories. */
1005 name = Dir_FindFile(fname, parseIncPath);
1007 name = Dir_FindFile(fname, sysIncPath);
1008 if (!name || !(stream = fopen(name, "r")))
1010 MAKEFILE = fname = name;
1012 * set the MAKEFILE variable desired by System V fans -- the
1013 * placement of the setting here means it gets set to the last
1014 * makefile specified, as it is set by SysV make.
1018 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1019 Parse_File(fname, stream);
1020 (void)fclose(stream);
1027 * Execute the command in cmd, and return the output of that command
1031 * A string containing the output of the command, or the empty string
1032 * If err is not NULL, it contains the reason for the command failure
1035 * The string must be freed by the caller.
1042 char *args[4]; /* Args for invoking the shell */
1043 int fds[2]; /* Pipe streams */
1044 int cpid; /* Child PID */
1045 int pid; /* PID from wait() */
1046 char *res; /* result */
1047 int status; /* command exit status */
1048 Buffer buf; /* buffer to store the result */
1056 * Set up arguments for shell
1064 * Open a pipe for fetching its output
1066 if (pipe(fds) == -1) {
1067 *err = "Couldn't create pipe for \"%s\"";
1074 switch (cpid = vfork()) {
1077 * Close input side of pipe
1079 (void) close(fds[0]);
1082 * Duplicate the output stream to the shell's output, then
1083 * shut the extra thing down. Note we don't fetch the error
1084 * stream...why not? Why?
1086 (void) dup2(fds[1], 1);
1087 (void) close(fds[1]);
1089 (void) execv("/bin/sh", args);
1094 *err = "Couldn't exec \"%s\"";
1099 * No need for the writing half
1101 (void) close(fds[1]);
1103 buf = Buf_Init (MAKE_BSIZE);
1106 char result[BUFSIZ];
1107 cc = read(fds[0], result, sizeof(result));
1109 Buf_AddBytes(buf, cc, (Byte *) result);
1111 while (cc > 0 || (cc == -1 && errno == EINTR));
1114 * Close the input side of the pipe.
1116 (void) close(fds[0]);
1119 * Wait for the process to exit.
1121 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1125 *err = "Error reading shell's output for \"%s\"";
1127 res = (char *)Buf_GetAll (buf, &cc);
1128 Buf_Destroy (buf, FALSE);
1131 *err = "\"%s\" returned non-zero status";
1134 * Null-terminate the result, convert newlines to spaces and
1135 * install it in the variable.
1142 * A final newline is just stripped
1163 * Print an error message given its format.
1169 * The message is printed.
1174 Error(char *fmt, ...)
1187 fmt = va_arg(ap, char *);
1189 (void)vfprintf(stderr, fmt, ap);
1191 (void)fprintf(stderr, "\n");
1192 (void)fflush(stderr);
1197 * Produce a Fatal error message. If jobs are running, waits for them
1209 Fatal(char *fmt, ...)
1222 fmt = va_arg(ap, char *);
1227 (void)vfprintf(stderr, fmt, ap);
1229 (void)fprintf(stderr, "\n");
1230 (void)fflush(stderr);
1234 exit(2); /* Not 1 so -q can distinguish error */
1239 * Major exception once jobs are being created. Kills all jobs, prints
1240 * a message and exits.
1246 * All children are killed indiscriminately and the program Lib_Exits
1251 Punt(char *fmt, ...)
1264 fmt = va_arg(ap, char *);
1267 (void)fprintf(stderr, "make: ");
1268 (void)vfprintf(stderr, fmt, ap);
1270 (void)fprintf(stderr, "\n");
1271 (void)fflush(stderr);
1278 * Exit without giving a message.
1293 exit(2); /* Not 1, so -q can distinguish error */
1298 * Called when aborting due to errors in child shell to signal
1309 int errors; /* number of errors encountered in Make_Make */
1311 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1316 * malloc, but die on error.
1324 if ((p = malloc(len)) == NULL)
1331 * strdup, but die on error.
1339 if ((p = strdup(str)) == NULL)
1346 * realloc, but die on error.
1353 if ((ptr = realloc(ptr, size)) == NULL)
1360 * die when out of memory.
1370 * Remove a file carefully, avoiding directories.
1378 if (lstat(file, &st) == -1)
1381 if (S_ISDIR(st.st_mode)) {
1385 return unlink(file);
1390 * exit with usage message
1395 (void)fprintf(stderr, "%s\n%s\n%s\n",
1396 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1397 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1398 " [-m directory] [-V variable] [variable=value] [target ...]");
1408 printf("%lx ", (unsigned long) a);