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
42 #include <sys/cdefs.h>
43 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 The Regents of the University of California. All rights reserved.");
49 * The main file for this entire program. Exit routines etc
52 * Utility functions defined in this file:
53 * Main_ParseArgLine Takes a line of arguments, breaks them and
54 * treats them as if they were given when first
55 * invoked. Used by the parse module to implement
58 * Error Print a tagged error message. The global
59 * MAKE variable must have been defined. This
60 * takes a format string and two optional
63 * Fatal Print an error message and exit. Also takes
64 * a format string and two arguments.
66 * Punt Aborts all jobs and exits with a message. Also
67 * takes a format string and two arguments.
69 * Finish Finish things up by printing the number of
70 * errors which occured, as passed to it, and
74 #include <sys/types.h>
76 #include <sys/param.h>
77 #include <sys/resource.h>
78 #include <sys/signal.h>
81 #include <sys/sysctl.h>
84 #include <sys/utsname.h>
99 #include "pathnames.h"
102 #define DEFMAXLOCAL DEFMAXJOBS
103 #endif /* DEFMAXLOCAL */
105 #define MAKEFLAGS ".MAKEFLAGS"
107 Lst create; /* Targets to be made */
108 time_t now; /* Time at start of make */
109 GNode *DEFAULT; /* .DEFAULT node */
110 Boolean allPrecious; /* .PRECIOUS given on line by itself */
112 static Boolean noBuiltins; /* -r flag */
113 static Lst makefiles; /* ordered list of makefiles to read */
114 static Boolean printVars; /* print value of one or more vars */
115 static Boolean expandVars; /* fully expand printed variables */
116 static Lst variables; /* list of variables to print */
117 int maxJobs; /* -j argument */
118 static Boolean forceJobs; /* -j argument given */
119 static int maxLocal; /* -L argument */
120 Boolean compatMake; /* -B argument */
121 Boolean debug; /* -d flag */
122 Boolean noExecute; /* -n flag */
123 Boolean keepgoing; /* -k flag */
124 Boolean queryFlag; /* -q flag */
125 Boolean touchFlag; /* -t flag */
126 Boolean usePipes; /* !-P flag */
127 Boolean ignoreErrors; /* -i flag */
128 Boolean beSilent; /* -s flag */
129 Boolean beVerbose; /* -v flag */
130 Boolean oldVars; /* variable substitution style */
131 Boolean checkEnvFirst; /* -e flag */
132 Lst envFirstVars; /* (-E) vars to override from env */
133 static Boolean jobsRunning; /* TRUE if the jobs might be running */
135 static void MainParseArgs(int, char **);
136 char * chdir_verify_path(char *, char *);
137 static int ReadMakefile(void *, void *);
138 static void usage(void);
140 static char *curdir; /* startup directory */
141 static char *objdir; /* where we chdir'ed to */
145 * Parse a given argument vector. Called from main() and from
146 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
148 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
154 * Various global and local flags will be set depending on the flags
158 MainParseArgs(argc, argv)
165 optind = 1; /* since we're called more than once */
167 # define OPTFLAGS "BD:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
169 # define OPTFLAGS "BD:E:I:PSV:Xd:ef:ij:km:nqrstv"
171 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
174 Var_Set(optarg, "1", VAR_GLOBAL);
175 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
176 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
179 Parse_AddIncludeDir(optarg);
180 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
181 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
185 (void)Lst_AtEnd(variables, (void *)optarg);
186 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
187 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
194 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
200 maxLocal = strtol(optarg, &endptr, 10);
201 if (maxLocal < 0 || *endptr != '\0') {
202 warnx("illegal number, -L argument -- %s",
206 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
207 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
213 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
217 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
220 char *modules = optarg;
222 for (; *modules; ++modules)
240 if (modules[1] == '1') {
241 debug |= DEBUG_GRAPH1;
244 else if (modules[1] == '2') {
245 debug |= DEBUG_GRAPH2;
268 warnx("illegal argument to d option -- %c", *modules);
271 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
272 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
276 p = malloc(strlen(optarg) + 1);
278 Punt("make: cannot allocate memory.");
279 (void)strcpy(p, optarg);
280 (void)Lst_AtEnd(envFirstVars, (void *)p);
281 Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
282 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
285 checkEnvFirst = TRUE;
286 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
289 (void)Lst_AtEnd(makefiles, (void *)optarg);
293 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
299 maxJobs = strtol(optarg, &endptr, 10);
300 if (maxJobs <= 0 || *endptr != '\0') {
301 warnx("illegal number, -j argument -- %s",
308 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
309 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
314 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
317 Dir_AddDir(sysIncPath, optarg);
318 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
319 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
323 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
327 /* Kind of nonsensical, wot? */
328 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
332 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
336 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
340 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
344 Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
355 * See if the rest of the arguments are variable assignments and
356 * perform them if so. Else take them to be targets and stuff them
357 * on the end of the "create" list.
359 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
360 if (Parse_IsVar(*argv))
361 Parse_DoVar(*argv, VAR_CMD);
364 Punt("illegal (null) argument.");
367 optind = 0; /* -flag... */
372 (void)Lst_AtEnd(create, (void *)estrdup(*argv));
377 * Main_ParseArgLine --
378 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
379 * is encountered and by main() when reading the .MAKEFLAGS envariable.
380 * Takes a line of arguments and breaks it into its
381 * component words and passes those words and the number of them to the
382 * MainParseArgs function.
383 * The line should have all its leading whitespace removed.
389 * Only those that come from the various arguments.
392 Main_ParseArgLine(line)
393 char *line; /* Line to fracture */
395 char **argv; /* Manufactured argument vector */
396 int argc; /* Number of arguments in argv */
400 for (; *line == ' '; ++line)
405 argv = brk_string(line, &argc, TRUE);
406 MainParseArgs(argc, argv);
410 chdir_verify_path(path, obpath)
416 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
417 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
418 warn("warning: %s", path);
430 * The main function, for obvious reasons. Initializes variables
431 * and a few modules, then parses the arguments give it in the
432 * environment and on the command line. Reads the system makefile
433 * followed by either Makefile, makefile or the file given by the
434 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
435 * flags it has received by then uses either the Make or the Compat
436 * module to create the initial list of targets.
439 * If -q was given, exits -1 if anything was out-of-date. Else it exits
443 * The program exits when done. Targets are created. etc. etc. etc.
450 Lst targs; /* target nodes to create -- passed to Make_Init */
451 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
453 char *p, *p1, *path, *pathp;
454 char mdpath[MAXPATHLEN];
455 char obpath[MAXPATHLEN];
456 char cdpath[MAXPATHLEN];
457 char *machine = getenv("MACHINE");
458 char *machine_arch = getenv("MACHINE_ARCH");
459 char *machine_cpu = getenv("MACHINE_CPU");
460 Lst sysMkPath; /* Path of sys.mk */
461 char *cp = NULL, *start;
462 /* avoid faults on read-only strings */
463 static char syspath[] = _PATH_DEFSYSPATH;
467 * Turn off ENV to make ksh happier.
474 * get rid of resource limit on file descriptors
478 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
479 rl.rlim_cur != rl.rlim_max) {
480 rl.rlim_cur = rl.rlim_max;
481 (void) setrlimit(RLIMIT_NOFILE, &rl);
486 * Find where we are...
487 * All this code is so that we know where we are when we start up
488 * on a different machine with pmake.
491 if (getcwd(curdir, MAXPATHLEN) == NULL)
494 if (stat(curdir, &sa) == -1)
495 err(2, "%s", curdir);
497 #if defined(__i386__) && defined(__FreeBSD_version) && \
498 __FreeBSD_version > 300003
500 * PC-98 kernel sets the `i386' string to the utsname.machine and
501 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
502 * we check machine.ispc98 and adjust the machine variable before
503 * using usname(3) below.
504 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
505 * __FreeBSD_version was defined as 300003. So, this check can
506 * safely be done with any kernel with version > 300003.
512 len = sizeof(ispc98);
513 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
521 * Get the name of this type of MACHINE from utsname
522 * so we can share an executable for similar machines.
523 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
525 * Note that while MACHINE is decided at run-time,
526 * MACHINE_ARCH is always known at compile time.
530 struct utsname utsname;
532 if (uname(&utsname) == -1) {
533 perror("make: uname");
536 machine = utsname.machine;
544 machine_arch = "unknown";
546 machine_arch = MACHINE_ARCH;
551 * Set machine_cpu to the minumum supported CPU revision based
552 * on the target architecture, if not already set.
555 if (!strcmp(machine_arch, "i386"))
556 machine_cpu = "i386";
557 else if (!strcmp(machine_arch, "alpha"))
560 machine_cpu = "unknown";
564 * The object directory location is determined using the
565 * following order of preference:
567 * 1. MAKEOBJDIRPREFIX`cwd`
569 * 3. _PATH_OBJDIR.${MACHINE}
571 * 5. _PATH_OBJDIRPREFIX`cwd`
573 * If one of the first two fails, use the current directory.
574 * If the remaining three all fail, use the current directory.
576 * Once things are initted,
577 * have to add the original directory to the search path,
578 * and modify the paths for the Makefiles apropriately. The
579 * current directory is also placed as a variable for make scripts.
581 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
582 if (!(path = getenv("MAKEOBJDIR"))) {
584 pathp = _PATH_OBJDIRPREFIX;
585 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
587 if (!(objdir = chdir_verify_path(mdpath, obpath)))
588 if (!(objdir=chdir_verify_path(path, obpath))) {
589 (void) snprintf(mdpath, MAXPATHLEN,
590 "%s%s", pathp, curdir);
591 if (!(objdir=chdir_verify_path(mdpath,
596 else if (!(objdir = chdir_verify_path(path, obpath)))
600 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
601 if (!(objdir = chdir_verify_path(mdpath, obpath)))
605 create = Lst_Init(FALSE);
606 makefiles = Lst_Init(FALSE);
607 envFirstVars = Lst_Init(FALSE);
610 variables = Lst_Init(FALSE);
611 beSilent = FALSE; /* Print commands as executed */
612 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
613 noExecute = FALSE; /* Execute all commands */
614 keepgoing = FALSE; /* Stop on error */
615 allPrecious = FALSE; /* Remove targets when interrupted */
616 queryFlag = FALSE; /* This is not just a check-run */
617 noBuiltins = FALSE; /* Read the built-in rules */
618 touchFlag = FALSE; /* Actually update targets */
619 usePipes = TRUE; /* Catch child output in pipes */
620 debug = 0; /* No debug verbosity, please. */
623 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
625 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
629 forceJobs = FALSE; /* No -j flag */
630 compatMake = FALSE; /* No compat mode */
634 * Initialize the parsing, directory and variable modules to prepare
635 * for the reading of inclusion paths and variable settings on the
638 Dir_Init(); /* Initialize directory structures so -I flags
639 * can be processed correctly */
640 Parse_Init(); /* Need to initialize the paths of #include
642 Var_Init(); /* As well as the lists of variables for
643 * parsing arguments */
645 if (objdir != curdir)
646 Dir_AddDir(dirSearchPath, curdir);
647 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
648 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
651 * Initialize various variables.
652 * MAKE also gets this name, for compatibility
653 * .MAKEFLAGS gets set to the empty string just in case.
654 * MFLAGS also gets initialized empty, for compatibility.
656 Var_Set("MAKE", argv[0], VAR_GLOBAL);
657 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
658 Var_Set("MFLAGS", "", VAR_GLOBAL);
659 Var_Set("MACHINE", machine, VAR_GLOBAL);
660 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
661 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
664 * First snag any flags out of the MAKE environment variable.
665 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
666 * in a different format).
669 Main_ParseArgLine(getenv("MAKEFLAGS"));
671 Main_ParseArgLine(getenv("MAKE"));
674 MainParseArgs(argc, argv);
677 * Be compatible if user did not specify -j and did not explicitly
678 * turned compatibility on
680 if (!compatMake && !forceJobs)
684 * Initialize archive, target and suffix modules in preparation for
685 * parsing the makefile(s)
695 * Set up the .TARGETS variable to contain the list of targets to be
696 * created. If none specified, make the variable empty -- the parser
697 * will fill the thing in with the default or .MAIN target.
699 if (!Lst_IsEmpty(create)) {
702 for (ln = Lst_First(create); ln != NULL;
704 char *name = (char *)Lst_Datum(ln);
706 Var_Append(".TARGETS", name, VAR_GLOBAL);
709 Var_Set(".TARGETS", "", VAR_GLOBAL);
713 * If no user-supplied system path was given (through the -m option)
714 * add the directories from the DEFSYSPATH (more than one may be given
715 * as dir1:...:dirn) to the system include path.
717 if (Lst_IsEmpty(sysIncPath)) {
718 for (start = syspath; *start != '\0'; start = cp) {
719 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
722 Dir_AddDir(sysIncPath, start);
725 Dir_AddDir(sysIncPath, start);
731 * Read in the built-in rules first, followed by the specified
732 * makefile, if it was (makefile != (char *) NULL), or the default
733 * Makefile and makefile, in that order, if it wasn't.
738 sysMkPath = Lst_Init (FALSE);
739 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
740 if (Lst_IsEmpty(sysMkPath))
741 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
742 ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile);
744 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
747 if (!Lst_IsEmpty(makefiles)) {
750 ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
752 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
753 } else if (!ReadMakefile("makefile", NULL))
754 (void)ReadMakefile("Makefile", NULL);
756 (void)ReadMakefile(".depend", NULL);
758 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
761 /* Install all the flags into the MAKE envariable. */
762 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
764 setenv("MAKEFLAGS", p, 1);
766 setenv("MAKE", 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)) {
777 char *vpath, *path, *cp, savec;
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 */
816 for (ln = Lst_First(variables); ln != NULL;
820 p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
822 Punt("make: cannot allocate memory.");
823 /* This sprintf is safe, because of the malloc above */
824 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
825 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
827 value = Var_Value((char *)Lst_Datum(ln),
830 printf("%s\n", value ? value : "");
837 * Have now read the entire graph and need to make a list of targets
838 * to create. If none was given on the command line, we consult the
839 * parsing module to find the main target(s) to create.
841 if (Lst_IsEmpty(create))
842 targs = Parse_MainName();
844 targs = Targ_FindList(create, TARG_CREATE);
846 if (!compatMake && !printVars) {
848 * Initialize job module before traversing the graph, now that
849 * any .BEGIN and .END targets have been read. This is done
850 * only if the -q flag wasn't given (to prevent the .BEGIN from
851 * being executed should it exist).
856 Job_Init(maxJobs, maxLocal);
860 /* Traverse the graph, checking on all the targets */
861 outOfDate = Make_Run(targs);
862 } else if (!printVars) {
864 * Compat_Init will take care of creating all the targets as
865 * well as initializing the module.
870 Lst_Destroy(targs, NOFREE);
871 Lst_Destroy(variables, NOFREE);
872 Lst_Destroy(makefiles, NOFREE);
873 Lst_Destroy(create, (void (*)(void *)) free);
875 /* print the graph now it's been processed if the user requested it */
887 if (queryFlag && outOfDate)
895 * Open and parse the given makefile.
898 * TRUE if ok. FALSE if couldn't open file.
908 char *fname = p; /* makefile to read */
909 extern Lst parseIncPath;
911 char *name, path[MAXPATHLEN];
913 if (!strcmp(fname, "-")) {
914 Parse_File("(stdin)", stdin);
915 Var_Set("MAKEFILE", "", VAR_GLOBAL);
917 /* if we've chdir'd, rebuild the path name */
918 if (curdir != objdir && *fname != '/') {
919 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
920 if ((stream = fopen(path, "r")) != NULL) {
924 } else if ((stream = fopen(fname, "r")) != NULL)
926 /* look in -I and system include directories. */
927 name = Dir_FindFile(fname, parseIncPath);
929 name = Dir_FindFile(fname, sysIncPath);
930 if (!name || !(stream = fopen(name, "r")))
934 * set the MAKEFILE variable desired by System V fans -- the
935 * placement of the setting here means it gets set to the last
936 * makefile specified, as it is set by SysV make.
938 found: Var_Set("MAKEFILE", fname, VAR_GLOBAL);
939 Parse_File(fname, stream);
940 (void)fclose(stream);
947 * Execute the command in cmd, and return the output of that command
951 * A string containing the output of the command, or the empty string
952 * If err is not NULL, it contains the reason for the command failure
955 * The string must be freed by the caller.
962 char *args[4]; /* Args for invoking the shell */
963 int fds[2]; /* Pipe streams */
964 int cpid; /* Child PID */
965 int pid; /* PID from wait() */
966 char *res; /* result */
967 int status; /* command exit status */
968 Buffer buf; /* buffer to store the result */
976 * Set up arguments for shell
984 * Open a pipe for fetching its output
986 if (pipe(fds) == -1) {
987 *err = "Couldn't create pipe for \"%s\"";
994 switch (cpid = vfork()) {
997 * Close input side of pipe
999 (void) close(fds[0]);
1002 * Duplicate the output stream to the shell's output, then
1003 * shut the extra thing down. Note we don't fetch the error
1004 * stream...why not? Why?
1006 (void) dup2(fds[1], 1);
1007 (void) close(fds[1]);
1010 (void) execv("/bin/sh", args);
1012 (void) execv("/bin/ksh", args);
1014 #error "DEFSHELL must be 1 or 2."
1020 *err = "Couldn't exec \"%s\"";
1025 * No need for the writing half
1027 (void) close(fds[1]);
1029 buf = Buf_Init (MAKE_BSIZE);
1032 char result[BUFSIZ];
1033 cc = read(fds[0], result, sizeof(result));
1035 Buf_AddBytes(buf, cc, (Byte *) result);
1037 while (cc > 0 || (cc == -1 && errno == EINTR));
1040 * Close the input side of the pipe.
1042 (void) close(fds[0]);
1045 * Wait for the process to exit.
1047 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1051 *err = "Error reading shell's output for \"%s\"";
1053 res = (char *)Buf_GetAll (buf, &cc);
1054 Buf_Destroy (buf, FALSE);
1057 *err = "\"%s\" returned non-zero status";
1060 * Null-terminate the result, convert newlines to spaces and
1061 * install it in the variable.
1068 * A final newline is just stripped
1089 * Print an error message given its format.
1095 * The message is printed.
1099 Error(char *fmt, ...)
1104 (void)vfprintf(stderr, fmt, ap);
1106 (void)fprintf(stderr, "\n");
1107 (void)fflush(stderr);
1112 * Produce a Fatal error message. If jobs are running, waits for them
1123 Fatal(char *fmt, ...)
1131 (void)vfprintf(stderr, fmt, ap);
1133 (void)fprintf(stderr, "\n");
1134 (void)fflush(stderr);
1138 exit(2); /* Not 1 so -q can distinguish error */
1143 * Major exception once jobs are being created. Kills all jobs, prints
1144 * a message and exits.
1150 * All children are killed indiscriminately and the program Lib_Exits
1154 Punt(char *fmt, ...)
1159 (void)fprintf(stderr, "make: ");
1160 (void)vfprintf(stderr, fmt, ap);
1162 (void)fprintf(stderr, "\n");
1163 (void)fflush(stderr);
1170 * Exit without giving a message.
1185 exit(2); /* Not 1, so -q can distinguish error */
1190 * Called when aborting due to errors in child shell to signal
1201 int errors; /* number of errors encountered in Make_Make */
1203 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1208 * malloc, but die on error.
1216 if ((p = malloc(len)) == NULL)
1223 * strdup, but die on error.
1231 if ((p = strdup(str)) == NULL)
1238 * realloc, but die on error.
1245 if ((ptr = realloc(ptr, size)) == NULL)
1252 * die when out of memory.
1262 * Remove a file carefully, avoiding directories.
1270 if (lstat(file, &st) == -1)
1273 if (S_ISDIR(st.st_mode)) {
1277 return unlink(file);
1282 * exit with usage message
1287 (void)fprintf(stderr, "%s\n%s\n%s\n",
1288 "usage: make [-Beiknqrstv] [-D variable] [-d flags] [-E variable] [-f makefile]",
1289 " [-I directory] [-j max_jobs] [-m directory] [-V variable]",
1290 " [variable=value] [target ...]");
1300 printf("%lx ", (unsigned long) a);