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.20 2004/11/30 15:22:46 joerg 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>
60 #include <sys/sysctl.h>
63 #include <sys/resource.h>
65 #include <sys/utsname.h>
83 #include "pathnames.h"
85 #define WANT_ENV_MKLVL 1
88 #define DEFMAXLOCAL DEFMAXJOBS
89 #endif /* DEFMAXLOCAL */
91 #define MAKEFLAGS ".MAKEFLAGS"
93 Lst create; /* Targets to be made */
94 time_t now; /* Time at start of make */
95 GNode *DEFAULT; /* .DEFAULT node */
96 Boolean allPrecious; /* .PRECIOUS given on line by itself */
98 static Boolean noBuiltins; /* -r flag */
99 static Lst makefiles; /* ordered list of makefiles to read */
100 static Boolean expandVars; /* fully expand printed variables */
101 static Lst variables; /* list of variables to print */
102 int maxJobs; /* -j argument */
103 static Boolean forceJobs; /* -j argument given */
104 static int maxLocal; /* -L argument */
105 Boolean compatMake; /* -B argument */
106 Boolean debug; /* -d flag */
107 Boolean noExecute; /* -n flag */
108 Boolean keepgoing; /* -k flag */
109 Boolean queryFlag; /* -q flag */
110 Boolean touchFlag; /* -t flag */
111 Boolean usePipes; /* !-P flag */
112 Boolean ignoreErrors; /* -i flag */
113 Boolean beSilent; /* -s flag */
114 Boolean beVerbose; /* -v flag */
115 Boolean oldVars; /* variable substitution style */
116 Boolean checkEnvFirst; /* -e flag */
117 Lst envFirstVars; /* (-E) vars to override from env */
118 Boolean jobsRunning; /* TRUE if the jobs might be running */
120 static void MainParseArgs(int, char **);
121 char * chdir_verify_path(char *, char *);
122 static int ReadMakefile(void *, void *);
123 static void usage(void);
124 static void catch_child(int sig __unused);
126 static char *curdir; /* startup directory */
127 static char *objdir; /* where we chdir'ed to */
132 * Parse a given argument vector. Called from main() and from
133 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
135 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
141 * Various global and local flags will be set depending on the flags
145 MainParseArgs(int argc, char **argv)
150 optind = 1; /* since we're called more than once */
152 # define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
154 # define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
156 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
159 if (chdir(optarg) == -1)
160 err(1, "chdir %s", optarg);
163 Var_Set(optarg, "1", VAR_GLOBAL);
164 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
165 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
168 Parse_AddIncludeDir(optarg);
169 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
170 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
173 (void)Lst_AtEnd(variables, (void *)optarg);
174 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
175 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
182 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
188 maxLocal = strtol(optarg, &endptr, 10);
189 if (maxLocal < 0 || *endptr != '\0') {
190 warnx("illegal number, -L argument -- %s",
194 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
195 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
201 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
205 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
208 char *modules = optarg;
210 for (; *modules; ++modules)
228 if (modules[1] == '1') {
229 debug |= DEBUG_GRAPH1;
232 else if (modules[1] == '2') {
233 debug |= DEBUG_GRAPH2;
256 warnx("illegal argument to d option -- %c", *modules);
259 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
260 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
264 p = emalloc(strlen(optarg) + 1);
265 (void)strcpy(p, optarg);
266 (void)Lst_AtEnd(envFirstVars, (void *)p);
267 Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
268 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
271 checkEnvFirst = TRUE;
272 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
275 (void)Lst_AtEnd(makefiles, (void *)optarg);
279 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
285 maxJobs = strtol(optarg, &endptr, 10);
286 if (maxJobs <= 0 || *endptr != '\0') {
287 warnx("illegal number, -j argument -- %s",
294 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
295 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
300 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
303 Dir_AddDir(sysIncPath, optarg);
304 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
305 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
309 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
313 /* Kind of nonsensical, wot? */
314 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
318 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
322 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
326 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
330 Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
341 * See if the rest of the arguments are variable assignments and
342 * perform them if so. Else take them to be targets and stuff them
343 * on the end of the "create" list.
345 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
346 if (Parse_IsVar(*argv))
347 Parse_DoVar(*argv, VAR_CMD);
350 Punt("illegal (null) argument.");
353 optind = 0; /* -flag... */
358 (void)Lst_AtEnd(create, (void *)estrdup(*argv));
363 * Main_ParseArgLine --
364 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
365 * is encountered and by main() when reading the .MAKEFLAGS envariable.
366 * Takes a line of arguments and breaks it into its
367 * component words and passes those words and the number of them to the
368 * MainParseArgs function.
369 * The line should have all its leading whitespace removed.
375 * Only those that come from the various arguments.
378 Main_ParseArgLine(char *line)
380 char **argv; /* Manufactured argument vector */
381 int argc; /* Number of arguments in argv */
385 for (; *line == ' '; ++line)
390 argv = brk_string(line, &argc, TRUE);
391 MainParseArgs(argc, argv);
395 chdir_verify_path(char *path, char *obpath)
399 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
400 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
401 warn("warning: %s", path);
413 * The main function, for obvious reasons. Initializes variables
414 * and a few modules, then parses the arguments give it in the
415 * environment and on the command line. Reads the system makefile
416 * followed by either Makefile, makefile or the file given by the
417 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
418 * flags it has received by then uses either the Make or the Compat
419 * module to create the initial list of targets.
422 * If -q was given, exits -1 if anything was out-of-date. Else it exits
426 * The program exits when done. Targets are created. etc. etc. etc.
429 main(int argc, char **argv)
431 Lst targs; /* target nodes to create -- passed to Make_Init */
432 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
434 char *p, *p1, *path, *pathp;
435 #ifdef WANT_ENV_MKLVL
436 #define MKLVL_MAXVAL 500
437 #define MKLVL_ENVVAR "__MKLVL__"
439 char *szMkLvl = getenv(MKLVL_ENVVAR);
440 #endif /* WANT_ENV_MKLVL */
441 char mdpath[MAXPATHLEN];
442 char obpath[MAXPATHLEN];
443 char cdpath[MAXPATHLEN];
444 char *machine = getenv("MACHINE");
445 char *machine_arch = getenv("MACHINE_ARCH");
446 char *machine_cpu = getenv("MACHINE_CPU");
447 Lst sysMkPath; /* Path of sys.mk */
448 char *cp = NULL, *start;
449 /* avoid faults on read-only strings */
450 static char syspath[] = _PATH_DEFSYSPATH;
454 * Catch SIGCHLD so that we get kicked out of select() when we
455 * need to look at a child. This is only known to matter for the
456 * -j case (perhaps without -P).
458 * XXX this is intentionally misplaced.
462 #ifdef WANT_ENV_MKLVL
463 if ((iMkLvl = szMkLvl ? atoi(szMkLvl) : 0) < 0) {
466 if (iMkLvl++ > MKLVL_MAXVAL) {
468 "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
470 bzero(szMkLvl = emalloc(32), 32);
471 sprintf(szMkLvl, "%d", iMkLvl);
472 setenv(MKLVL_ENVVAR, szMkLvl, 1);
473 #endif /* WANT_ENV_MKLVL */
475 sigemptyset(&sa.sa_mask);
476 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
477 sa.sa_handler = catch_child;
478 sigaction(SIGCHLD, &sa, NULL);
483 * get rid of resource limit on file descriptors
487 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
488 rl.rlim_cur != rl.rlim_max) {
489 rl.rlim_cur = rl.rlim_max;
490 (void) setrlimit(RLIMIT_NOFILE, &rl);
496 * PC-98 kernel sets the `i386' string to the utsname.machine and
497 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
498 * we check machine.ispc98 and adjust the machine variable before
499 * using usname(3) below.
500 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
501 * __FreeBSD_version was defined as 300003. So, this check can
502 * safely be done with any kernel with version > 300003.
508 len = sizeof(ispc98);
509 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
516 * Get the name of this type of MACHINE from utsname
517 * so we can share an executable for similar machines.
518 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
520 * Note that while MACHINE is decided at run-time,
521 * MACHINE_ARCH is always known at compile time.
525 struct utsname utsname;
527 if (uname(&utsname) == -1)
529 machine = utsname.machine;
537 machine_arch = "unknown";
539 machine_arch = MACHINE_ARCH;
544 * Set machine_cpu to the minumum supported CPU revision based
545 * on the target architecture, if not already set.
548 if (!strcmp(machine_arch, "i386"))
549 machine_cpu = "i386";
550 else if (!strcmp(machine_arch, "alpha"))
553 machine_cpu = "unknown";
556 create = Lst_Init(FALSE);
557 makefiles = Lst_Init(FALSE);
558 envFirstVars = Lst_Init(FALSE);
560 variables = Lst_Init(FALSE);
561 beSilent = FALSE; /* Print commands as executed */
562 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
563 noExecute = FALSE; /* Execute all commands */
564 keepgoing = FALSE; /* Stop on error */
565 allPrecious = FALSE; /* Remove targets when interrupted */
566 queryFlag = FALSE; /* This is not just a check-run */
567 noBuiltins = FALSE; /* Read the built-in rules */
568 touchFlag = FALSE; /* Actually update targets */
569 usePipes = TRUE; /* Catch child output in pipes */
570 debug = 0; /* No debug verbosity, please. */
573 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
575 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
579 forceJobs = FALSE; /* No -j flag */
580 compatMake = FALSE; /* No compat mode */
584 * Initialize the parsing, directory and variable modules to prepare
585 * for the reading of inclusion paths and variable settings on the
588 Dir_Init(); /* Initialize directory structures so -I flags
589 * can be processed correctly */
590 Parse_Init(); /* Need to initialize the paths of #include
592 Var_Init(); /* As well as the lists of variables for
593 * parsing arguments */
597 * Initialize various variables.
598 * MAKE also gets this name, for compatibility
599 * .MAKEFLAGS gets set to the empty string just in case.
600 * MFLAGS also gets initialized empty, for compatibility.
602 Var_Set("MAKE", argv[0], VAR_GLOBAL);
603 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
604 Var_Set("MFLAGS", "", VAR_GLOBAL);
605 Var_Set("MACHINE", machine, VAR_GLOBAL);
606 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
607 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
609 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
613 * First snag any flags out of the MAKE environment variable.
614 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
615 * in a different format).
618 Main_ParseArgLine(getenv("MAKEFLAGS"));
620 Main_ParseArgLine(getenv("MAKE"));
623 MainParseArgs(argc, argv);
626 * Find where we are...
627 * All this code is so that we know where we are when we start up
628 * on a different machine with pmake.
631 if (getcwd(curdir, MAXPATHLEN) == NULL)
634 if (stat(curdir, &sa) == -1)
635 err(2, "%s", curdir);
638 * The object directory location is determined using the
639 * following order of preference:
641 * 1. MAKEOBJDIRPREFIX`cwd`
643 * 3. _PATH_OBJDIR.${MACHINE}
645 * 5. _PATH_OBJDIRPREFIX`cwd`
647 * If one of the first two fails, use the current directory.
648 * If the remaining three all fail, use the current directory.
650 * Once things are initted,
651 * have to add the original directory to the search path,
652 * and modify the paths for the Makefiles apropriately. The
653 * current directory is also placed as a variable for make scripts.
655 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
656 if (!(path = getenv("MAKEOBJDIR"))) {
658 pathp = _PATH_OBJDIRPREFIX;
659 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
661 if (!(objdir = chdir_verify_path(mdpath, obpath)))
662 if (!(objdir=chdir_verify_path(path, obpath))) {
663 (void) snprintf(mdpath, MAXPATHLEN,
664 "%s%s", pathp, curdir);
665 if (!(objdir=chdir_verify_path(mdpath,
670 else if (!(objdir = chdir_verify_path(path, obpath)))
674 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
675 if (!(objdir = chdir_verify_path(mdpath, obpath)))
678 Dir_InitDot(); /* Initialize the "." directory */
679 if (objdir != curdir)
680 Dir_AddDir(dirSearchPath, curdir);
681 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
682 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
683 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
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;
713 char *name = (char *)Lst_Datum(ln);
715 Var_Append(".TARGETS", name, VAR_GLOBAL);
718 Var_Set(".TARGETS", "", VAR_GLOBAL);
722 * If no user-supplied system path was given (through the -m option)
723 * add the directories from the DEFSYSPATH (more than one may be given
724 * as dir1:...:dirn) to the system include path.
726 if (Lst_IsEmpty(sysIncPath)) {
727 for (start = syspath; *start != '\0'; start = cp) {
728 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
731 Dir_AddDir(sysIncPath, start);
734 Dir_AddDir(sysIncPath, start);
740 * Read in the built-in rules first, followed by the specified
741 * makefile, if it was (makefile != (char *) NULL), or the default
742 * Makefile and makefile, in that order, if it wasn't.
747 sysMkPath = Lst_Init (FALSE);
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, (void *)NULL, ReadMakefile);
753 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
756 if (!Lst_IsEmpty(makefiles)) {
759 ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
761 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
762 } else if (!ReadMakefile("BSDmakefile", NULL))
763 if (!ReadMakefile("makefile", NULL))
764 (void)ReadMakefile("Makefile", NULL);
766 (void)ReadMakefile(".depend", NULL);
768 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
771 /* Install all the flags into the MAKE envariable. */
772 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
774 setenv("MAKEFLAGS", p, 1);
776 setenv("MAKE", p, 1);
781 * For compatibility, look at the directories in the VPATH variable
782 * and add them to the search path, if the variable is defined. The
783 * variable's value is in the same format as the PATH envariable, i.e.
784 * <directory>:<directory>:<directory>...
786 if (Var_Exists("VPATH", VAR_CMD)) {
789 * GCC stores string constants in read-only memory, but
790 * Var_Subst will want to write this thing, so store it
793 static char VPATH[] = "${VPATH}";
795 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
798 /* skip to end of directory */
799 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
801 /* Save terminator character so know when to stop */
804 /* Add directory to search path */
805 Dir_AddDir(dirSearchPath, path);
808 } while (savec == ':');
813 * Now that all search paths have been read for suffixes et al, it's
814 * time to add the default search path to their lists...
818 /* print the initial graph, if the user requested it */
822 /* print the values of any variables requested by the user */
823 if (!Lst_IsEmpty(variables)) {
826 for (ln = Lst_First(variables); ln != NULL;
830 p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
831 /* This sprintf is safe, because of the malloc above */
832 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
833 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
835 value = Var_Value((char *)Lst_Datum(ln),
838 printf("%s\n", value ? value : "");
845 * Have now read the entire graph and need to make a list of targets
846 * to create. If none was given on the command line, we consult the
847 * parsing module to find the main target(s) to create.
849 if (Lst_IsEmpty(create))
850 targs = Parse_MainName();
852 targs = Targ_FindList(create, TARG_CREATE);
856 * Initialize job module before traversing the graph, now that
857 * any .BEGIN and .END targets have been read. This is done
858 * only if the -q flag wasn't given (to prevent the .BEGIN from
859 * being executed should it exist).
864 Job_Init(maxJobs, maxLocal);
868 /* Traverse the graph, checking on all the targets */
869 outOfDate = Make_Run(targs);
872 * Compat_Init will take care of creating all the targets as
873 * well as initializing the module.
877 Lst_Destroy(targs, NOFREE);
880 Lst_Destroy(variables, NOFREE);
881 Lst_Destroy(makefiles, NOFREE);
882 Lst_Destroy(create, (void (*) (void *)) free);
884 /* print the graph now it's been processed if the user requested it */
896 if (queryFlag && outOfDate)
904 * Open and parse the given makefile.
907 * TRUE if ok. FALSE if couldn't open file.
913 ReadMakefile(void *p, void *q __unused)
915 char *fname; /* makefile to read */
917 char *name, path[MAXPATHLEN];
923 if (!strcmp(fname, "-")) {
924 Parse_File("(stdin)", stdin);
925 Var_Set("MAKEFILE", "", VAR_GLOBAL);
927 setMAKEFILE = strcmp(fname, ".depend");
929 /* if we've chdir'd, rebuild the path name */
930 if (curdir != objdir && *fname != '/') {
931 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
933 * XXX The realpath stuff breaks relative includes
934 * XXX in some cases. The problem likely is in
935 * XXX parse.c where it does special things in
936 * XXX ParseDoInclude if the file is relateive
937 * XXX or absolute and not a system file. There
938 * XXX it assumes that if the current file that's
939 * XXX being included is absolute, that any files
940 * XXX that it includes shouldn't do the -I path
941 * XXX stuff, which is inconsistant with historical
942 * XXX behavior. However, I can't pentrate the mists
943 * XXX further, so I'm putting this workaround in
944 * XXX here until such time as the underlying bug
947 #if THIS_BREAKS_THINGS
948 if (realpath(path, path) != NULL &&
949 (stream = fopen(path, "r")) != NULL) {
954 } else if (realpath(fname, path) != NULL) {
957 if ((stream = fopen(fname, "r")) != NULL)
961 if ((stream = fopen(path, "r")) != NULL) {
968 if ((stream = fopen(fname, "r")) != NULL)
972 /* look in -I and system include directories. */
973 name = Dir_FindFile(fname, parseIncPath);
975 name = Dir_FindFile(fname, sysIncPath);
976 if (!name || !(stream = fopen(name, "r")))
978 MAKEFILE = fname = name;
980 * set the MAKEFILE variable desired by System V fans -- the
981 * placement of the setting here means it gets set to the last
982 * makefile specified, as it is set by SysV make.
986 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
987 Parse_File(fname, stream);
988 (void)fclose(stream);
995 * Execute the command in cmd, and return the output of that command
999 * A string containing the output of the command, or the empty string
1000 * If error is not NULL, it contains the reason for the command failure
1003 * The string must be freed by the caller.
1006 Cmd_Exec(char *cmd, char **error)
1008 char *args[4]; /* Args for invoking the shell */
1009 int fds[2]; /* Pipe streams */
1010 int cpid; /* Child PID */
1011 int pid; /* PID from wait() */
1012 char *res; /* result */
1013 int status; /* command exit status */
1014 Buffer buf; /* buffer to store the result */
1021 * Set up arguments for shell
1029 * Open a pipe for fetching its output
1031 if (pipe(fds) == -1) {
1032 *error = "Couldn't create pipe for \"%s\"";
1039 switch (cpid = vfork()) {
1042 * Close input side of pipe
1044 (void) close(fds[0]);
1047 * Duplicate the output stream to the shell's output, then
1048 * shut the extra thing down. Note we don't fetch the error
1049 * stream...why not? Why?
1051 (void) dup2(fds[1], 1);
1052 (void) close(fds[1]);
1054 (void) execv("/bin/sh", args);
1059 *error = "Couldn't exec \"%s\"";
1064 * No need for the writing half
1066 (void) close(fds[1]);
1068 buf = Buf_Init (MAKE_BSIZE);
1071 char result[BUFSIZ];
1072 cc = read(fds[0], result, sizeof(result));
1074 Buf_AddBytes(buf, cc, (Byte *) result);
1076 while (cc > 0 || (cc == -1 && errno == EINTR));
1079 * Close the input side of the pipe.
1081 (void) close(fds[0]);
1084 * Wait for the process to exit.
1086 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1090 *error = "Error reading shell's output for \"%s\"";
1092 res = (char *)Buf_GetAll (buf, &cc);
1093 Buf_Destroy (buf, FALSE);
1096 *error = "\"%s\" returned non-zero status";
1099 * Null-terminate the result, convert newlines to spaces and
1100 * install it in the variable.
1107 * A final newline is just stripped
1128 * exit with usage message
1133 (void)fprintf(stderr, "%s\n%s\n%s\n",
1134 "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1135 " [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1136 " [-m directory] [-V variable] [variable=value] [target ...]");
1142 catch_child(int sig __unused)