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.39 2004/12/17 21:09:04 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 /* Targets to be made */
90 Lst create = Lst_Initializer(create);
92 time_t now; /* Time at start of make */
93 GNode *DEFAULT; /* .DEFAULT node */
94 Boolean allPrecious; /* .PRECIOUS given on line by itself */
96 static Boolean noBuiltins; /* -r flag */
98 /* ordered list of makefiles to read */
99 static Lst makefiles = Lst_Initializer(makefiles);
101 static Boolean expandVars; /* fully expand printed variables */
103 /* list of variables to print */
104 static Lst variables = Lst_Initializer(variables);
106 int maxJobs; /* -j argument */
107 static Boolean forceJobs; /* -j argument given */
108 Boolean compatMake; /* -B argument */
109 Boolean debug; /* -d flag */
110 Boolean noExecute; /* -n flag */
111 Boolean keepgoing; /* -k flag */
112 Boolean queryFlag; /* -q flag */
113 Boolean touchFlag; /* -t flag */
114 Boolean usePipes; /* !-P flag */
115 Boolean ignoreErrors; /* -i flag */
116 Boolean beSilent; /* -s flag */
117 Boolean beVerbose; /* -v flag */
118 Boolean oldVars; /* variable substitution style */
119 Boolean checkEnvFirst; /* -e flag */
121 /* (-E) vars to override from env */
122 Lst envFirstVars = Lst_Initializer(envFirstVars);
124 Boolean jobsRunning; /* TRUE if the jobs might be running */
126 static void MainParseArgs(int, char **);
127 char * chdir_verify_path(char *, char *);
128 static int ReadMakefile(const void *, const void *);
129 static void usage(void);
131 static char *curdir; /* startup directory */
132 static char *objdir; /* where we chdir'ed to */
135 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
138 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)
169 optind = 1; /* since we're called more than once */
170 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
171 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
174 if (chdir(optarg) == -1)
175 err(1, "chdir %s", optarg);
178 Var_Set(optarg, "1", VAR_GLOBAL);
179 MFLAGS_append("-D", optarg);
182 Parse_AddIncludeDir(optarg);
183 MFLAGS_append("-I", optarg);
186 Lst_AtEnd(&variables, estrdup(optarg));
187 MFLAGS_append("-V", optarg);
194 MFLAGS_append("-B", NULL);
195 unsetenv("MAKE_JOBS_FIFO");
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 Lst_AtEnd(&envFirstVars, estrdup(optarg));
262 MFLAGS_append("-E", optarg);
265 checkEnvFirst = TRUE;
266 MFLAGS_append("-e", NULL);
269 Lst_AtEnd(&makefiles, estrdup(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 Lst_AtEnd(&create, 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 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
456 char *p, *p1, *path, *pathp;
457 char mdpath[MAXPATHLEN];
458 char obpath[MAXPATHLEN];
459 char cdpath[MAXPATHLEN];
460 char *machine = getenv("MACHINE");
461 char *machine_arch = getenv("MACHINE_ARCH");
462 char *machine_cpu = getenv("MACHINE_CPU");
463 char *cp = NULL, *start;
464 /* avoid faults on read-only strings */
465 static char syspath[] = _PATH_DEFSYSPATH;
469 * Catch SIGCHLD so that we get kicked out of select() when we
470 * need to look at a child. This is only known to matter for the
471 * -j case (perhaps without -P).
473 * XXX this is intentionally misplaced.
477 sigemptyset(&sa.sa_mask);
478 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
479 sa.sa_handler = catch_child;
480 sigaction(SIGCHLD, &sa, NULL);
487 * Turn off ENV to make ksh happier.
494 * get rid of resource limit on file descriptors
498 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
499 rl.rlim_cur != rl.rlim_max) {
500 rl.rlim_cur = rl.rlim_max;
501 setrlimit(RLIMIT_NOFILE, &rl);
507 * PC-98 kernel sets the `i386' string to the utsname.machine and
508 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
509 * we check machine.ispc98 and adjust the machine variable before
510 * using usname(3) below.
511 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
512 * __FreeBSD_version was defined as 300003. So, this check can
513 * safely be done with any kernel with version > 300003.
519 len = sizeof(ispc98);
520 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
527 * Get the name of this type of MACHINE from utsname
528 * so we can share an executable for similar machines.
529 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
531 * Note that while MACHINE is decided at run-time,
532 * MACHINE_ARCH is always known at compile time.
536 struct utsname utsname;
538 if (uname(&utsname) == -1)
540 machine = utsname.machine;
548 machine_arch = "unknown";
550 machine_arch = MACHINE_ARCH;
555 * Set machine_cpu to the minumum supported CPU revision based
556 * on the target architecture, if not already set.
559 if (!strcmp(machine_arch, "i386"))
560 machine_cpu = "i386";
561 else if (!strcmp(machine_arch, "alpha"))
564 machine_cpu = "unknown";
568 beSilent = FALSE; /* Print commands as executed */
569 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
570 noExecute = FALSE; /* Execute all commands */
571 keepgoing = FALSE; /* Stop on error */
572 allPrecious = FALSE; /* Remove targets when interrupted */
573 queryFlag = FALSE; /* This is not just a check-run */
574 noBuiltins = FALSE; /* Read the built-in rules */
575 touchFlag = FALSE; /* Actually update targets */
576 usePipes = TRUE; /* Catch child output in pipes */
577 debug = 0; /* No debug verbosity, please. */
580 maxJobs = DEFMAXJOBS;
581 forceJobs = FALSE; /* No -j flag */
582 compatMake = FALSE; /* No compat mode */
585 * Initialize the parsing, directory and variable modules to prepare
586 * for the reading of inclusion paths and variable settings on the
589 Dir_Init(); /* Initialize directory structures so -I flags
590 * can be processed correctly */
591 Parse_Init(); /* Need to initialize the paths of #include
593 Var_Init(); /* As well as the lists of variables for
594 * parsing arguments */
598 * Initialize various variables.
599 * MAKE also gets this name, for compatibility
600 * .MAKEFLAGS gets set to the empty string just in case.
601 * MFLAGS also gets initialized empty, for compatibility.
603 Var_Set("MAKE", argv[0], VAR_GLOBAL);
604 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
605 Var_Set("MFLAGS", "", VAR_GLOBAL);
606 Var_Set("MACHINE", machine, VAR_GLOBAL);
607 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
608 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
610 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
614 * First snag any flags out of the MAKE environment variable.
615 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
616 * in a different format).
618 Main_ParseArgLine(getenv("MAKEFLAGS"));
620 MainParseArgs(argc, argv);
623 * Find where we are...
624 * All this code is so that we know where we are when we start up
625 * on a different machine with pmake.
628 if (getcwd(curdir, MAXPATHLEN) == NULL)
631 if (stat(curdir, &sa) == -1)
632 err(2, "%s", curdir);
635 * The object directory location is determined using the
636 * following order of preference:
638 * 1. MAKEOBJDIRPREFIX`cwd`
640 * 3. _PATH_OBJDIR.${MACHINE}
642 * 5. _PATH_OBJDIRPREFIX`cwd`
644 * If one of the first two fails, use the current directory.
645 * If the remaining three all fail, use the current directory.
647 * Once things are initted,
648 * have to add the original directory to the search path,
649 * and modify the paths for the Makefiles apropriately. The
650 * current directory is also placed as a variable for make scripts.
652 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
653 if (!(path = getenv("MAKEOBJDIR"))) {
655 pathp = _PATH_OBJDIRPREFIX;
656 snprintf(mdpath, MAXPATHLEN, "%s.%s",
658 if (!(objdir = chdir_verify_path(mdpath, obpath)))
659 if (!(objdir=chdir_verify_path(path, obpath))) {
660 snprintf(mdpath, MAXPATHLEN,
661 "%s%s", pathp, curdir);
662 if (!(objdir=chdir_verify_path(mdpath,
667 else if (!(objdir = chdir_verify_path(path, obpath)))
671 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
672 if (!(objdir = chdir_verify_path(mdpath, obpath)))
675 Dir_InitDot(); /* Initialize the "." directory */
676 if (objdir != curdir)
677 Dir_AddDir(&dirSearchPath, curdir);
678 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
679 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
680 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
682 if (getenv("MAKE_JOBS_FIFO") != NULL)
685 * Be compatible if user did not specify -j and did not explicitly
686 * turned compatibility on
688 if (!compatMake && !forceJobs)
692 * Initialize archive, target and suffix modules in preparation for
693 * parsing the makefile(s)
703 * Set up the .TARGETS variable to contain the list of targets to be
704 * created. If none specified, make the variable empty -- the parser
705 * will fill the thing in with the default or .MAIN target.
707 if (!Lst_IsEmpty(&create)) {
710 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
711 char *name = Lst_Datum(ln);
713 Var_Append(".TARGETS", name, VAR_GLOBAL);
716 Var_Set(".TARGETS", "", VAR_GLOBAL);
720 * If no user-supplied system path was given (through the -m option)
721 * add the directories from the DEFSYSPATH (more than one may be given
722 * as dir1:...:dirn) to the system include path.
724 if (Lst_IsEmpty(&sysIncPath)) {
725 for (start = syspath; *start != '\0'; start = cp) {
726 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
729 Dir_AddDir(&sysIncPath, start);
732 Dir_AddDir(&sysIncPath, start);
738 * Read in the built-in rules first, followed by the specified
739 * makefile, if it was (makefile != (char *) NULL), or the default
740 * Makefile and makefile, in that order, if it wasn't.
744 Lst sysMkPath = Lst_Initializer(sysMkPath);
747 Dir_Expand(_PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
748 if (Lst_IsEmpty(&sysMkPath))
749 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
750 ln = Lst_Find(&sysMkPath, NULL, ReadMakefile);
752 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
753 Lst_Destroy(&sysMkPath, free);
756 if (!Lst_IsEmpty(&makefiles)) {
759 ln = Lst_Find(&makefiles, NULL, ReadMakefile);
761 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
762 } else if (!ReadMakefile("BSDmakefile", NULL))
763 if (!ReadMakefile("makefile", NULL))
764 ReadMakefile("Makefile", NULL);
766 ReadMakefile(".depend", NULL);
768 /* Install all the flags into the MAKE envariable. */
769 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
770 setenv("MAKEFLAGS", p, 1);
774 * For compatibility, look at the directories in the VPATH variable
775 * and add them to the search path, if the variable is defined. The
776 * variable's value is in the same format as the PATH envariable, i.e.
777 * <directory>:<directory>:<directory>...
779 if (Var_Exists("VPATH", VAR_CMD)) {
782 * GCC stores string constants in read-only memory, but
783 * Var_Subst will want to write this thing, so store it
786 static char VPATH[] = "${VPATH}";
788 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
791 /* skip to end of directory */
792 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
794 /* Save terminator character so know when to stop */
797 /* Add directory to search path */
798 Dir_AddDir(&dirSearchPath, path);
801 } while (savec == ':');
806 * Now that all search paths have been read for suffixes et al, it's
807 * time to add the default search path to their lists...
811 /* print the initial graph, if the user requested it */
815 /* print the values of any variables requested by the user */
816 if (!Lst_IsEmpty(&variables)) {
819 for (ln = Lst_First(&variables); ln != NULL;
823 p1 = emalloc(strlen(Lst_Datum(ln)) + 1 + 3);
824 /* This sprintf is safe, because of the malloc above */
825 sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
826 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
828 value = Var_Value(Lst_Datum(ln),
831 printf("%s\n", value ? value : "");
838 * Have now read the entire graph and need to make a list of targets
839 * to create. If none was given on the command line, we consult the
840 * parsing module to find the main target(s) to create.
842 Lst targs = Lst_Initializer(targs);
844 if (Lst_IsEmpty(&create))
845 Parse_MainName(&targs);
847 Targ_FindList(&targs, &create, TARG_CREATE);
851 * Initialize job module before traversing the graph, now that
852 * any .BEGIN and .END targets have been read. This is done
853 * only if the -q flag wasn't given (to prevent the .BEGIN from
854 * being executed should it exist).
861 /* Traverse the graph, checking on all the targets */
862 outOfDate = Make_Run(&targs);
865 * Compat_Init will take care of creating all the targets as
866 * well as initializing the module.
871 Lst_Destroy(&targs, NOFREE);
874 Lst_Destroy(&variables, free);
875 Lst_Destroy(&makefiles, free);
876 Lst_Destroy(&create, free);
878 /* print the graph now it's been processed if the user requested it */
890 if (queryFlag && outOfDate)
898 * Open and parse the given makefile.
901 * TRUE if ok. FALSE if couldn't open file.
907 ReadMakefile(const void *p, const void *q __unused)
909 char *fname; /* makefile to read */
911 char *name, path[MAXPATHLEN];
915 /* XXX - remove this once constification is done */
918 if (!strcmp(fname, "-")) {
919 Parse_File("(stdin)", stdin);
920 Var_Set("MAKEFILE", "", VAR_GLOBAL);
922 setMAKEFILE = strcmp(fname, ".depend");
924 /* if we've chdir'd, rebuild the path name */
925 if (curdir != objdir && *fname != '/') {
926 snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
928 * XXX The realpath stuff breaks relative includes
929 * XXX in some cases. The problem likely is in
930 * XXX parse.c where it does special things in
931 * XXX ParseDoInclude if the file is relateive
932 * XXX or absolute and not a system file. There
933 * XXX it assumes that if the current file that's
934 * XXX being included is absolute, that any files
935 * XXX that it includes shouldn't do the -I path
936 * XXX stuff, which is inconsistant with historical
937 * XXX behavior. However, I can't pentrate the mists
938 * XXX further, so I'm putting this workaround in
939 * XXX here until such time as the underlying bug
942 #if THIS_BREAKS_THINGS
943 if (realpath(path, path) != NULL &&
944 (stream = fopen(path, "r")) != NULL) {
949 } else if (realpath(fname, path) != NULL) {
952 if ((stream = fopen(fname, "r")) != NULL)
956 if ((stream = fopen(path, "r")) != NULL) {
963 if ((stream = fopen(fname, "r")) != NULL)
967 /* look in -I and system include directories. */
968 name = Dir_FindFile(fname, &parseIncPath);
970 name = Dir_FindFile(fname, &sysIncPath);
971 if (!name || !(stream = fopen(name, "r")))
973 MAKEFILE = fname = name;
975 * set the MAKEFILE variable desired by System V fans -- the
976 * placement of the setting here means it gets set to the last
977 * makefile specified, as it is set by SysV make.
981 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
982 Parse_File(fname, stream);
990 * Execute the command in cmd, and return the output of that command
994 * A string containing the output of the command, or the empty string
995 * If error is not NULL, it contains the reason for the command failure
998 * The string must be freed by the caller.
1001 Cmd_Exec(char *cmd, char **error)
1003 char *args[4]; /* Args for invoking the shell */
1004 int fds[2]; /* Pipe streams */
1005 int cpid; /* Child PID */
1006 int pid; /* PID from wait() */
1007 char *res; /* result */
1008 int status; /* command exit status */
1009 Buffer buf; /* buffer to store the result */
1016 if (shellPath == NULL)
1019 * Set up arguments for shell
1021 args[0] = shellName;
1027 * Open a pipe for fetching its output
1029 if (pipe(fds) == -1) {
1030 *error = "Couldn't create pipe for \"%s\"";
1037 switch (cpid = vfork()) {
1040 * Close input side of pipe
1045 * Duplicate the output stream to the shell's output, then
1046 * shut the extra thing down. Note we don't fetch the error
1047 * stream...why not? Why?
1052 execv(shellPath, args);
1057 *error = "Couldn't exec \"%s\"";
1062 * No need for the writing half
1066 buf = Buf_Init(MAKE_BSIZE);
1069 char result[BUFSIZ];
1070 rcnt = read(fds[0], result, sizeof(result));
1072 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1073 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1075 * Close the input side of the pipe.
1080 * Wait for the process to exit.
1082 while (((pid = wait(&status)) != cpid) && (pid >= 0))
1086 *error = "Error reading shell's output for \"%s\"";
1088 res = (char *)Buf_GetAll(buf, &blen);
1089 Buf_Destroy(buf, FALSE);
1092 *error = "\"%s\" returned non-zero status";
1095 * Null-terminate the result, convert newlines to spaces and
1096 * install it in the variable.
1099 cp = &res[blen] - 1;
1103 * A final newline is just stripped
1124 * exit with usage message
1129 fprintf(stderr, "%s\n%s\n%s\n",
1130 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1131 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1132 " [-m directory] [-V variable] [variable=value] [target ...]");