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.42 2005/01/06 13:18:58 okumoto 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
57 #include <sys/utsname.h>
59 #include <sys/param.h>
60 #include <sys/types.h>
82 #include "pathnames.h"
89 #define WANT_ENV_MKLVL 1
90 #define MKLVL_MAXVAL 500
91 #define MKLVL_ENVVAR "__MKLVL__"
93 #define MAKEFLAGS ".MAKEFLAGS"
95 /* Targets to be made */
96 Lst create = Lst_Initializer(create);
98 time_t now; /* Time at start of make */
99 GNode *DEFAULT; /* .DEFAULT node */
100 Boolean allPrecious; /* .PRECIOUS given on line by itself */
102 static Boolean noBuiltins; /* -r flag */
104 /* ordered list of makefiles to read */
105 static Lst makefiles = Lst_Initializer(makefiles);
107 static Boolean expandVars; /* fully expand printed variables */
109 /* list of variables to print */
110 static Lst variables = Lst_Initializer(variables);
112 int maxJobs; /* -j argument */
113 static Boolean forceJobs; /* -j argument given */
114 Boolean compatMake; /* -B argument */
115 Boolean debug; /* -d flag */
116 Boolean noExecute; /* -n flag */
117 Boolean keepgoing; /* -k flag */
118 Boolean queryFlag; /* -q flag */
119 Boolean touchFlag; /* -t flag */
120 Boolean usePipes; /* !-P flag */
121 Boolean ignoreErrors; /* -i flag */
122 Boolean beSilent; /* -s flag */
123 Boolean beVerbose; /* -v flag */
124 Boolean oldVars; /* variable substitution style */
125 Boolean checkEnvFirst; /* -e flag */
127 /* (-E) vars to override from env */
128 Lst envFirstVars = Lst_Initializer(envFirstVars);
130 Boolean jobsRunning; /* TRUE if the jobs might be running */
132 static void MainParseArgs(int, char **);
133 char * chdir_verify_path(char *, char *);
134 static int ReadMakefile(const void *, const void *);
135 static void usage(void);
137 static char *curdir; /* startup directory */
138 static char *objdir; /* where we chdir'ed to */
141 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
144 MFLAGS_append(char *flag, char *arg)
147 Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
149 Var_Append(MAKEFLAGS, arg, VAR_GLOBAL);
151 Var_Append("MFLAGS", flag, VAR_GLOBAL);
153 Var_Append("MFLAGS", arg, VAR_GLOBAL);
158 * Parse a given argument vector. Called from main() and from
159 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
161 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
167 * Various global and local flags will be set depending on the flags
171 MainParseArgs(int argc, char **argv)
175 optind = 1; /* since we're called more than once */
176 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
177 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
180 if (chdir(optarg) == -1)
181 err(1, "chdir %s", optarg);
184 Var_Set(optarg, "1", VAR_GLOBAL);
185 MFLAGS_append("-D", optarg);
188 Parse_AddIncludeDir(optarg);
189 MFLAGS_append("-I", optarg);
192 Lst_AtEnd(&variables, estrdup(optarg));
193 MFLAGS_append("-V", optarg);
200 MFLAGS_append("-B", NULL);
201 unsetenv("MAKE_JOBS_FIFO");
205 MFLAGS_append("-P", NULL);
209 MFLAGS_append("-S", NULL);
212 char *modules = optarg;
214 for (; *modules; ++modules)
232 if (modules[1] == '1') {
233 debug |= DEBUG_GRAPH1;
236 else if (modules[1] == '2') {
237 debug |= DEBUG_GRAPH2;
260 warnx("illegal argument to d option -- %c", *modules);
263 MFLAGS_append("-d", optarg);
267 Lst_AtEnd(&envFirstVars, estrdup(optarg));
268 MFLAGS_append("-E", optarg);
271 checkEnvFirst = TRUE;
272 MFLAGS_append("-e", NULL);
275 Lst_AtEnd(&makefiles, estrdup(optarg));
279 MFLAGS_append("-i", NULL);
285 maxJobs = strtol(optarg, &endptr, 10);
286 if (maxJobs <= 0 || *endptr != '\0') {
287 warnx("illegal number, -j argument -- %s",
291 MFLAGS_append("-j", optarg);
296 MFLAGS_append("-k", NULL);
299 Dir_AddDir(&sysIncPath, optarg);
300 MFLAGS_append("-m", optarg);
304 MFLAGS_append("-n", NULL);
308 /* Kind of nonsensical, wot? */
309 MFLAGS_append("-q", NULL);
313 MFLAGS_append("-r", NULL);
317 MFLAGS_append("-s", NULL);
321 MFLAGS_append("-t", NULL);
325 MFLAGS_append("-v", NULL);
336 * See if the rest of the arguments are variable assignments and
337 * perform them if so. Else take them to be targets and stuff them
338 * on the end of the "create" list.
340 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
341 if (Parse_IsVar(*argv)) {
342 char *ptr = Var_Quote(*argv);
344 Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
347 Parse_DoVar(*argv, VAR_CMD);
350 Punt("illegal (null) argument.");
353 optind = 0; /* -flag... */
358 Lst_AtEnd(&create, estrdup(*argv));
363 * Main_ParseArgLine --
364 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
365 * is encountered and by main() when reading the .MAKEFLAGS envariable.
366 * Takes a line of arguments and breaks it into its
367 * component words and passes those words and the number of them to the
368 * MainParseArgs function.
369 * The line should have all its leading whitespace removed.
375 * Only those that come from the various arguments.
378 Main_ParseArgLine(char *line)
380 char **argv; /* Manufactured argument vector */
381 int argc; /* Number of arguments in argv */
385 for (; *line == ' '; ++line)
390 argv = brk_string(line, &argc, TRUE);
391 MainParseArgs(argc, argv);
395 chdir_verify_path(char *path, char *obpath)
399 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
400 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
401 warn("warning: %s", path);
411 catch_child(int sig __unused)
416 * In lieu of a good way to prevent every possible looping in
417 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
418 * by make(1), to prevent a forkbomb from happening, in a dumb and
422 check_make_level(void)
424 #ifdef WANT_ENV_MKLVL
425 char *value = getenv(MKLVL_ENVVAR);
426 int level = (value == NULL) ? 0 : atoi(value);
429 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
430 } else if (level > MKLVL_MAXVAL) {
431 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
434 sprintf(new_value, "%d", level + 1);
435 setenv(MKLVL_ENVVAR, new_value, 1);
437 #endif /* WANT_ENV_MKLVL */
442 * The main function, for obvious reasons. Initializes variables
443 * and a few modules, then parses the arguments give it in the
444 * environment and on the command line. Reads the system makefile
445 * followed by either Makefile, makefile or the file given by the
446 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
447 * flags it has received by then uses either the Make or the Compat
448 * module to create the initial list of targets.
451 * If -q was given, exits -1 if anything was out-of-date. Else it exits
455 * The program exits when done. Targets are created. etc. etc. etc.
458 main(int argc, char **argv)
460 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
462 char *p, *p1, *path, *pathp;
463 char mdpath[MAXPATHLEN];
464 char obpath[MAXPATHLEN];
465 char cdpath[MAXPATHLEN];
466 char *machine = getenv("MACHINE");
467 char *machine_arch = getenv("MACHINE_ARCH");
468 char *machine_cpu = getenv("MACHINE_CPU");
469 char *cp = NULL, *start;
470 /* avoid faults on read-only strings */
471 static char syspath[] = _PATH_DEFSYSPATH;
475 * Catch SIGCHLD so that we get kicked out of select() when we
476 * need to look at a child. This is only known to matter for the
477 * -j case (perhaps without -P).
479 * XXX this is intentionally misplaced.
483 sigemptyset(&sa.sa_mask);
484 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
485 sa.sa_handler = catch_child;
486 sigaction(SIGCHLD, &sa, NULL);
493 * Turn off ENV to make ksh happier.
500 * get rid of resource limit on file descriptors
504 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
505 rl.rlim_cur != rl.rlim_max) {
506 rl.rlim_cur = rl.rlim_max;
507 setrlimit(RLIMIT_NOFILE, &rl);
513 * PC-98 kernel sets the `i386' string to the utsname.machine and
514 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
515 * we check machine.ispc98 and adjust the machine variable before
516 * using usname(3) below.
517 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
518 * __FreeBSD_version was defined as 300003. So, this check can
519 * safely be done with any kernel with version > 300003.
525 len = sizeof(ispc98);
526 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
533 * Get the name of this type of MACHINE from utsname
534 * so we can share an executable for similar machines.
535 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
537 * Note that while MACHINE is decided at run-time,
538 * MACHINE_ARCH is always known at compile time.
542 struct utsname utsname;
544 if (uname(&utsname) == -1)
546 machine = utsname.machine;
554 machine_arch = "unknown";
556 machine_arch = MACHINE_ARCH;
561 * Set machine_cpu to the minumum supported CPU revision based
562 * on the target architecture, if not already set.
565 if (!strcmp(machine_arch, "i386"))
566 machine_cpu = "i386";
567 else if (!strcmp(machine_arch, "alpha"))
570 machine_cpu = "unknown";
574 beSilent = FALSE; /* Print commands as executed */
575 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
576 noExecute = FALSE; /* Execute all commands */
577 keepgoing = FALSE; /* Stop on error */
578 allPrecious = FALSE; /* Remove targets when interrupted */
579 queryFlag = FALSE; /* This is not just a check-run */
580 noBuiltins = FALSE; /* Read the built-in rules */
581 touchFlag = FALSE; /* Actually update targets */
582 usePipes = TRUE; /* Catch child output in pipes */
583 debug = 0; /* No debug verbosity, please. */
586 maxJobs = DEFMAXJOBS;
587 forceJobs = FALSE; /* No -j flag */
588 compatMake = FALSE; /* No compat mode */
591 * Initialize the parsing, directory and variable modules to prepare
592 * for the reading of inclusion paths and variable settings on the
595 Dir_Init(); /* Initialize directory structures so -I flags
596 * can be processed correctly */
597 Parse_Init(); /* Need to initialize the paths of #include
599 Var_Init(); /* As well as the lists of variables for
600 * parsing arguments */
604 * Initialize various variables.
605 * MAKE also gets this name, for compatibility
606 * .MAKEFLAGS gets set to the empty string just in case.
607 * MFLAGS also gets initialized empty, for compatibility.
609 Var_Set("MAKE", argv[0], VAR_GLOBAL);
610 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
611 Var_Set("MFLAGS", "", VAR_GLOBAL);
612 Var_Set("MACHINE", machine, VAR_GLOBAL);
613 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
614 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
616 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
620 * First snag any flags out of the MAKE environment variable.
621 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
622 * in a different format).
624 Main_ParseArgLine(getenv("MAKEFLAGS"));
626 MainParseArgs(argc, argv);
629 * Find where we are...
630 * All this code is so that we know where we are when we start up
631 * on a different machine with pmake.
634 if (getcwd(curdir, MAXPATHLEN) == NULL)
637 if (stat(curdir, &sa) == -1)
638 err(2, "%s", curdir);
641 * The object directory location is determined using the
642 * following order of preference:
644 * 1. MAKEOBJDIRPREFIX`cwd`
646 * 3. _PATH_OBJDIR.${MACHINE}
648 * 5. _PATH_OBJDIRPREFIX`cwd`
650 * If one of the first two fails, use the current directory.
651 * If the remaining three all fail, use the current directory.
653 * Once things are initted,
654 * have to add the original directory to the search path,
655 * and modify the paths for the Makefiles apropriately. The
656 * current directory is also placed as a variable for make scripts.
658 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
659 if (!(path = getenv("MAKEOBJDIR"))) {
661 pathp = _PATH_OBJDIRPREFIX;
662 snprintf(mdpath, MAXPATHLEN, "%s.%s",
664 if (!(objdir = chdir_verify_path(mdpath, obpath)))
665 if (!(objdir=chdir_verify_path(path, obpath))) {
666 snprintf(mdpath, MAXPATHLEN,
667 "%s%s", pathp, curdir);
668 if (!(objdir=chdir_verify_path(mdpath,
673 else if (!(objdir = chdir_verify_path(path, obpath)))
677 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
678 if (!(objdir = chdir_verify_path(mdpath, obpath)))
681 Dir_InitDot(); /* Initialize the "." directory */
682 if (objdir != curdir)
683 Dir_AddDir(&dirSearchPath, curdir);
684 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
685 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
686 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
688 if (getenv("MAKE_JOBS_FIFO") != NULL)
691 * Be compatible if user did not specify -j and did not explicitly
692 * turned compatibility on
694 if (!compatMake && !forceJobs)
698 * Initialize archive, target and suffix modules in preparation for
699 * parsing the makefile(s)
709 * Set up the .TARGETS variable to contain the list of targets to be
710 * created. If none specified, make the variable empty -- the parser
711 * will fill the thing in with the default or .MAIN target.
713 if (!Lst_IsEmpty(&create)) {
716 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
717 char *name = Lst_Datum(ln);
719 Var_Append(".TARGETS", name, VAR_GLOBAL);
722 Var_Set(".TARGETS", "", VAR_GLOBAL);
726 * If no user-supplied system path was given (through the -m option)
727 * add the directories from the DEFSYSPATH (more than one may be given
728 * as dir1:...:dirn) to the system include path.
730 if (Lst_IsEmpty(&sysIncPath)) {
731 for (start = syspath; *start != '\0'; start = cp) {
732 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
735 Dir_AddDir(&sysIncPath, start);
738 Dir_AddDir(&sysIncPath, start);
744 * Read in the built-in rules first, followed by the specified
745 * makefile, if it was (makefile != (char *) NULL), or the default
746 * Makefile and makefile, in that order, if it wasn't.
750 Lst sysMkPath = Lst_Initializer(sysMkPath);
753 Dir_Expand(_PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
754 if (Lst_IsEmpty(&sysMkPath))
755 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
756 ln = Lst_Find(&sysMkPath, NULL, ReadMakefile);
758 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
759 Lst_Destroy(&sysMkPath, free);
762 if (!Lst_IsEmpty(&makefiles)) {
765 ln = Lst_Find(&makefiles, NULL, ReadMakefile);
767 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
768 } else if (!ReadMakefile("BSDmakefile", NULL))
769 if (!ReadMakefile("makefile", NULL))
770 ReadMakefile("Makefile", NULL);
772 ReadMakefile(".depend", NULL);
774 /* Install all the flags into the MAKE envariable. */
775 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
776 setenv("MAKEFLAGS", p, 1);
780 * For compatibility, look at the directories in the VPATH variable
781 * and add them to the search path, if the variable is defined. The
782 * variable's value is in the same format as the PATH envariable, i.e.
783 * <directory>:<directory>:<directory>...
785 if (Var_Exists("VPATH", VAR_CMD)) {
788 * GCC stores string constants in read-only memory, but
789 * Var_Subst will want to write this thing, so store it
792 static char VPATH[] = "${VPATH}";
794 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
797 /* skip to end of directory */
798 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
800 /* Save terminator character so know when to stop */
803 /* Add directory to search path */
804 Dir_AddDir(&dirSearchPath, path);
807 } while (savec == ':');
812 * Now that all search paths have been read for suffixes et al, it's
813 * time to add the default search path to their lists...
817 /* print the initial graph, if the user requested it */
821 /* print the values of any variables requested by the user */
822 if (!Lst_IsEmpty(&variables)) {
825 for (ln = Lst_First(&variables); ln != NULL;
829 p1 = emalloc(strlen(Lst_Datum(ln)) + 1 + 3);
830 /* This sprintf is safe, because of the malloc above */
831 sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
832 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
834 value = Var_Value(Lst_Datum(ln),
837 printf("%s\n", value ? value : "");
844 * Have now read the entire graph and need to make a list of targets
845 * to create. If none was given on the command line, we consult the
846 * parsing module to find the main target(s) to create.
848 Lst targs = Lst_Initializer(targs);
850 if (Lst_IsEmpty(&create))
851 Parse_MainName(&targs);
853 Targ_FindList(&targs, &create, TARG_CREATE);
857 * Initialize job module before traversing the graph, now that
858 * any .BEGIN and .END targets have been read. This is done
859 * only if the -q flag wasn't given (to prevent the .BEGIN from
860 * being executed should it exist).
867 /* Traverse the graph, checking on all the targets */
868 outOfDate = Make_Run(&targs);
871 * Compat_Init will take care of creating all the targets as
872 * well as initializing the module.
877 Lst_Destroy(&targs, NOFREE);
880 Lst_Destroy(&variables, free);
881 Lst_Destroy(&makefiles, free);
882 Lst_Destroy(&create, free);
884 /* print the graph now it's been processed if the user requested it */
888 if (queryFlag && outOfDate)
896 * Open and parse the given makefile.
899 * TRUE if ok. FALSE if couldn't open file.
905 ReadMakefile(const void *p, const void *q __unused)
907 char *fname; /* makefile to read */
909 char *name, path[MAXPATHLEN];
913 /* XXX - remove this once constification is done */
916 if (!strcmp(fname, "-")) {
917 Parse_File("(stdin)", stdin);
918 Var_Set("MAKEFILE", "", VAR_GLOBAL);
920 setMAKEFILE = strcmp(fname, ".depend");
922 /* if we've chdir'd, rebuild the path name */
923 if (curdir != objdir && *fname != '/') {
924 snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
926 * XXX The realpath stuff breaks relative includes
927 * XXX in some cases. The problem likely is in
928 * XXX parse.c where it does special things in
929 * XXX ParseDoInclude if the file is relateive
930 * XXX or absolute and not a system file. There
931 * XXX it assumes that if the current file that's
932 * XXX being included is absolute, that any files
933 * XXX that it includes shouldn't do the -I path
934 * XXX stuff, which is inconsistant with historical
935 * XXX behavior. However, I can't pentrate the mists
936 * XXX further, so I'm putting this workaround in
937 * XXX here until such time as the underlying bug
940 #if THIS_BREAKS_THINGS
941 if (realpath(path, path) != NULL &&
942 (stream = fopen(path, "r")) != NULL) {
947 } else if (realpath(fname, path) != NULL) {
950 if ((stream = fopen(fname, "r")) != NULL)
954 if ((stream = fopen(path, "r")) != NULL) {
961 if ((stream = fopen(fname, "r")) != NULL)
965 /* look in -I and system include directories. */
966 name = Dir_FindFile(fname, &parseIncPath);
968 name = Dir_FindFile(fname, &sysIncPath);
969 if (!name || !(stream = fopen(name, "r")))
971 MAKEFILE = fname = name;
973 * set the MAKEFILE variable desired by System V fans -- the
974 * placement of the setting here means it gets set to the last
975 * makefile specified, as it is set by SysV make.
979 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
980 Parse_File(fname, stream);
988 * Execute the command in cmd, and return the output of that command
992 * A string containing the output of the command, or the empty string
993 * If error is not NULL, it contains the reason for the command failure
996 * The string must be freed by the caller.
999 Cmd_Exec(char *cmd, char **error)
1001 char *args[4]; /* Args for invoking the shell */
1002 int fds[2]; /* Pipe streams */
1003 int cpid; /* Child PID */
1004 int pid; /* PID from wait() */
1005 char *res; /* result */
1006 int status; /* command exit status */
1007 Buffer *buf; /* buffer to store the result */
1014 if (shellPath == NULL)
1017 * Set up arguments for shell
1019 args[0] = shellName;
1025 * Open a pipe for fetching its output
1027 if (pipe(fds) == -1) {
1028 *error = "Couldn't create pipe for \"%s\"";
1035 switch (cpid = vfork()) {
1038 * Close input side of pipe
1043 * Duplicate the output stream to the shell's output, then
1044 * shut the extra thing down. Note we don't fetch the error
1045 * stream...why not? Why?
1050 execv(shellPath, args);
1055 *error = "Couldn't exec \"%s\"";
1060 * No need for the writing half
1064 buf = Buf_Init(MAKE_BSIZE);
1067 char result[BUFSIZ];
1068 rcnt = read(fds[0], result, sizeof(result));
1070 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1071 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1073 * Close the input side of the pipe.
1078 * Wait for the process to exit.
1080 while (((pid = wait(&status)) != cpid) && (pid >= 0))
1084 *error = "Error reading shell's output for \"%s\"";
1086 res = (char *)Buf_GetAll(buf, &blen);
1087 Buf_Destroy(buf, FALSE);
1090 *error = "\"%s\" returned non-zero status";
1093 * Null-terminate the result, convert newlines to spaces and
1094 * install it in the variable.
1097 cp = &res[blen] - 1;
1101 * A final newline is just stripped
1122 * exit with usage message
1127 fprintf(stderr, "%s\n%s\n%s\n",
1128 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1129 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1130 " [-m directory] [-V variable] [variable=value] [target ...]");