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 * @(#)main.c 8.3 (Berkeley) 3/19/94
43 static char copyright[] =
44 "@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
45 The Regents of the University of California. All rights reserved.\n";
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
53 * The main file for this entire program. Exit routines etc
56 * Utility functions defined in this file:
57 * Main_ParseArgLine Takes a line of arguments, breaks them and
58 * treats them as if they were given when first
59 * invoked. Used by the parse module to implement
63 #include <sys/param.h>
64 #include <sys/signal.h>
67 #include <sys/sysctl.h>
70 #include <sys/resource.h>
72 #include <sys/utsname.h>
90 #include "pathnames.h"
92 #define WANT_ENV_MKLVL 1
95 #define DEFMAXLOCAL DEFMAXJOBS
96 #endif /* DEFMAXLOCAL */
98 #define MAKEFLAGS ".MAKEFLAGS"
100 Lst create; /* Targets to be made */
101 time_t now; /* Time at start of make */
102 GNode *DEFAULT; /* .DEFAULT node */
103 Boolean allPrecious; /* .PRECIOUS given on line by itself */
105 static Boolean noBuiltins; /* -r flag */
106 static Lst makefiles; /* ordered list of makefiles to read */
107 static Boolean expandVars; /* fully expand printed variables */
108 static Lst variables; /* list of variables to print */
109 int maxJobs; /* -j argument */
110 static Boolean forceJobs; /* -j argument given */
111 static int maxLocal; /* -L argument */
112 Boolean compatMake; /* -B argument */
113 Boolean debug; /* -d flag */
114 Boolean noExecute; /* -n flag */
115 Boolean keepgoing; /* -k flag */
116 Boolean queryFlag; /* -q flag */
117 Boolean touchFlag; /* -t flag */
118 Boolean usePipes; /* !-P flag */
119 Boolean ignoreErrors; /* -i flag */
120 Boolean beSilent; /* -s flag */
121 Boolean beVerbose; /* -v flag */
122 Boolean oldVars; /* variable substitution style */
123 Boolean checkEnvFirst; /* -e flag */
124 Lst envFirstVars; /* (-E) vars to override from env */
125 Boolean jobsRunning; /* TRUE if the jobs might be running */
127 static void MainParseArgs(int, char **);
128 char * chdir_verify_path(char *, char *);
129 static int ReadMakefile(void *, void *);
130 static void usage(void);
132 static char *curdir; /* startup directory */
133 static char *objdir; /* where we chdir'ed to */
136 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
139 MFLAGS_append(char *flag, char *arg)
141 Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
143 Var_Append(MAKEFLAGS, arg, VAR_GLOBAL);
145 Var_Append("MFLAGS", flag, VAR_GLOBAL);
147 Var_Append("MFLAGS", arg, VAR_GLOBAL);
152 * Parse a given argument vector. Called from main() and from
153 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
155 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
161 * Various global and local flags will be set depending on the flags
165 MainParseArgs(int argc, char **argv)
170 optind = 1; /* since we're called more than once */
171 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
172 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
175 if (chdir(optarg) == -1)
176 err(1, "chdir %s", optarg);
179 Var_Set(optarg, "1", VAR_GLOBAL);
180 MFLAGS_append("-D", optarg);
183 Parse_AddIncludeDir(optarg);
184 MFLAGS_append("-I", optarg);
187 (void)Lst_AtEnd(variables, (void *)optarg);
188 MFLAGS_append("-V", optarg);
195 MFLAGS_append("-B", NULL);
199 MFLAGS_append("-P", NULL);
203 MFLAGS_append("-S", NULL);
206 char *modules = optarg;
208 for (; *modules; ++modules)
226 if (modules[1] == '1') {
227 debug |= DEBUG_GRAPH1;
230 else if (modules[1] == '2') {
231 debug |= DEBUG_GRAPH2;
254 warnx("illegal argument to d option -- %c", *modules);
257 MFLAGS_append("-d", optarg);
261 p = emalloc(strlen(optarg) + 1);
262 (void)strcpy(p, optarg);
263 (void)Lst_AtEnd(envFirstVars, (void *)p);
264 MFLAGS_append("-E", optarg);
267 checkEnvFirst = TRUE;
268 MFLAGS_append("-e", NULL);
271 (void)Lst_AtEnd(makefiles, (void *)optarg);
275 MFLAGS_append("-i", NULL);
281 maxJobs = strtol(optarg, &endptr, 10);
282 if (maxJobs <= 0 || *endptr != '\0') {
283 warnx("illegal number, -j argument -- %s",
288 MFLAGS_append("-j", optarg);
293 MFLAGS_append("-k", NULL);
296 Dir_AddDir(sysIncPath, optarg);
297 MFLAGS_append("-m", optarg);
301 MFLAGS_append("-n", NULL);
305 /* Kind of nonsensical, wot? */
306 MFLAGS_append("-q", NULL);
310 MFLAGS_append("-r", NULL);
314 MFLAGS_append("-s", NULL);
318 MFLAGS_append("-t", NULL);
322 MFLAGS_append("-v", NULL);
333 * See if the rest of the arguments are variable assignments and
334 * perform them if so. Else take them to be targets and stuff them
335 * on the end of the "create" list.
337 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
338 if (Parse_IsVar(*argv)) {
339 char *ptr = Var_Quote(*argv);
341 Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
344 Parse_DoVar(*argv, VAR_CMD);
347 Punt("illegal (null) argument.");
350 optind = 0; /* -flag... */
355 (void)Lst_AtEnd(create, (void *)estrdup(*argv));
360 * Main_ParseArgLine --
361 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
362 * is encountered and by main() when reading the .MAKEFLAGS envariable.
363 * Takes a line of arguments and breaks it into its
364 * component words and passes those words and the number of them to the
365 * MainParseArgs function.
366 * The line should have all its leading whitespace removed.
372 * Only those that come from the various arguments.
375 Main_ParseArgLine(char *line)
377 char **argv; /* Manufactured argument vector */
378 int argc; /* Number of arguments in argv */
382 for (; *line == ' '; ++line)
387 argv = brk_string(line, &argc, TRUE);
388 MainParseArgs(argc, argv);
392 chdir_verify_path(char *path, char *obpath)
396 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
397 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
398 warn("warning: %s", path);
408 catch_child(int sig __unused)
414 * The main function, for obvious reasons. Initializes variables
415 * and a few modules, then parses the arguments give it in the
416 * environment and on the command line. Reads the system makefile
417 * followed by either Makefile, makefile or the file given by the
418 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
419 * flags it has received by then uses either the Make or the Compat
420 * module to create the initial list of targets.
423 * If -q was given, exits -1 if anything was out-of-date. Else it exits
427 * The program exits when done. Targets are created. etc. etc. etc.
430 main(int argc, char **argv)
432 Lst targs; /* target nodes to create -- passed to Make_Init */
433 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
435 char *p, *p1, *path, *pathp;
436 #ifdef WANT_ENV_MKLVL
437 #define MKLVL_MAXVAL 500
438 #define MKLVL_ENVVAR "__MKLVL__"
440 char *szMkLvl = getenv(MKLVL_ENVVAR);
441 #endif /* WANT_ENV_MKLVL */
442 char mdpath[MAXPATHLEN];
443 char obpath[MAXPATHLEN];
444 char cdpath[MAXPATHLEN];
445 char *machine = getenv("MACHINE");
446 char *machine_arch = getenv("MACHINE_ARCH");
447 char *machine_cpu = getenv("MACHINE_CPU");
448 Lst sysMkPath; /* Path of sys.mk */
449 char *cp = NULL, *start;
450 /* avoid faults on read-only strings */
451 static char syspath[] = _PATH_DEFSYSPATH;
455 * Catch SIGCHLD so that we get kicked out of select() when we
456 * need to look at a child. This is only known to matter for the
457 * -j case (perhaps without -P).
459 * XXX this is intentionally misplaced.
463 sigemptyset(&sa.sa_mask);
464 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
465 sa.sa_handler = catch_child;
466 sigaction(SIGCHLD, &sa, NULL);
469 #ifdef WANT_ENV_MKLVL
470 if ((iMkLvl = szMkLvl ? atoi(szMkLvl) : 0) < 0) {
473 if (iMkLvl++ > MKLVL_MAXVAL) {
475 "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
477 bzero(szMkLvl = emalloc(32), 32);
478 sprintf(szMkLvl, "%d", iMkLvl);
479 setenv(MKLVL_ENVVAR, szMkLvl, 1);
480 #endif /* WANT_ENV_MKLVL */
484 * Turn off ENV to make ksh happier.
491 * get rid of resource limit on file descriptors
495 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
496 rl.rlim_cur != rl.rlim_max) {
497 rl.rlim_cur = rl.rlim_max;
498 (void) setrlimit(RLIMIT_NOFILE, &rl);
504 * PC-98 kernel sets the `i386' string to the utsname.machine and
505 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
506 * we check machine.ispc98 and adjust the machine variable before
507 * using usname(3) below.
508 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
509 * __FreeBSD_version was defined as 300003. So, this check can
510 * safely be done with any kernel with version > 300003.
516 len = sizeof(ispc98);
517 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
524 * Get the name of this type of MACHINE from utsname
525 * so we can share an executable for similar machines.
526 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
528 * Note that while MACHINE is decided at run-time,
529 * MACHINE_ARCH is always known at compile time.
533 struct utsname utsname;
535 if (uname(&utsname) == -1)
537 machine = utsname.machine;
545 machine_arch = "unknown";
547 machine_arch = MACHINE_ARCH;
552 * Set machine_cpu to the minumum supported CPU revision based
553 * on the target architecture, if not already set.
556 if (!strcmp(machine_arch, "i386"))
557 machine_cpu = "i386";
558 else if (!strcmp(machine_arch, "alpha"))
561 machine_cpu = "unknown";
564 create = Lst_Init(FALSE);
565 makefiles = Lst_Init(FALSE);
566 envFirstVars = Lst_Init(FALSE);
568 variables = Lst_Init(FALSE);
569 beSilent = FALSE; /* Print commands as executed */
570 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
571 noExecute = FALSE; /* Execute all commands */
572 keepgoing = FALSE; /* Stop on error */
573 allPrecious = FALSE; /* Remove targets when interrupted */
574 queryFlag = FALSE; /* This is not just a check-run */
575 noBuiltins = FALSE; /* Read the built-in rules */
576 touchFlag = FALSE; /* Actually update targets */
577 usePipes = TRUE; /* Catch child output in pipes */
578 debug = 0; /* No debug verbosity, please. */
581 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
583 forceJobs = FALSE; /* No -j flag */
584 compatMake = FALSE; /* No compat mode */
588 * Initialize the parsing, directory and variable modules to prepare
589 * for the reading of inclusion paths and variable settings on the
592 Dir_Init(); /* Initialize directory structures so -I flags
593 * can be processed correctly */
594 Parse_Init(); /* Need to initialize the paths of #include
596 Var_Init(); /* As well as the lists of variables for
597 * parsing arguments */
601 * Initialize various variables.
602 * MAKE also gets this name, for compatibility
603 * .MAKEFLAGS gets set to the empty string just in case.
604 * MFLAGS also gets initialized empty, for compatibility.
606 Var_Set("MAKE", argv[0], VAR_GLOBAL);
607 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
608 Var_Set("MFLAGS", "", VAR_GLOBAL);
609 Var_Set("MACHINE", machine, VAR_GLOBAL);
610 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
611 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
613 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
617 * First snag any flags out of the MAKE environment variable.
618 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
619 * in a different format).
622 Main_ParseArgLine(getenv("MAKEFLAGS"));
624 Main_ParseArgLine(getenv("MAKE"));
627 MainParseArgs(argc, argv);
630 * Find where we are...
631 * All this code is so that we know where we are when we start up
632 * on a different machine with pmake.
635 if (getcwd(curdir, MAXPATHLEN) == NULL)
638 if (stat(curdir, &sa) == -1)
639 err(2, "%s", curdir);
642 * The object directory location is determined using the
643 * following order of preference:
645 * 1. MAKEOBJDIRPREFIX`cwd`
647 * 3. _PATH_OBJDIR.${MACHINE}
649 * 5. _PATH_OBJDIRPREFIX`cwd`
651 * If one of the first two fails, use the current directory.
652 * If the remaining three all fail, use the current directory.
654 * Once things are initted,
655 * have to add the original directory to the search path,
656 * and modify the paths for the Makefiles apropriately. The
657 * current directory is also placed as a variable for make scripts.
659 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
660 if (!(path = getenv("MAKEOBJDIR"))) {
662 pathp = _PATH_OBJDIRPREFIX;
663 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
665 if (!(objdir = chdir_verify_path(mdpath, obpath)))
666 if (!(objdir=chdir_verify_path(path, obpath))) {
667 (void) snprintf(mdpath, MAXPATHLEN,
668 "%s%s", pathp, curdir);
669 if (!(objdir=chdir_verify_path(mdpath,
674 else if (!(objdir = chdir_verify_path(path, obpath)))
678 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
679 if (!(objdir = chdir_verify_path(mdpath, obpath)))
682 Dir_InitDot(); /* Initialize the "." directory */
683 if (objdir != curdir)
684 Dir_AddDir(dirSearchPath, curdir);
685 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
686 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
689 * Be compatible if user did not specify -j and did not explicitly
690 * turned compatibility on
692 if (!compatMake && !forceJobs)
696 * Initialize archive, target and suffix modules in preparation for
697 * parsing the makefile(s)
707 * Set up the .TARGETS variable to contain the list of targets to be
708 * created. If none specified, make the variable empty -- the parser
709 * will fill the thing in with the default or .MAIN target.
711 if (!Lst_IsEmpty(create)) {
714 for (ln = Lst_First(create); ln != NULL;
716 char *name = (char *)Lst_Datum(ln);
718 Var_Append(".TARGETS", name, VAR_GLOBAL);
721 Var_Set(".TARGETS", "", VAR_GLOBAL);
725 * If no user-supplied system path was given (through the -m option)
726 * add the directories from the DEFSYSPATH (more than one may be given
727 * as dir1:...:dirn) to the system include path.
729 if (Lst_IsEmpty(sysIncPath)) {
730 for (start = syspath; *start != '\0'; start = cp) {
731 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
734 Dir_AddDir(sysIncPath, start);
737 Dir_AddDir(sysIncPath, start);
743 * Read in the built-in rules first, followed by the specified
744 * makefile, if it was (makefile != (char *) NULL), or the default
745 * Makefile and makefile, in that order, if it wasn't.
750 sysMkPath = Lst_Init (FALSE);
751 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
752 if (Lst_IsEmpty(sysMkPath))
753 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
754 ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile);
756 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
759 if (!Lst_IsEmpty(makefiles)) {
762 ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
764 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
765 } else if (!ReadMakefile("BSDmakefile", NULL))
766 if (!ReadMakefile("makefile", NULL))
767 (void)ReadMakefile("Makefile", NULL);
769 (void)ReadMakefile(".depend", NULL);
771 /* Install all the flags into the MAKE envariable. */
772 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
774 setenv("MAKEFLAGS", p, 1);
776 setenv("MAKE", p, 1);
781 * For compatibility, look at the directories in the VPATH variable
782 * and add them to the search path, if the variable is defined. The
783 * variable's value is in the same format as the PATH envariable, i.e.
784 * <directory>:<directory>:<directory>...
786 if (Var_Exists("VPATH", VAR_CMD)) {
789 * GCC stores string constants in read-only memory, but
790 * Var_Subst will want to write this thing, so store it
793 static char VPATH[] = "${VPATH}";
795 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
798 /* skip to end of directory */
799 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
801 /* Save terminator character so know when to stop */
804 /* Add directory to search path */
805 Dir_AddDir(dirSearchPath, path);
808 } while (savec == ':');
813 * Now that all search paths have been read for suffixes et al, it's
814 * time to add the default search path to their lists...
818 /* print the initial graph, if the user requested it */
822 /* print the values of any variables requested by the user */
823 if (!Lst_IsEmpty(variables)) {
826 for (ln = Lst_First(variables); ln != NULL;
830 p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
831 /* This sprintf is safe, because of the malloc above */
832 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
833 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
835 value = Var_Value((char *)Lst_Datum(ln),
838 printf("%s\n", value ? value : "");
845 * Have now read the entire graph and need to make a list of targets
846 * to create. If none was given on the command line, we consult the
847 * parsing module to find the main target(s) to create.
849 if (Lst_IsEmpty(create))
850 targs = Parse_MainName();
852 targs = Targ_FindList(create, TARG_CREATE);
856 * Initialize job module before traversing the graph, now that
857 * any .BEGIN and .END targets have been read. This is done
858 * only if the -q flag wasn't given (to prevent the .BEGIN from
859 * being executed should it exist).
864 Job_Init(maxJobs, maxLocal);
868 /* Traverse the graph, checking on all the targets */
869 outOfDate = Make_Run(targs);
872 * Compat_Init will take care of creating all the targets as
873 * well as initializing the module.
878 Lst_Destroy(targs, NOFREE);
881 Lst_Destroy(variables, NOFREE);
882 Lst_Destroy(makefiles, NOFREE);
883 Lst_Destroy(create, (void (*)(void *)) free);
885 /* print the graph now it's been processed if the user requested it */
897 if (queryFlag && outOfDate)
905 * Open and parse the given makefile.
908 * TRUE if ok. FALSE if couldn't open file.
914 ReadMakefile(void *p, void *q __unused)
916 char *fname; /* makefile to read */
918 char *name, path[MAXPATHLEN];
924 if (!strcmp(fname, "-")) {
925 Parse_File("(stdin)", stdin);
926 Var_Set("MAKEFILE", "", VAR_GLOBAL);
928 setMAKEFILE = strcmp(fname, ".depend");
930 /* if we've chdir'd, rebuild the path name */
931 if (curdir != objdir && *fname != '/') {
932 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
934 * XXX The realpath stuff breaks relative includes
935 * XXX in some cases. The problem likely is in
936 * XXX parse.c where it does special things in
937 * XXX ParseDoInclude if the file is relateive
938 * XXX or absolute and not a system file. There
939 * XXX it assumes that if the current file that's
940 * XXX being included is absolute, that any files
941 * XXX that it includes shouldn't do the -I path
942 * XXX stuff, which is inconsistant with historical
943 * XXX behavior. However, I can't pentrate the mists
944 * XXX further, so I'm putting this workaround in
945 * XXX here until such time as the underlying bug
948 #if THIS_BREAKS_THINGS
949 if (realpath(path, path) != NULL &&
950 (stream = fopen(path, "r")) != NULL) {
955 } else if (realpath(fname, path) != NULL) {
958 if ((stream = fopen(fname, "r")) != NULL)
962 if ((stream = fopen(path, "r")) != NULL) {
969 if ((stream = fopen(fname, "r")) != NULL)
973 /* look in -I and system include directories. */
974 name = Dir_FindFile(fname, parseIncPath);
976 name = Dir_FindFile(fname, sysIncPath);
977 if (!name || !(stream = fopen(name, "r")))
979 MAKEFILE = fname = name;
981 * set the MAKEFILE variable desired by System V fans -- the
982 * placement of the setting here means it gets set to the last
983 * makefile specified, as it is set by SysV make.
987 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
988 Parse_File(fname, stream);
989 (void)fclose(stream);
996 * Execute the command in cmd, and return the output of that command
1000 * A string containing the output of the command, or the empty string
1001 * If error is not NULL, it contains the reason for the command failure
1004 * The string must be freed by the caller.
1007 Cmd_Exec(char *cmd, char **error)
1009 char *args[4]; /* Args for invoking the shell */
1010 int fds[2]; /* Pipe streams */
1011 int cpid; /* Child PID */
1012 int pid; /* PID from wait() */
1013 char *res; /* result */
1014 int status; /* command exit status */
1015 Buffer buf; /* buffer to store the result */
1021 if (shellPath == NULL)
1024 * Set up arguments for shell
1026 args[0] = shellName;
1032 * Open a pipe for fetching its output
1034 if (pipe(fds) == -1) {
1035 *error = "Couldn't create pipe for \"%s\"";
1042 switch (cpid = vfork()) {
1045 * Close input side of pipe
1047 (void) close(fds[0]);
1050 * Duplicate the output stream to the shell's output, then
1051 * shut the extra thing down. Note we don't fetch the error
1052 * stream...why not? Why?
1054 (void) dup2(fds[1], 1);
1055 (void) close(fds[1]);
1057 (void) execv(shellPath, args);
1062 *error = "Couldn't exec \"%s\"";
1067 * No need for the writing half
1069 (void) close(fds[1]);
1071 buf = Buf_Init (MAKE_BSIZE);
1074 char result[BUFSIZ];
1075 cc = read(fds[0], result, sizeof(result));
1077 Buf_AddBytes(buf, cc, (Byte *) result);
1079 while (cc > 0 || (cc == -1 && errno == EINTR));
1082 * Close the input side of the pipe.
1084 (void) close(fds[0]);
1087 * Wait for the process to exit.
1089 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1093 *error = "Error reading shell's output for \"%s\"";
1095 res = (char *)Buf_GetAll (buf, &cc);
1096 Buf_Destroy (buf, FALSE);
1099 *error = "\"%s\" returned non-zero status";
1102 * Null-terminate the result, convert newlines to spaces and
1103 * install it in the variable.
1110 * A final newline is just stripped
1131 * exit with usage message
1136 (void)fprintf(stderr, "%s\n%s\n%s\n",
1137 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1138 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1139 " [-m directory] [-V variable] [variable=value] [target ...]");