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.38 2004/12/17 08:17:05 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 */
136 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
139 MFLAGS_append(char *flag, char *arg)
142 Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
144 Var_Append(MAKEFLAGS, arg, VAR_GLOBAL);
146 Var_Append("MFLAGS", flag, VAR_GLOBAL);
148 Var_Append("MFLAGS", arg, VAR_GLOBAL);
153 * Parse a given argument vector. Called from main() and from
154 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
156 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
162 * Various global and local flags will be set depending on the flags
166 MainParseArgs(int argc, char **argv)
170 optind = 1; /* since we're called more than once */
171 #define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
172 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
175 if (chdir(optarg) == -1)
176 err(1, "chdir %s", optarg);
179 Var_Set(optarg, "1", VAR_GLOBAL);
180 MFLAGS_append("-D", optarg);
183 Parse_AddIncludeDir(optarg);
184 MFLAGS_append("-I", optarg);
187 Lst_AtEnd(&variables, estrdup(optarg));
188 MFLAGS_append("-V", optarg);
195 MFLAGS_append("-B", NULL);
196 unsetenv("MAKE_JOBS_FIFO");
200 MFLAGS_append("-P", NULL);
204 MFLAGS_append("-S", NULL);
207 char *modules = optarg;
209 for (; *modules; ++modules)
227 if (modules[1] == '1') {
228 debug |= DEBUG_GRAPH1;
231 else if (modules[1] == '2') {
232 debug |= DEBUG_GRAPH2;
255 warnx("illegal argument to d option -- %c", *modules);
258 MFLAGS_append("-d", optarg);
262 Lst_AtEnd(&envFirstVars, estrdup(optarg));
263 MFLAGS_append("-E", optarg);
266 checkEnvFirst = TRUE;
267 MFLAGS_append("-e", NULL);
270 Lst_AtEnd(&makefiles, estrdup(optarg));
274 MFLAGS_append("-i", NULL);
280 maxJobs = strtol(optarg, &endptr, 10);
281 if (maxJobs <= 0 || *endptr != '\0') {
282 warnx("illegal number, -j argument -- %s",
286 MFLAGS_append("-j", optarg);
291 MFLAGS_append("-k", NULL);
294 Dir_AddDir(&sysIncPath, optarg);
295 MFLAGS_append("-m", optarg);
299 MFLAGS_append("-n", NULL);
303 /* Kind of nonsensical, wot? */
304 MFLAGS_append("-q", NULL);
308 MFLAGS_append("-r", NULL);
312 MFLAGS_append("-s", NULL);
316 MFLAGS_append("-t", NULL);
320 MFLAGS_append("-v", NULL);
331 * See if the rest of the arguments are variable assignments and
332 * perform them if so. Else take them to be targets and stuff them
333 * on the end of the "create" list.
335 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
336 if (Parse_IsVar(*argv)) {
337 char *ptr = Var_Quote(*argv);
339 Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
342 Parse_DoVar(*argv, VAR_CMD);
345 Punt("illegal (null) argument.");
348 optind = 0; /* -flag... */
353 Lst_AtEnd(&create, estrdup(*argv));
358 * Main_ParseArgLine --
359 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
360 * is encountered and by main() when reading the .MAKEFLAGS envariable.
361 * Takes a line of arguments and breaks it into its
362 * component words and passes those words and the number of them to the
363 * MainParseArgs function.
364 * The line should have all its leading whitespace removed.
370 * Only those that come from the various arguments.
373 Main_ParseArgLine(char *line)
375 char **argv; /* Manufactured argument vector */
376 int argc; /* Number of arguments in argv */
380 for (; *line == ' '; ++line)
385 argv = brk_string(line, &argc, TRUE);
386 MainParseArgs(argc, argv);
390 chdir_verify_path(char *path, char *obpath)
394 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
395 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
396 warn("warning: %s", path);
406 catch_child(int sig __unused)
411 * In lieu of a good way to prevent every possible looping in
412 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
413 * by make(1), to prevent a forkbomb from happening, in a dumb and
417 check_make_level(void)
419 #ifdef WANT_ENV_MKLVL
420 char *value = getenv(MKLVL_ENVVAR);
421 int level = (value == NULL) ? 0 : atoi(value);
424 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
425 } else if (level > MKLVL_MAXVAL) {
426 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
429 sprintf(new_value, "%d", level + 1);
430 setenv(MKLVL_ENVVAR, new_value, 1);
432 #endif /* WANT_ENV_MKLVL */
437 * The main function, for obvious reasons. Initializes variables
438 * and a few modules, then parses the arguments give it in the
439 * environment and on the command line. Reads the system makefile
440 * followed by either Makefile, makefile or the file given by the
441 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
442 * flags it has received by then uses either the Make or the Compat
443 * module to create the initial list of targets.
446 * If -q was given, exits -1 if anything was out-of-date. Else it exits
450 * The program exits when done. Targets are created. etc. etc. etc.
453 main(int argc, char **argv)
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 char *cp = NULL, *start;
465 /* avoid faults on read-only strings */
466 static char syspath[] = _PATH_DEFSYSPATH;
470 * Catch SIGCHLD so that we get kicked out of select() when we
471 * need to look at a child. This is only known to matter for the
472 * -j case (perhaps without -P).
474 * XXX this is intentionally misplaced.
478 sigemptyset(&sa.sa_mask);
479 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
480 sa.sa_handler = catch_child;
481 sigaction(SIGCHLD, &sa, NULL);
488 * Turn off ENV to make ksh happier.
495 * get rid of resource limit on file descriptors
499 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
500 rl.rlim_cur != rl.rlim_max) {
501 rl.rlim_cur = rl.rlim_max;
502 setrlimit(RLIMIT_NOFILE, &rl);
508 * PC-98 kernel sets the `i386' string to the utsname.machine and
509 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
510 * we check machine.ispc98 and adjust the machine variable before
511 * using usname(3) below.
512 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
513 * __FreeBSD_version was defined as 300003. So, this check can
514 * safely be done with any kernel with version > 300003.
520 len = sizeof(ispc98);
521 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
528 * Get the name of this type of MACHINE from utsname
529 * so we can share an executable for similar machines.
530 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
532 * Note that while MACHINE is decided at run-time,
533 * MACHINE_ARCH is always known at compile time.
537 struct utsname utsname;
539 if (uname(&utsname) == -1)
541 machine = utsname.machine;
549 machine_arch = "unknown";
551 machine_arch = MACHINE_ARCH;
556 * Set machine_cpu to the minumum supported CPU revision based
557 * on the target architecture, if not already set.
560 if (!strcmp(machine_arch, "i386"))
561 machine_cpu = "i386";
562 else if (!strcmp(machine_arch, "alpha"))
565 machine_cpu = "unknown";
569 beSilent = FALSE; /* Print commands as executed */
570 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
571 noExecute = FALSE; /* Execute all commands */
572 keepgoing = FALSE; /* Stop on error */
573 allPrecious = FALSE; /* Remove targets when interrupted */
574 queryFlag = FALSE; /* This is not just a check-run */
575 noBuiltins = FALSE; /* Read the built-in rules */
576 touchFlag = FALSE; /* Actually update targets */
577 usePipes = TRUE; /* Catch child output in pipes */
578 debug = 0; /* No debug verbosity, please. */
581 maxJobs = DEFMAXJOBS;
582 forceJobs = FALSE; /* No -j flag */
583 compatMake = FALSE; /* No compat mode */
586 * Initialize the parsing, directory and variable modules to prepare
587 * for the reading of inclusion paths and variable settings on the
590 Dir_Init(); /* Initialize directory structures so -I flags
591 * can be processed correctly */
592 Parse_Init(); /* Need to initialize the paths of #include
594 Var_Init(); /* As well as the lists of variables for
595 * parsing arguments */
599 * Initialize various variables.
600 * MAKE also gets this name, for compatibility
601 * .MAKEFLAGS gets set to the empty string just in case.
602 * MFLAGS also gets initialized empty, for compatibility.
604 Var_Set("MAKE", argv[0], VAR_GLOBAL);
605 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
606 Var_Set("MFLAGS", "", VAR_GLOBAL);
607 Var_Set("MACHINE", machine, VAR_GLOBAL);
608 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
609 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
611 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
615 * First snag any flags out of the MAKE environment variable.
616 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
617 * in a different format).
619 Main_ParseArgLine(getenv("MAKEFLAGS"));
621 MainParseArgs(argc, argv);
624 * Find where we are...
625 * All this code is so that we know where we are when we start up
626 * on a different machine with pmake.
629 if (getcwd(curdir, MAXPATHLEN) == NULL)
632 if (stat(curdir, &sa) == -1)
633 err(2, "%s", curdir);
636 * The object directory location is determined using the
637 * following order of preference:
639 * 1. MAKEOBJDIRPREFIX`cwd`
641 * 3. _PATH_OBJDIR.${MACHINE}
643 * 5. _PATH_OBJDIRPREFIX`cwd`
645 * If one of the first two fails, use the current directory.
646 * If the remaining three all fail, use the current directory.
648 * Once things are initted,
649 * have to add the original directory to the search path,
650 * and modify the paths for the Makefiles apropriately. The
651 * current directory is also placed as a variable for make scripts.
653 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
654 if (!(path = getenv("MAKEOBJDIR"))) {
656 pathp = _PATH_OBJDIRPREFIX;
657 snprintf(mdpath, MAXPATHLEN, "%s.%s",
659 if (!(objdir = chdir_verify_path(mdpath, obpath)))
660 if (!(objdir=chdir_verify_path(path, obpath))) {
661 snprintf(mdpath, MAXPATHLEN,
662 "%s%s", pathp, curdir);
663 if (!(objdir=chdir_verify_path(mdpath,
668 else if (!(objdir = chdir_verify_path(path, obpath)))
672 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
673 if (!(objdir = chdir_verify_path(mdpath, obpath)))
676 Dir_InitDot(); /* Initialize the "." directory */
677 if (objdir != curdir)
678 Dir_AddDir(&dirSearchPath, curdir);
679 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
680 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
681 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
683 if (getenv("MAKE_JOBS_FIFO") != NULL)
686 * Be compatible if user did not specify -j and did not explicitly
687 * turned compatibility on
689 if (!compatMake && !forceJobs)
693 * Initialize archive, target and suffix modules in preparation for
694 * parsing the makefile(s)
704 * Set up the .TARGETS variable to contain the list of targets to be
705 * created. If none specified, make the variable empty -- the parser
706 * will fill the thing in with the default or .MAIN target.
708 if (!Lst_IsEmpty(&create)) {
711 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
712 char *name = Lst_Datum(ln);
714 Var_Append(".TARGETS", name, VAR_GLOBAL);
717 Var_Set(".TARGETS", "", VAR_GLOBAL);
721 * If no user-supplied system path was given (through the -m option)
722 * add the directories from the DEFSYSPATH (more than one may be given
723 * as dir1:...:dirn) to the system include path.
725 if (Lst_IsEmpty(&sysIncPath)) {
726 for (start = syspath; *start != '\0'; start = cp) {
727 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
730 Dir_AddDir(&sysIncPath, start);
733 Dir_AddDir(&sysIncPath, start);
739 * Read in the built-in rules first, followed by the specified
740 * makefile, if it was (makefile != (char *) NULL), or the default
741 * Makefile and makefile, in that order, if it wasn't.
745 Lst sysMkPath = Lst_Initializer(sysMkPath);
748 Dir_Expand(_PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
749 if (Lst_IsEmpty(&sysMkPath))
750 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
751 ln = Lst_Find(&sysMkPath, NULL, ReadMakefile);
753 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
754 Lst_Destroy(&sysMkPath, free);
757 if (!Lst_IsEmpty(&makefiles)) {
760 ln = Lst_Find(&makefiles, NULL, ReadMakefile);
762 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
763 } else if (!ReadMakefile("BSDmakefile", NULL))
764 if (!ReadMakefile("makefile", NULL))
765 ReadMakefile("Makefile", NULL);
767 ReadMakefile(".depend", NULL);
769 /* Install all the flags into the MAKE envariable. */
770 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
771 setenv("MAKEFLAGS", p, 1);
775 * For compatibility, look at the directories in the VPATH variable
776 * and add them to the search path, if the variable is defined. The
777 * variable's value is in the same format as the PATH envariable, i.e.
778 * <directory>:<directory>:<directory>...
780 if (Var_Exists("VPATH", VAR_CMD)) {
783 * GCC stores string constants in read-only memory, but
784 * Var_Subst will want to write this thing, so store it
787 static char VPATH[] = "${VPATH}";
789 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
792 /* skip to end of directory */
793 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
795 /* Save terminator character so know when to stop */
798 /* Add directory to search path */
799 Dir_AddDir(&dirSearchPath, path);
802 } while (savec == ':');
807 * Now that all search paths have been read for suffixes et al, it's
808 * time to add the default search path to their lists...
812 /* print the initial graph, if the user requested it */
816 /* print the values of any variables requested by the user */
817 if (!Lst_IsEmpty(&variables)) {
820 for (ln = Lst_First(&variables); ln != NULL;
824 p1 = emalloc(strlen(Lst_Datum(ln)) + 1 + 3);
825 /* This sprintf is safe, because of the malloc above */
826 sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
827 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
829 value = Var_Value(Lst_Datum(ln),
832 printf("%s\n", value ? value : "");
839 * Have now read the entire graph and need to make a list of targets
840 * to create. If none was given on the command line, we consult the
841 * parsing module to find the main target(s) to create.
843 Lst targs = Lst_Initializer(targs);
845 if (Lst_IsEmpty(&create))
846 Parse_MainName(&targs);
848 Targ_FindList(&targs, &create, TARG_CREATE);
852 * Initialize job module before traversing the graph, now that
853 * any .BEGIN and .END targets have been read. This is done
854 * only if the -q flag wasn't given (to prevent the .BEGIN from
855 * being executed should it exist).
862 /* Traverse the graph, checking on all the targets */
863 outOfDate = Make_Run(&targs);
866 * Compat_Init will take care of creating all the targets as
867 * well as initializing the module.
872 Lst_Destroy(&targs, NOFREE);
875 Lst_Destroy(&variables, free);
876 Lst_Destroy(&makefiles, free);
877 Lst_Destroy(&create, free);
879 /* print the graph now it's been processed if the user requested it */
891 if (queryFlag && outOfDate)
899 * Open and parse the given makefile.
902 * TRUE if ok. FALSE if couldn't open file.
908 ReadMakefile(const void *p, const void *q __unused)
910 char *fname; /* makefile to read */
912 char *name, path[MAXPATHLEN];
916 /* XXX - remove this once constification is done */
919 if (!strcmp(fname, "-")) {
920 Parse_File("(stdin)", stdin);
921 Var_Set("MAKEFILE", "", VAR_GLOBAL);
923 setMAKEFILE = strcmp(fname, ".depend");
925 /* if we've chdir'd, rebuild the path name */
926 if (curdir != objdir && *fname != '/') {
927 snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
929 * XXX The realpath stuff breaks relative includes
930 * XXX in some cases. The problem likely is in
931 * XXX parse.c where it does special things in
932 * XXX ParseDoInclude if the file is relateive
933 * XXX or absolute and not a system file. There
934 * XXX it assumes that if the current file that's
935 * XXX being included is absolute, that any files
936 * XXX that it includes shouldn't do the -I path
937 * XXX stuff, which is inconsistant with historical
938 * XXX behavior. However, I can't pentrate the mists
939 * XXX further, so I'm putting this workaround in
940 * XXX here until such time as the underlying bug
943 #if THIS_BREAKS_THINGS
944 if (realpath(path, path) != NULL &&
945 (stream = fopen(path, "r")) != NULL) {
950 } else if (realpath(fname, path) != NULL) {
953 if ((stream = fopen(fname, "r")) != NULL)
957 if ((stream = fopen(path, "r")) != NULL) {
964 if ((stream = fopen(fname, "r")) != NULL)
968 /* look in -I and system include directories. */
969 name = Dir_FindFile(fname, &parseIncPath);
971 name = Dir_FindFile(fname, &sysIncPath);
972 if (!name || !(stream = fopen(name, "r")))
974 MAKEFILE = fname = name;
976 * set the MAKEFILE variable desired by System V fans -- the
977 * placement of the setting here means it gets set to the last
978 * makefile specified, as it is set by SysV make.
982 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
983 Parse_File(fname, stream);
991 * Execute the command in cmd, and return the output of that command
995 * A string containing the output of the command, or the empty string
996 * If error is not NULL, it contains the reason for the command failure
999 * The string must be freed by the caller.
1002 Cmd_Exec(char *cmd, char **error)
1004 char *args[4]; /* Args for invoking the shell */
1005 int fds[2]; /* Pipe streams */
1006 int cpid; /* Child PID */
1007 int pid; /* PID from wait() */
1008 char *res; /* result */
1009 int status; /* command exit status */
1010 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
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?
1053 execv(shellPath, args);
1058 *error = "Couldn't exec \"%s\"";
1063 * No need for the writing half
1067 buf = Buf_Init(MAKE_BSIZE);
1070 char result[BUFSIZ];
1071 rcnt = read(fds[0], result, sizeof(result));
1073 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1074 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1076 * Close the input side of the pipe.
1081 * Wait for the process to exit.
1083 while (((pid = wait(&status)) != cpid) && (pid >= 0))
1087 *error = "Error reading shell's output for \"%s\"";
1089 res = (char *)Buf_GetAll(buf, &blen);
1090 Buf_Destroy(buf, FALSE);
1093 *error = "\"%s\" returned non-zero status";
1096 * Null-terminate the result, convert newlines to spaces and
1097 * install it in the variable.
1100 cp = &res[blen] - 1;
1104 * A final newline is just stripped
1125 * exit with usage message
1130 fprintf(stderr, "%s\n%s\n%s\n",
1131 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1132 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1133 " [-m directory] [-V variable] [variable=value] [target ...]");