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.33 2004/12/16 22:20:12 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
56 #include <sys/param.h>
57 #include <sys/signal.h>
59 #include <sys/sysctl.h>
61 #include <sys/resource.h>
63 #include <sys/utsname.h>
81 #include "pathnames.h"
83 #define WANT_ENV_MKLVL 1
84 #define MKLVL_MAXVAL 500
85 #define MKLVL_ENVVAR "__MKLVL__"
87 #define MAKEFLAGS ".MAKEFLAGS"
89 Lst create; /* Targets to be made */
90 time_t now; /* Time at start of make */
91 GNode *DEFAULT; /* .DEFAULT node */
92 Boolean allPrecious; /* .PRECIOUS given on line by itself */
94 static Boolean noBuiltins; /* -r flag */
95 static Lst makefiles; /* ordered list of makefiles to read */
96 static Boolean expandVars; /* fully expand printed variables */
97 static Lst variables; /* list of variables to print */
98 int maxJobs; /* -j argument */
99 static Boolean forceJobs; /* -j argument given */
100 Boolean compatMake; /* -B argument */
101 Boolean debug; /* -d flag */
102 Boolean noExecute; /* -n flag */
103 Boolean keepgoing; /* -k flag */
104 Boolean queryFlag; /* -q flag */
105 Boolean touchFlag; /* -t flag */
106 Boolean usePipes; /* !-P flag */
107 Boolean ignoreErrors; /* -i flag */
108 Boolean beSilent; /* -s flag */
109 Boolean beVerbose; /* -v flag */
110 Boolean oldVars; /* variable substitution style */
111 Boolean checkEnvFirst; /* -e flag */
112 Lst envFirstVars; /* (-E) vars to override from env */
113 Boolean jobsRunning; /* TRUE if the jobs might be running */
115 static void MainParseArgs(int, char **);
116 char * chdir_verify_path(char *, char *);
117 static int ReadMakefile(void *, void *);
118 static void usage(void);
120 static char *curdir; /* startup directory */
121 static char *objdir; /* where we chdir'ed to */
125 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
128 MFLAGS_append(char *flag, char *arg)
131 Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
133 Var_Append(MAKEFLAGS, arg, VAR_GLOBAL);
135 Var_Append("MFLAGS", flag, VAR_GLOBAL);
137 Var_Append("MFLAGS", arg, VAR_GLOBAL);
142 * Parse a given argument vector. Called from main() and from
143 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
145 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
151 * Various global and local flags will be set depending on the flags
155 MainParseArgs(int argc, char **argv)
160 optind = 1; /* since we're called more than once */
161 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
162 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
165 if (chdir(optarg) == -1)
166 err(1, "chdir %s", optarg);
169 Var_Set(optarg, "1", VAR_GLOBAL);
170 MFLAGS_append("-D", optarg);
173 Parse_AddIncludeDir(optarg);
174 MFLAGS_append("-I", optarg);
177 (void)Lst_AtEnd(variables, (void *)optarg);
178 MFLAGS_append("-V", optarg);
185 MFLAGS_append("-B", NULL);
186 unsetenv("MAKE_JOBS_FIFO");
190 MFLAGS_append("-P", NULL);
194 MFLAGS_append("-S", NULL);
197 char *modules = optarg;
199 for (; *modules; ++modules)
217 if (modules[1] == '1') {
218 debug |= DEBUG_GRAPH1;
221 else if (modules[1] == '2') {
222 debug |= DEBUG_GRAPH2;
245 warnx("illegal argument to d option -- %c", *modules);
248 MFLAGS_append("-d", optarg);
252 p = emalloc(strlen(optarg) + 1);
254 Lst_AtEnd(envFirstVars, p);
255 MFLAGS_append("-E", optarg);
258 checkEnvFirst = TRUE;
259 MFLAGS_append("-e", NULL);
262 Lst_AtEnd(makefiles, optarg);
266 MFLAGS_append("-i", NULL);
272 maxJobs = strtol(optarg, &endptr, 10);
273 if (maxJobs <= 0 || *endptr != '\0') {
274 warnx("illegal number, -j argument -- %s",
278 MFLAGS_append("-j", optarg);
283 MFLAGS_append("-k", NULL);
286 Dir_AddDir(sysIncPath, optarg);
287 MFLAGS_append("-m", optarg);
291 MFLAGS_append("-n", NULL);
295 /* Kind of nonsensical, wot? */
296 MFLAGS_append("-q", NULL);
300 MFLAGS_append("-r", NULL);
304 MFLAGS_append("-s", NULL);
308 MFLAGS_append("-t", NULL);
312 MFLAGS_append("-v", NULL);
323 * See if the rest of the arguments are variable assignments and
324 * perform them if so. Else take them to be targets and stuff them
325 * on the end of the "create" list.
327 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
328 if (Parse_IsVar(*argv)) {
329 char *ptr = Var_Quote(*argv);
331 Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
334 Parse_DoVar(*argv, VAR_CMD);
337 Punt("illegal (null) argument.");
340 optind = 0; /* -flag... */
345 Lst_AtEnd(create, estrdup(*argv));
350 * Main_ParseArgLine --
351 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
352 * is encountered and by main() when reading the .MAKEFLAGS envariable.
353 * Takes a line of arguments and breaks it into its
354 * component words and passes those words and the number of them to the
355 * MainParseArgs function.
356 * The line should have all its leading whitespace removed.
362 * Only those that come from the various arguments.
365 Main_ParseArgLine(char *line)
367 char **argv; /* Manufactured argument vector */
368 int argc; /* Number of arguments in argv */
372 for (; *line == ' '; ++line)
377 argv = brk_string(line, &argc, TRUE);
378 MainParseArgs(argc, argv);
382 chdir_verify_path(char *path, char *obpath)
386 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
387 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
388 warn("warning: %s", path);
398 catch_child(int sig __unused)
403 * In lieu of a good way to prevent every possible looping in
404 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
405 * by make(1), to prevent a forkbomb from happening, in a dumb and
409 check_make_level(void)
411 #ifdef WANT_ENV_MKLVL
412 char *value = getenv(MKLVL_ENVVAR);
413 int level = (value == NULL) ? 0 : atoi(value);
416 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
417 } else if (level > MKLVL_MAXVAL) {
418 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
421 sprintf(new_value, "%d", level + 1);
422 setenv(MKLVL_ENVVAR, new_value, 1);
424 #endif /* WANT_ENV_MKLVL */
429 * The main function, for obvious reasons. Initializes variables
430 * and a few modules, then parses the arguments give it in the
431 * environment and on the command line. Reads the system makefile
432 * followed by either Makefile, makefile or the file given by the
433 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
434 * flags it has received by then uses either the Make or the Compat
435 * module to create the initial list of targets.
438 * If -q was given, exits -1 if anything was out-of-date. Else it exits
442 * The program exits when done. Targets are created. etc. etc. etc.
445 main(int argc, char **argv)
447 Lst targs; /* target nodes to create -- passed to Make_Init */
448 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
450 char *p, *p1, *path, *pathp;
451 char mdpath[MAXPATHLEN];
452 char obpath[MAXPATHLEN];
453 char cdpath[MAXPATHLEN];
454 char *machine = getenv("MACHINE");
455 char *machine_arch = getenv("MACHINE_ARCH");
456 char *machine_cpu = getenv("MACHINE_CPU");
457 Lst sysMkPath; /* Path of sys.mk */
458 char *cp = NULL, *start;
459 /* avoid faults on read-only strings */
460 static char syspath[] = _PATH_DEFSYSPATH;
464 * Catch SIGCHLD so that we get kicked out of select() when we
465 * need to look at a child. This is only known to matter for the
466 * -j case (perhaps without -P).
468 * XXX this is intentionally misplaced.
472 sigemptyset(&sa.sa_mask);
473 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
474 sa.sa_handler = catch_child;
475 sigaction(SIGCHLD, &sa, NULL);
482 * Turn off ENV to make ksh happier.
489 * get rid of resource limit on file descriptors
493 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
494 rl.rlim_cur != rl.rlim_max) {
495 rl.rlim_cur = rl.rlim_max;
496 setrlimit(RLIMIT_NOFILE, &rl);
502 * PC-98 kernel sets the `i386' string to the utsname.machine and
503 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
504 * we check machine.ispc98 and adjust the machine variable before
505 * using usname(3) below.
506 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
507 * __FreeBSD_version was defined as 300003. So, this check can
508 * safely be done with any kernel with version > 300003.
514 len = sizeof(ispc98);
515 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
522 * Get the name of this type of MACHINE from utsname
523 * so we can share an executable for similar machines.
524 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
526 * Note that while MACHINE is decided at run-time,
527 * MACHINE_ARCH is always known at compile time.
531 struct utsname utsname;
533 if (uname(&utsname) == -1)
535 machine = utsname.machine;
543 machine_arch = "unknown";
545 machine_arch = MACHINE_ARCH;
550 * Set machine_cpu to the minumum supported CPU revision based
551 * on the target architecture, if not already set.
554 if (!strcmp(machine_arch, "i386"))
555 machine_cpu = "i386";
556 else if (!strcmp(machine_arch, "alpha"))
559 machine_cpu = "unknown";
562 create = Lst_Init(FALSE);
563 makefiles = Lst_Init(FALSE);
564 envFirstVars = Lst_Init(FALSE);
566 variables = Lst_Init(FALSE);
567 beSilent = FALSE; /* Print commands as executed */
568 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
569 noExecute = FALSE; /* Execute all commands */
570 keepgoing = FALSE; /* Stop on error */
571 allPrecious = FALSE; /* Remove targets when interrupted */
572 queryFlag = FALSE; /* This is not just a check-run */
573 noBuiltins = FALSE; /* Read the built-in rules */
574 touchFlag = FALSE; /* Actually update targets */
575 usePipes = TRUE; /* Catch child output in pipes */
576 debug = 0; /* No debug verbosity, please. */
579 maxJobs = DEFMAXJOBS;
580 forceJobs = FALSE; /* No -j flag */
581 compatMake = FALSE; /* No compat mode */
584 * Initialize the parsing, directory and variable modules to prepare
585 * for the reading of inclusion paths and variable settings on the
588 Dir_Init(); /* Initialize directory structures so -I flags
589 * can be processed correctly */
590 Parse_Init(); /* Need to initialize the paths of #include
592 Var_Init(); /* As well as the lists of variables for
593 * parsing arguments */
597 * Initialize various variables.
598 * MAKE also gets this name, for compatibility
599 * .MAKEFLAGS gets set to the empty string just in case.
600 * MFLAGS also gets initialized empty, for compatibility.
602 Var_Set("MAKE", argv[0], VAR_GLOBAL);
603 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
604 Var_Set("MFLAGS", "", VAR_GLOBAL);
605 Var_Set("MACHINE", machine, VAR_GLOBAL);
606 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
607 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
609 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
613 * First snag any flags out of the MAKE environment variable.
614 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
615 * in a different format).
617 Main_ParseArgLine(getenv("MAKEFLAGS"));
619 MainParseArgs(argc, argv);
622 * Find where we are...
623 * All this code is so that we know where we are when we start up
624 * on a different machine with pmake.
627 if (getcwd(curdir, MAXPATHLEN) == NULL)
630 if (stat(curdir, &sa) == -1)
631 err(2, "%s", curdir);
634 * The object directory location is determined using the
635 * following order of preference:
637 * 1. MAKEOBJDIRPREFIX`cwd`
639 * 3. _PATH_OBJDIR.${MACHINE}
641 * 5. _PATH_OBJDIRPREFIX`cwd`
643 * If one of the first two fails, use the current directory.
644 * If the remaining three all fail, use the current directory.
646 * Once things are initted,
647 * have to add the original directory to the search path,
648 * and modify the paths for the Makefiles apropriately. The
649 * current directory is also placed as a variable for make scripts.
651 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
652 if (!(path = getenv("MAKEOBJDIR"))) {
654 pathp = _PATH_OBJDIRPREFIX;
655 snprintf(mdpath, MAXPATHLEN, "%s.%s",
657 if (!(objdir = chdir_verify_path(mdpath, obpath)))
658 if (!(objdir=chdir_verify_path(path, obpath))) {
659 snprintf(mdpath, MAXPATHLEN,
660 "%s%s", pathp, curdir);
661 if (!(objdir=chdir_verify_path(mdpath,
666 else if (!(objdir = chdir_verify_path(path, obpath)))
670 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
671 if (!(objdir = chdir_verify_path(mdpath, obpath)))
674 Dir_InitDot(); /* Initialize the "." directory */
675 if (objdir != curdir)
676 Dir_AddDir(dirSearchPath, curdir);
677 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
678 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
679 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
681 if (getenv("MAKE_JOBS_FIFO") != NULL)
684 * Be compatible if user did not specify -j and did not explicitly
685 * turned compatibility on
687 if (!compatMake && !forceJobs)
691 * Initialize archive, target and suffix modules in preparation for
692 * parsing the makefile(s)
702 * Set up the .TARGETS variable to contain the list of targets to be
703 * created. If none specified, make the variable empty -- the parser
704 * will fill the thing in with the default or .MAIN target.
706 if (!Lst_IsEmpty(create)) {
709 for (ln = Lst_First(create); ln != NULL; ln = Lst_Succ(ln)) {
710 char *name = Lst_Datum(ln);
712 Var_Append(".TARGETS", name, VAR_GLOBAL);
715 Var_Set(".TARGETS", "", VAR_GLOBAL);
719 * If no user-supplied system path was given (through the -m option)
720 * add the directories from the DEFSYSPATH (more than one may be given
721 * as dir1:...:dirn) to the system include path.
723 if (Lst_IsEmpty(sysIncPath)) {
724 for (start = syspath; *start != '\0'; start = cp) {
725 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
728 Dir_AddDir(sysIncPath, start);
731 Dir_AddDir(sysIncPath, start);
737 * Read in the built-in rules first, followed by the specified
738 * makefile, if it was (makefile != (char *) NULL), or the default
739 * Makefile and makefile, in that order, if it wasn't.
744 sysMkPath = Lst_Init(FALSE);
745 Dir_Expand(_PATH_DEFSYSMK, sysIncPath, sysMkPath);
746 if (Lst_IsEmpty(sysMkPath))
747 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
748 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
750 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
753 if (!Lst_IsEmpty(makefiles)) {
756 ln = Lst_Find(makefiles, NULL, ReadMakefile);
758 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
759 } else if (!ReadMakefile("BSDmakefile", NULL))
760 if (!ReadMakefile("makefile", NULL))
761 ReadMakefile("Makefile", NULL);
763 ReadMakefile(".depend", NULL);
765 /* Install all the flags into the MAKE envariable. */
766 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
767 setenv("MAKEFLAGS", p, 1);
771 * For compatibility, look at the directories in the VPATH variable
772 * and add them to the search path, if the variable is defined. The
773 * variable's value is in the same format as the PATH envariable, i.e.
774 * <directory>:<directory>:<directory>...
776 if (Var_Exists("VPATH", VAR_CMD)) {
779 * GCC stores string constants in read-only memory, but
780 * Var_Subst will want to write this thing, so store it
783 static char VPATH[] = "${VPATH}";
785 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
788 /* skip to end of directory */
789 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
791 /* Save terminator character so know when to stop */
794 /* Add directory to search path */
795 Dir_AddDir(dirSearchPath, path);
798 } while (savec == ':');
803 * Now that all search paths have been read for suffixes et al, it's
804 * time to add the default search path to their lists...
808 /* print the initial graph, if the user requested it */
812 /* print the values of any variables requested by the user */
813 if (!Lst_IsEmpty(variables)) {
816 for (ln = Lst_First(variables); ln != NULL;
820 p1 = emalloc(strlen(Lst_Datum(ln)) + 1 + 3);
821 /* This sprintf is safe, because of the malloc above */
822 sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
823 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
825 value = Var_Value(Lst_Datum(ln),
828 printf("%s\n", value ? value : "");
835 * Have now read the entire graph and need to make a list of targets
836 * to create. If none was given on the command line, we consult the
837 * parsing module to find the main target(s) to create.
839 if (Lst_IsEmpty(create))
840 targs = Parse_MainName();
842 targs = Targ_FindList(create, TARG_CREATE);
846 * Initialize job module before traversing the graph, now that
847 * any .BEGIN and .END targets have been read. This is done
848 * only if the -q flag wasn't given (to prevent the .BEGIN from
849 * being executed should it exist).
856 /* Traverse the graph, checking on all the targets */
857 outOfDate = Make_Run(targs);
860 * Compat_Init will take care of creating all the targets as
861 * well as initializing the module.
866 Lst_Destroy(targs, NOFREE);
869 Lst_Destroy(variables, NOFREE);
870 Lst_Destroy(makefiles, NOFREE);
871 Lst_Destroy(create, free);
873 /* print the graph now it's been processed if the user requested it */
885 if (queryFlag && outOfDate)
893 * Open and parse the given makefile.
896 * TRUE if ok. FALSE if couldn't open file.
902 ReadMakefile(void *p, void *q __unused)
904 char *fname; /* makefile to read */
906 char *name, path[MAXPATHLEN];
912 if (!strcmp(fname, "-")) {
913 Parse_File("(stdin)", stdin);
914 Var_Set("MAKEFILE", "", VAR_GLOBAL);
916 setMAKEFILE = strcmp(fname, ".depend");
918 /* if we've chdir'd, rebuild the path name */
919 if (curdir != objdir && *fname != '/') {
920 snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
922 * XXX The realpath stuff breaks relative includes
923 * XXX in some cases. The problem likely is in
924 * XXX parse.c where it does special things in
925 * XXX ParseDoInclude if the file is relateive
926 * XXX or absolute and not a system file. There
927 * XXX it assumes that if the current file that's
928 * XXX being included is absolute, that any files
929 * XXX that it includes shouldn't do the -I path
930 * XXX stuff, which is inconsistant with historical
931 * XXX behavior. However, I can't pentrate the mists
932 * XXX further, so I'm putting this workaround in
933 * XXX here until such time as the underlying bug
936 #if THIS_BREAKS_THINGS
937 if (realpath(path, path) != NULL &&
938 (stream = fopen(path, "r")) != NULL) {
943 } else if (realpath(fname, path) != NULL) {
946 if ((stream = fopen(fname, "r")) != NULL)
950 if ((stream = fopen(path, "r")) != NULL) {
957 if ((stream = fopen(fname, "r")) != NULL)
961 /* look in -I and system include directories. */
962 name = Dir_FindFile(fname, parseIncPath);
964 name = Dir_FindFile(fname, sysIncPath);
965 if (!name || !(stream = fopen(name, "r")))
967 MAKEFILE = fname = name;
969 * set the MAKEFILE variable desired by System V fans -- the
970 * placement of the setting here means it gets set to the last
971 * makefile specified, as it is set by SysV make.
975 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
976 Parse_File(fname, stream);
984 * Execute the command in cmd, and return the output of that command
988 * A string containing the output of the command, or the empty string
989 * If error is not NULL, it contains the reason for the command failure
992 * The string must be freed by the caller.
995 Cmd_Exec(char *cmd, char **error)
997 char *args[4]; /* Args for invoking the shell */
998 int fds[2]; /* Pipe streams */
999 int cpid; /* Child PID */
1000 int pid; /* PID from wait() */
1001 char *res; /* result */
1002 int status; /* command exit status */
1003 Buffer buf; /* buffer to store the result */
1010 if (shellPath == NULL)
1013 * Set up arguments for shell
1015 args[0] = shellName;
1021 * Open a pipe for fetching its output
1023 if (pipe(fds) == -1) {
1024 *error = "Couldn't create pipe for \"%s\"";
1031 switch (cpid = vfork()) {
1034 * Close input side of pipe
1039 * Duplicate the output stream to the shell's output, then
1040 * shut the extra thing down. Note we don't fetch the error
1041 * stream...why not? Why?
1046 execv(shellPath, args);
1051 *error = "Couldn't exec \"%s\"";
1056 * No need for the writing half
1060 buf = Buf_Init(MAKE_BSIZE);
1063 char result[BUFSIZ];
1064 rcnt = read(fds[0], result, sizeof(result));
1066 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1067 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1069 * Close the input side of the pipe.
1074 * Wait for the process to exit.
1076 while (((pid = wait(&status)) != cpid) && (pid >= 0))
1080 *error = "Error reading shell's output for \"%s\"";
1082 res = (char *)Buf_GetAll(buf, &blen);
1083 Buf_Destroy(buf, FALSE);
1086 *error = "\"%s\" returned non-zero status";
1089 * Null-terminate the result, convert newlines to spaces and
1090 * install it in the variable.
1093 cp = &res[blen] - 1;
1097 * A final newline is just stripped
1118 * exit with usage message
1123 fprintf(stderr, "%s\n%s\n%s\n",
1124 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1125 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1126 " [-m directory] [-V variable] [variable=value] [target ...]");