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
93 #define MKLVL_MAXVAL 500
94 #define MKLVL_ENVVAR "__MKLVL__"
96 #define MAKEFLAGS ".MAKEFLAGS"
98 Lst create; /* Targets to be made */
99 time_t now; /* Time at start of make */
100 GNode *DEFAULT; /* .DEFAULT node */
101 Boolean allPrecious; /* .PRECIOUS given on line by itself */
103 static Boolean noBuiltins; /* -r flag */
104 static Lst makefiles; /* ordered list of makefiles to read */
105 static Boolean expandVars; /* fully expand printed variables */
106 static Lst variables; /* list of variables to print */
107 int maxJobs; /* -j argument */
108 static Boolean forceJobs; /* -j argument given */
109 Boolean compatMake; /* -B argument */
110 Boolean debug; /* -d flag */
111 Boolean noExecute; /* -n flag */
112 Boolean keepgoing; /* -k flag */
113 Boolean queryFlag; /* -q flag */
114 Boolean touchFlag; /* -t flag */
115 Boolean usePipes; /* !-P flag */
116 Boolean ignoreErrors; /* -i flag */
117 Boolean beSilent; /* -s flag */
118 Boolean beVerbose; /* -v flag */
119 Boolean oldVars; /* variable substitution style */
120 Boolean checkEnvFirst; /* -e flag */
121 Lst envFirstVars; /* (-E) vars to override from env */
122 Boolean jobsRunning; /* TRUE if the jobs might be running */
124 static void MainParseArgs(int, char **);
125 char * chdir_verify_path(char *, char *);
126 static int ReadMakefile(void *, void *);
127 static void usage(void);
129 static char *curdir; /* startup directory */
130 static char *objdir; /* where we chdir'ed to */
133 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
136 MFLAGS_append(char *flag, char *arg)
138 Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
140 Var_Append(MAKEFLAGS, arg, VAR_GLOBAL);
142 Var_Append("MFLAGS", flag, VAR_GLOBAL);
144 Var_Append("MFLAGS", arg, VAR_GLOBAL);
149 * Parse a given argument vector. Called from main() and from
150 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
152 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
158 * Various global and local flags will be set depending on the flags
162 MainParseArgs(int argc, char **argv)
167 optind = 1; /* since we're called more than once */
168 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
169 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
172 if (chdir(optarg) == -1)
173 err(1, "chdir %s", optarg);
176 Var_Set(optarg, "1", VAR_GLOBAL);
177 MFLAGS_append("-D", optarg);
180 Parse_AddIncludeDir(optarg);
181 MFLAGS_append("-I", optarg);
184 (void)Lst_AtEnd(variables, (void *)optarg);
185 MFLAGS_append("-V", optarg);
192 MFLAGS_append("-B", NULL);
193 unsetenv("MAKE_JOBS_FIFO");
197 MFLAGS_append("-P", NULL);
201 MFLAGS_append("-S", NULL);
204 char *modules = optarg;
206 for (; *modules; ++modules)
224 if (modules[1] == '1') {
225 debug |= DEBUG_GRAPH1;
228 else if (modules[1] == '2') {
229 debug |= DEBUG_GRAPH2;
252 warnx("illegal argument to d option -- %c", *modules);
255 MFLAGS_append("-d", optarg);
259 p = emalloc(strlen(optarg) + 1);
260 (void)strcpy(p, optarg);
261 (void)Lst_AtEnd(envFirstVars, (void *)p);
262 MFLAGS_append("-E", optarg);
265 checkEnvFirst = TRUE;
266 MFLAGS_append("-e", NULL);
269 (void)Lst_AtEnd(makefiles, (void *)optarg);
273 MFLAGS_append("-i", NULL);
279 maxJobs = strtol(optarg, &endptr, 10);
280 if (maxJobs <= 0 || *endptr != '\0') {
281 warnx("illegal number, -j argument -- %s",
285 MFLAGS_append("-j", optarg);
290 MFLAGS_append("-k", NULL);
293 Dir_AddDir(sysIncPath, optarg);
294 MFLAGS_append("-m", optarg);
298 MFLAGS_append("-n", NULL);
302 /* Kind of nonsensical, wot? */
303 MFLAGS_append("-q", NULL);
307 MFLAGS_append("-r", NULL);
311 MFLAGS_append("-s", NULL);
315 MFLAGS_append("-t", NULL);
319 MFLAGS_append("-v", NULL);
330 * See if the rest of the arguments are variable assignments and
331 * perform them if so. Else take them to be targets and stuff them
332 * on the end of the "create" list.
334 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
335 if (Parse_IsVar(*argv)) {
336 char *ptr = Var_Quote(*argv);
338 Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
341 Parse_DoVar(*argv, VAR_CMD);
344 Punt("illegal (null) argument.");
347 optind = 0; /* -flag... */
352 (void)Lst_AtEnd(create, (void *)estrdup(*argv));
357 * Main_ParseArgLine --
358 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
359 * is encountered and by main() when reading the .MAKEFLAGS envariable.
360 * Takes a line of arguments and breaks it into its
361 * component words and passes those words and the number of them to the
362 * MainParseArgs function.
363 * The line should have all its leading whitespace removed.
369 * Only those that come from the various arguments.
372 Main_ParseArgLine(char *line)
374 char **argv; /* Manufactured argument vector */
375 int argc; /* Number of arguments in argv */
379 for (; *line == ' '; ++line)
384 argv = brk_string(line, &argc, TRUE);
385 MainParseArgs(argc, argv);
389 chdir_verify_path(char *path, char *obpath)
393 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
394 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
395 warn("warning: %s", path);
405 catch_child(int sig __unused)
410 * In lieu of a good way to prevent every possible looping in
411 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
412 * by make(1), to prevent a forkbomb from happening, in a dumb and
416 check_make_level(void)
418 #ifdef WANT_ENV_MKLVL
419 char *value = getenv(MKLVL_ENVVAR);
420 int level = (value == NULL) ? 0 : atoi(value);
423 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
424 } else if (level > MKLVL_MAXVAL) {
425 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
428 sprintf(new_value, "%d", level + 1);
429 setenv(MKLVL_ENVVAR, new_value, 1);
431 #endif /* WANT_ENV_MKLVL */
436 * The main function, for obvious reasons. Initializes variables
437 * and a few modules, then parses the arguments give it in the
438 * environment and on the command line. Reads the system makefile
439 * followed by either Makefile, makefile or the file given by the
440 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
441 * flags it has received by then uses either the Make or the Compat
442 * module to create the initial list of targets.
445 * If -q was given, exits -1 if anything was out-of-date. Else it exits
449 * The program exits when done. Targets are created. etc. etc. etc.
452 main(int argc, char **argv)
454 Lst targs; /* target nodes to create -- passed to Make_Init */
455 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
457 char *p, *p1, *path, *pathp;
458 char mdpath[MAXPATHLEN];
459 char obpath[MAXPATHLEN];
460 char cdpath[MAXPATHLEN];
461 char *machine = getenv("MACHINE");
462 char *machine_arch = getenv("MACHINE_ARCH");
463 char *machine_cpu = getenv("MACHINE_CPU");
464 Lst sysMkPath; /* Path of sys.mk */
465 char *cp = NULL, *start;
466 /* avoid faults on read-only strings */
467 static char syspath[] = _PATH_DEFSYSPATH;
471 * Catch SIGCHLD so that we get kicked out of select() when we
472 * need to look at a child. This is only known to matter for the
473 * -j case (perhaps without -P).
475 * XXX this is intentionally misplaced.
479 sigemptyset(&sa.sa_mask);
480 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
481 sa.sa_handler = catch_child;
482 sigaction(SIGCHLD, &sa, NULL);
489 * Turn off ENV to make ksh happier.
496 * get rid of resource limit on file descriptors
500 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
501 rl.rlim_cur != rl.rlim_max) {
502 rl.rlim_cur = rl.rlim_max;
503 (void) setrlimit(RLIMIT_NOFILE, &rl);
509 * PC-98 kernel sets the `i386' string to the utsname.machine and
510 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
511 * we check machine.ispc98 and adjust the machine variable before
512 * using usname(3) below.
513 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
514 * __FreeBSD_version was defined as 300003. So, this check can
515 * safely be done with any kernel with version > 300003.
521 len = sizeof(ispc98);
522 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
529 * Get the name of this type of MACHINE from utsname
530 * so we can share an executable for similar machines.
531 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
533 * Note that while MACHINE is decided at run-time,
534 * MACHINE_ARCH is always known at compile time.
538 struct utsname utsname;
540 if (uname(&utsname) == -1)
542 machine = utsname.machine;
550 machine_arch = "unknown";
552 machine_arch = MACHINE_ARCH;
557 * Set machine_cpu to the minumum supported CPU revision based
558 * on the target architecture, if not already set.
561 if (!strcmp(machine_arch, "i386"))
562 machine_cpu = "i386";
563 else if (!strcmp(machine_arch, "alpha"))
566 machine_cpu = "unknown";
569 create = Lst_Init(FALSE);
570 makefiles = Lst_Init(FALSE);
571 envFirstVars = Lst_Init(FALSE);
573 variables = Lst_Init(FALSE);
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 */
592 * Initialize the parsing, directory and variable modules to prepare
593 * for the reading of inclusion paths and variable settings on the
596 Dir_Init(); /* Initialize directory structures so -I flags
597 * can be processed correctly */
598 Parse_Init(); /* Need to initialize the paths of #include
600 Var_Init(); /* As well as the lists of variables for
601 * parsing arguments */
605 * Initialize various variables.
606 * MAKE also gets this name, for compatibility
607 * .MAKEFLAGS gets set to the empty string just in case.
608 * MFLAGS also gets initialized empty, for compatibility.
610 Var_Set("MAKE", argv[0], VAR_GLOBAL);
611 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
612 Var_Set("MFLAGS", "", VAR_GLOBAL);
613 Var_Set("MACHINE", machine, VAR_GLOBAL);
614 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
615 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
617 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
621 * First snag any flags out of the MAKE environment variable.
622 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
623 * in a different format).
625 Main_ParseArgLine(getenv("MAKEFLAGS"));
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);
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;
718 char *name = (char *)Lst_Datum(ln);
720 Var_Append(".TARGETS", name, VAR_GLOBAL);
723 Var_Set(".TARGETS", "", VAR_GLOBAL);
727 * If no user-supplied system path was given (through the -m option)
728 * add the directories from the DEFSYSPATH (more than one may be given
729 * as dir1:...:dirn) to the system include path.
731 if (Lst_IsEmpty(sysIncPath)) {
732 for (start = syspath; *start != '\0'; start = cp) {
733 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
736 Dir_AddDir(sysIncPath, start);
739 Dir_AddDir(sysIncPath, start);
745 * Read in the built-in rules first, followed by the specified
746 * makefile, if it was (makefile != (char *) NULL), or the default
747 * Makefile and makefile, in that order, if it wasn't.
752 sysMkPath = Lst_Init (FALSE);
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, (void *)NULL, ReadMakefile);
758 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
761 if (!Lst_IsEmpty(makefiles)) {
764 ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
766 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
767 } else if (!ReadMakefile("BSDmakefile", NULL))
768 if (!ReadMakefile("makefile", NULL))
769 (void)ReadMakefile("Makefile", NULL);
771 (void)ReadMakefile(".depend", NULL);
773 /* Install all the flags into the MAKE envariable. */
774 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
775 setenv("MAKEFLAGS", p, 1);
779 * For compatibility, look at the directories in the VPATH variable
780 * and add them to the search path, if the variable is defined. The
781 * variable's value is in the same format as the PATH envariable, i.e.
782 * <directory>:<directory>:<directory>...
784 if (Var_Exists("VPATH", VAR_CMD)) {
787 * GCC stores string constants in read-only memory, but
788 * Var_Subst will want to write this thing, so store it
791 static char VPATH[] = "${VPATH}";
793 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
796 /* skip to end of directory */
797 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
799 /* Save terminator character so know when to stop */
802 /* Add directory to search path */
803 Dir_AddDir(dirSearchPath, path);
806 } while (savec == ':');
811 * Now that all search paths have been read for suffixes et al, it's
812 * time to add the default search path to their lists...
816 /* print the initial graph, if the user requested it */
820 /* print the values of any variables requested by the user */
821 if (!Lst_IsEmpty(variables)) {
824 for (ln = Lst_First(variables); ln != NULL;
828 p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
829 /* This sprintf is safe, because of the malloc above */
830 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
831 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
833 value = Var_Value((char *)Lst_Datum(ln),
836 printf("%s\n", value ? value : "");
843 * Have now read the entire graph and need to make a list of targets
844 * to create. If none was given on the command line, we consult the
845 * parsing module to find the main target(s) to create.
847 if (Lst_IsEmpty(create))
848 targs = Parse_MainName();
850 targs = Targ_FindList(create, TARG_CREATE);
854 * Initialize job module before traversing the graph, now that
855 * any .BEGIN and .END targets have been read. This is done
856 * only if the -q flag wasn't given (to prevent the .BEGIN from
857 * being executed should it exist).
864 /* Traverse the graph, checking on all the targets */
865 outOfDate = Make_Run(targs);
868 * Compat_Init will take care of creating all the targets as
869 * well as initializing the module.
874 Lst_Destroy(targs, NOFREE);
877 Lst_Destroy(variables, NOFREE);
878 Lst_Destroy(makefiles, NOFREE);
879 Lst_Destroy(create, (void (*)(void *)) free);
881 /* print the graph now it's been processed if the user requested it */
893 if (queryFlag && outOfDate)
901 * Open and parse the given makefile.
904 * TRUE if ok. FALSE if couldn't open file.
910 ReadMakefile(void *p, void *q __unused)
912 char *fname; /* makefile to read */
914 char *name, path[MAXPATHLEN];
920 if (!strcmp(fname, "-")) {
921 Parse_File("(stdin)", stdin);
922 Var_Set("MAKEFILE", "", VAR_GLOBAL);
924 setMAKEFILE = strcmp(fname, ".depend");
926 /* if we've chdir'd, rebuild the path name */
927 if (curdir != objdir && *fname != '/') {
928 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
930 * XXX The realpath stuff breaks relative includes
931 * XXX in some cases. The problem likely is in
932 * XXX parse.c where it does special things in
933 * XXX ParseDoInclude if the file is relateive
934 * XXX or absolute and not a system file. There
935 * XXX it assumes that if the current file that's
936 * XXX being included is absolute, that any files
937 * XXX that it includes shouldn't do the -I path
938 * XXX stuff, which is inconsistant with historical
939 * XXX behavior. However, I can't pentrate the mists
940 * XXX further, so I'm putting this workaround in
941 * XXX here until such time as the underlying bug
944 #if THIS_BREAKS_THINGS
945 if (realpath(path, path) != NULL &&
946 (stream = fopen(path, "r")) != NULL) {
951 } else if (realpath(fname, path) != NULL) {
954 if ((stream = fopen(fname, "r")) != NULL)
958 if ((stream = fopen(path, "r")) != NULL) {
965 if ((stream = fopen(fname, "r")) != NULL)
969 /* look in -I and system include directories. */
970 name = Dir_FindFile(fname, parseIncPath);
972 name = Dir_FindFile(fname, sysIncPath);
973 if (!name || !(stream = fopen(name, "r")))
975 MAKEFILE = fname = name;
977 * set the MAKEFILE variable desired by System V fans -- the
978 * placement of the setting here means it gets set to the last
979 * makefile specified, as it is set by SysV make.
983 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
984 Parse_File(fname, stream);
985 (void)fclose(stream);
992 * Execute the command in cmd, and return the output of that command
996 * A string containing the output of the command, or the empty string
997 * If error is not NULL, it contains the reason for the command failure
1000 * The string must be freed by the caller.
1003 Cmd_Exec(char *cmd, char **error)
1005 char *args[4]; /* Args for invoking the shell */
1006 int fds[2]; /* Pipe streams */
1007 int cpid; /* Child PID */
1008 int pid; /* PID from wait() */
1009 char *res; /* result */
1010 int status; /* command exit status */
1011 Buffer buf; /* buffer to store the result */
1017 if (shellPath == NULL)
1020 * Set up arguments for shell
1022 args[0] = shellName;
1028 * Open a pipe for fetching its output
1030 if (pipe(fds) == -1) {
1031 *error = "Couldn't create pipe for \"%s\"";
1038 switch (cpid = vfork()) {
1041 * Close input side of pipe
1043 (void) close(fds[0]);
1046 * Duplicate the output stream to the shell's output, then
1047 * shut the extra thing down. Note we don't fetch the error
1048 * stream...why not? Why?
1050 (void) dup2(fds[1], 1);
1051 (void) close(fds[1]);
1053 (void) execv(shellPath, args);
1058 *error = "Couldn't exec \"%s\"";
1063 * No need for the writing half
1065 (void) close(fds[1]);
1067 buf = Buf_Init (MAKE_BSIZE);
1070 char result[BUFSIZ];
1071 cc = read(fds[0], result, sizeof(result));
1073 Buf_AddBytes(buf, cc, (Byte *) result);
1075 while (cc > 0 || (cc == -1 && errno == EINTR));
1078 * Close the input side of the pipe.
1080 (void) close(fds[0]);
1083 * Wait for the process to exit.
1085 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1089 *error = "Error reading shell's output for \"%s\"";
1091 res = (char *)Buf_GetAll (buf, &cc);
1092 Buf_Destroy (buf, FALSE);
1095 *error = "\"%s\" returned non-zero status";
1098 * Null-terminate the result, convert newlines to spaces and
1099 * install it in the variable.
1106 * A final newline is just stripped
1127 * exit with usage message
1132 (void)fprintf(stderr, "%s\n%s\n%s\n",
1133 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1134 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1135 " [-m directory] [-V variable] [variable=value] [target ...]");