Sync usage with man page.
[netbsd-mini2440.git] / usr.bin / make / main.c
blobe5e6e2aae1c6241ff690e68643ea3d92e7cef096
1 /* $NetBSD: main.c,v 1.174 2009/09/09 17:09:49 sjg Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.174 2009/09/09 17:09:49 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
77 The Regents of the University of California. All rights reserved.");
78 #endif /* not lint */
80 #ifndef lint
81 #if 0
82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94";
83 #else
84 __RCSID("$NetBSD: main.c,v 1.174 2009/09/09 17:09:49 sjg Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
94 * Utility functions defined in this file:
95 * Main_ParseArgLine Takes a line of arguments, breaks them and
96 * treats them as if they were given when first
97 * invoked. Used by the parse module to implement
98 * the .MFLAGS target.
100 * Error Print a tagged error message. The global
101 * MAKE variable must have been defined. This
102 * takes a format string and two optional
103 * arguments for it.
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/signal.h>
121 #include <sys/stat.h>
122 #ifdef MAKE_NATIVE
123 #include <sys/utsname.h>
124 #endif
125 #include <sys/wait.h>
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
134 #include "make.h"
135 #include "hash.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "pathnames.h"
139 #include "trace.h"
141 #ifdef USE_IOVEC
142 #include <sys/uio.h>
143 #endif
145 #ifndef DEFMAXLOCAL
146 #define DEFMAXLOCAL DEFMAXJOBS
147 #endif /* DEFMAXLOCAL */
149 Lst create; /* Targets to be made */
150 time_t now; /* Time at start of make */
151 GNode *DEFAULT; /* .DEFAULT node */
152 Boolean allPrecious; /* .PRECIOUS given on line by itself */
154 static Boolean noBuiltins; /* -r flag */
155 static Lst makefiles; /* ordered list of makefiles to read */
156 static Boolean printVars; /* print value of one or more vars */
157 static Lst variables; /* list of variables to print */
158 int maxJobs; /* -j argument */
159 static int maxJobTokens; /* -j argument */
160 Boolean compatMake; /* -B argument */
161 int debug; /* -d argument */
162 Boolean noExecute; /* -n flag */
163 Boolean noRecursiveExecute; /* -N flag */
164 Boolean keepgoing; /* -k flag */
165 Boolean queryFlag; /* -q flag */
166 Boolean touchFlag; /* -t flag */
167 Boolean ignoreErrors; /* -i flag */
168 Boolean beSilent; /* -s flag */
169 Boolean oldVars; /* variable substitution style */
170 Boolean checkEnvFirst; /* -e flag */
171 Boolean parseWarnFatal; /* -W flag */
172 Boolean jobServer; /* -J flag */
173 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
174 Boolean varNoExportEnv; /* -X flag */
175 Boolean doing_depend; /* Set while reading .depend */
176 static Boolean jobsRunning; /* TRUE if the jobs might be running */
177 static const char * tracefile;
178 static char * Check_Cwd_av(int, char **, int);
179 static void MainParseArgs(int, char **);
180 static int ReadMakefile(const void *, const void *);
181 static void usage(void);
183 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
184 static char curdir[MAXPATHLEN + 1]; /* startup directory */
185 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
186 char *progname; /* the program name */
188 Boolean forceJobs = FALSE;
190 extern Lst parseIncPath;
192 static void
193 parse_debug_options(const char *argvalue)
195 const char *modules;
196 const char *mode;
197 char *fname;
198 int len;
200 for (modules = argvalue; *modules; ++modules) {
201 switch (*modules) {
202 case 'A':
203 debug = ~0;
204 break;
205 case 'a':
206 debug |= DEBUG_ARCH;
207 break;
208 case 'C':
209 debug |= DEBUG_CWD;
210 break;
211 case 'c':
212 debug |= DEBUG_COND;
213 break;
214 case 'd':
215 debug |= DEBUG_DIR;
216 break;
217 case 'e':
218 debug |= DEBUG_ERROR;
219 break;
220 case 'f':
221 debug |= DEBUG_FOR;
222 break;
223 case 'g':
224 if (modules[1] == '1') {
225 debug |= DEBUG_GRAPH1;
226 ++modules;
228 else if (modules[1] == '2') {
229 debug |= DEBUG_GRAPH2;
230 ++modules;
232 else if (modules[1] == '3') {
233 debug |= DEBUG_GRAPH3;
234 ++modules;
236 break;
237 case 'j':
238 debug |= DEBUG_JOB;
239 break;
240 case 'l':
241 debug |= DEBUG_LOUD;
242 break;
243 case 'm':
244 debug |= DEBUG_MAKE;
245 break;
246 case 'n':
247 debug |= DEBUG_SCRIPT;
248 break;
249 case 'p':
250 debug |= DEBUG_PARSE;
251 break;
252 case 's':
253 debug |= DEBUG_SUFF;
254 break;
255 case 't':
256 debug |= DEBUG_TARG;
257 break;
258 case 'v':
259 debug |= DEBUG_VAR;
260 break;
261 case 'x':
262 debug |= DEBUG_SHELL;
263 break;
264 case 'F':
265 if (debug_file != stdout && debug_file != stderr)
266 fclose(debug_file);
267 if (*++modules == '+')
268 mode = "a";
269 else
270 mode = "w";
271 if (strcmp(modules, "stdout") == 0) {
272 debug_file = stdout;
273 goto debug_setbuf;
275 if (strcmp(modules, "stderr") == 0) {
276 debug_file = stderr;
277 goto debug_setbuf;
279 len = strlen(modules);
280 fname = malloc(len + 20);
281 memcpy(fname, modules, len + 1);
282 /* Let the filename be modified by the pid */
283 if (strcmp(fname + len - 3, ".%d") == 0)
284 snprintf(fname + len - 2, 20, "%d", getpid());
285 debug_file = fopen(fname, mode);
286 if (!debug_file) {
287 fprintf(stderr, "Cannot open debug file %s\n",
288 fname);
289 usage();
291 free(fname);
292 goto debug_setbuf;
293 default:
294 (void)fprintf(stderr,
295 "%s: illegal argument to d option -- %c\n",
296 progname, *modules);
297 usage();
300 debug_setbuf:
302 * Make the debug_file unbuffered, and make
303 * stdout line buffered (unless debugfile == stdout).
305 setvbuf(debug_file, NULL, _IONBF, 0);
306 if (debug_file != stdout) {
307 setvbuf(stdout, NULL, _IOLBF, 0);
312 * MainParseArgs --
313 * Parse a given argument vector. Called from main() and from
314 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
316 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
318 * Results:
319 * None
321 * Side Effects:
322 * Various global and local flags will be set depending on the flags
323 * given
325 static void
326 MainParseArgs(int argc, char **argv)
328 char *p;
329 int c = '?';
330 int arginc;
331 char *argvalue;
332 const char *getopt_def;
333 char *optscan;
334 Boolean inOption, dashDash = FALSE;
335 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
337 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrst"
338 /* Can't actually use getopt(3) because rescanning is not portable */
340 getopt_def = OPTFLAGS;
341 rearg:
342 inOption = FALSE;
343 optscan = NULL;
344 while(argc > 1) {
345 char *getopt_spec;
346 if(!inOption)
347 optscan = argv[1];
348 c = *optscan++;
349 arginc = 0;
350 if(inOption) {
351 if(c == '\0') {
352 ++argv;
353 --argc;
354 inOption = FALSE;
355 continue;
357 } else {
358 if (c != '-' || dashDash)
359 break;
360 inOption = TRUE;
361 c = *optscan++;
363 /* '-' found at some earlier point */
364 getopt_spec = strchr(getopt_def, c);
365 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
366 /* -<something> found, and <something> should have an arg */
367 inOption = FALSE;
368 arginc = 1;
369 argvalue = optscan;
370 if(*argvalue == '\0') {
371 if (argc < 3)
372 goto noarg;
373 argvalue = argv[2];
374 arginc = 2;
376 } else {
377 argvalue = NULL;
379 switch(c) {
380 case '\0':
381 arginc = 1;
382 inOption = FALSE;
383 break;
384 case 'B':
385 compatMake = TRUE;
386 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
387 break;
388 case 'C':
389 if (chdir(argvalue) == -1) {
390 (void)fprintf(stderr,
391 "%s: chdir %s: %s\n",
392 progname, argvalue,
393 strerror(errno));
394 exit(1);
396 if (getcwd(curdir, MAXPATHLEN) == NULL) {
397 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
398 exit(2);
400 ignorePWD = TRUE;
401 break;
402 case 'D':
403 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
404 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
405 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
406 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
407 break;
408 case 'I':
409 if (argvalue == NULL) goto noarg;
410 Parse_AddIncludeDir(argvalue);
411 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
412 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
413 break;
414 case 'J':
415 if (argvalue == NULL) goto noarg;
416 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
417 (void)fprintf(stderr,
418 "%s: internal error -- J option malformed (%s)\n",
419 progname, argvalue);
420 usage();
422 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
423 (fcntl(jp_1, F_GETFD, 0) < 0)) {
424 #if 0
425 (void)fprintf(stderr,
426 "%s: ###### warning -- J descriptors were closed!\n",
427 progname);
428 exit(2);
429 #endif
430 jp_0 = -1;
431 jp_1 = -1;
432 compatMake = TRUE;
433 } else {
434 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
435 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
436 jobServer = TRUE;
438 break;
439 case 'N':
440 noExecute = TRUE;
441 noRecursiveExecute = TRUE;
442 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
443 break;
444 case 'S':
445 keepgoing = FALSE;
446 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
447 break;
448 case 'T':
449 if (argvalue == NULL) goto noarg;
450 tracefile = bmake_strdup(argvalue);
451 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
452 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
453 break;
454 case 'V':
455 if (argvalue == NULL) goto noarg;
456 printVars = TRUE;
457 (void)Lst_AtEnd(variables, argvalue);
458 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
459 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
460 break;
461 case 'W':
462 parseWarnFatal = TRUE;
463 break;
464 case 'X':
465 varNoExportEnv = TRUE;
466 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
467 break;
468 case 'd':
469 if (argvalue == NULL) goto noarg;
470 /* If '-d-opts' don't pass to children */
471 if (argvalue[0] == '-')
472 argvalue++;
473 else {
474 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
475 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
477 parse_debug_options(argvalue);
478 break;
479 case 'e':
480 checkEnvFirst = TRUE;
481 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
482 break;
483 case 'f':
484 if (argvalue == NULL) goto noarg;
485 (void)Lst_AtEnd(makefiles, argvalue);
486 break;
487 case 'i':
488 ignoreErrors = TRUE;
489 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
490 break;
491 case 'j':
492 if (argvalue == NULL) goto noarg;
493 forceJobs = TRUE;
494 maxJobs = strtol(argvalue, &p, 0);
495 if (*p != '\0' || maxJobs < 1) {
496 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
497 progname);
498 exit(1);
500 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
501 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
502 maxJobTokens = maxJobs;
503 break;
504 case 'k':
505 keepgoing = TRUE;
506 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
507 break;
508 case 'm':
509 if (argvalue == NULL) goto noarg;
510 /* look for magic parent directory search string */
511 if (strncmp(".../", argvalue, 4) == 0) {
512 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
513 found_path, sizeof(found_path)))
514 break; /* nothing doing */
515 (void)Dir_AddDir(sysIncPath, found_path);
516 } else {
517 (void)Dir_AddDir(sysIncPath, argvalue);
519 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
520 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
521 break;
522 case 'n':
523 noExecute = TRUE;
524 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
525 break;
526 case 'q':
527 queryFlag = TRUE;
528 /* Kind of nonsensical, wot? */
529 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
530 break;
531 case 'r':
532 noBuiltins = TRUE;
533 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
534 break;
535 case 's':
536 beSilent = TRUE;
537 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
538 break;
539 case 't':
540 touchFlag = TRUE;
541 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
542 break;
543 case '-':
544 dashDash = TRUE;
545 break;
546 default:
547 case '?':
548 usage();
550 argv += arginc;
551 argc -= arginc;
554 oldVars = TRUE;
557 * See if the rest of the arguments are variable assignments and
558 * perform them if so. Else take them to be targets and stuff them
559 * on the end of the "create" list.
561 for (; argc > 1; ++argv, --argc)
562 if (Parse_IsVar(argv[1])) {
563 Parse_DoVar(argv[1], VAR_CMD);
564 } else {
565 if (!*argv[1])
566 Punt("illegal (null) argument.");
567 if (*argv[1] == '-' && !dashDash)
568 goto rearg;
569 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
572 return;
573 noarg:
574 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
575 progname, c);
576 usage();
580 * Main_ParseArgLine --
581 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
582 * is encountered and by main() when reading the .MAKEFLAGS envariable.
583 * Takes a line of arguments and breaks it into its
584 * component words and passes those words and the number of them to the
585 * MainParseArgs function.
586 * The line should have all its leading whitespace removed.
588 * Input:
589 * line Line to fracture
591 * Results:
592 * None
594 * Side Effects:
595 * Only those that come from the various arguments.
597 void
598 Main_ParseArgLine(const char *line)
600 char **argv; /* Manufactured argument vector */
601 int argc; /* Number of arguments in argv */
602 char *args; /* Space used by the args */
603 char *buf, *p1;
604 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
605 size_t len;
607 if (line == NULL)
608 return;
609 for (; *line == ' '; ++line)
610 continue;
611 if (!*line)
612 return;
614 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
615 (void)snprintf(buf, len, "%s %s", argv0, line);
616 if (p1)
617 free(p1);
619 argv = brk_string(buf, &argc, TRUE, &args);
620 if (argv == NULL) {
621 Error("Unterminated quoted string [%s]", buf);
622 free(buf);
623 return;
625 free(buf);
626 MainParseArgs(argc, argv);
628 free(args);
629 free(argv);
632 Boolean
633 Main_SetObjdir(const char *path)
635 struct stat sb;
636 char *p = NULL;
637 char buf[MAXPATHLEN + 1];
638 Boolean rc = FALSE;
640 /* expand variable substitutions */
641 if (strchr(path, '$') != 0) {
642 snprintf(buf, MAXPATHLEN, "%s", path);
643 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
646 if (path[0] != '/') {
647 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
648 path = buf;
651 /* look for the directory and try to chdir there */
652 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
653 if (chdir(path)) {
654 (void)fprintf(stderr, "make warning: %s: %s.\n",
655 path, strerror(errno));
656 } else {
657 strncpy(objdir, path, MAXPATHLEN);
658 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
659 setenv("PWD", objdir, 1);
660 Dir_InitDot();
661 rc = TRUE;
665 if (p)
666 free(p);
667 return rc;
671 * ReadAllMakefiles --
672 * wrapper around ReadMakefile() to read all.
674 * Results:
675 * TRUE if ok, FALSE on error
677 static int
678 ReadAllMakefiles(const void *p, const void *q)
680 return (ReadMakefile(p, q) == 0);
683 #ifdef SIGINFO
684 /*ARGSUSED*/
685 static void
686 siginfo(int signo)
688 char dir[MAXPATHLEN];
689 char str[2 * MAXPATHLEN];
690 int len;
691 if (getcwd(dir, sizeof(dir)) == NULL)
692 return;
693 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
694 if (len > 0)
695 (void)write(STDERR_FILENO, str, (size_t)len);
697 #endif
700 * main --
701 * The main function, for obvious reasons. Initializes variables
702 * and a few modules, then parses the arguments give it in the
703 * environment and on the command line. Reads the system makefile
704 * followed by either Makefile, makefile or the file given by the
705 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
706 * flags it has received by then uses either the Make or the Compat
707 * module to create the initial list of targets.
709 * Results:
710 * If -q was given, exits -1 if anything was out-of-date. Else it exits
711 * 0.
713 * Side Effects:
714 * The program exits when done. Targets are created. etc. etc. etc.
717 main(int argc, char **argv)
719 Lst targs; /* target nodes to create -- passed to Make_Init */
720 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
721 struct stat sb, sa;
722 char *p1, *path, *pwd;
723 char mdpath[MAXPATHLEN];
724 char *machine = getenv("MACHINE");
725 const char *machine_arch = getenv("MACHINE_ARCH");
726 char *syspath = getenv("MAKESYSPATH");
727 Lst sysMkPath; /* Path of sys.mk */
728 char *cp = NULL, *start;
729 /* avoid faults on read-only strings */
730 static char defsyspath[] = _PATH_DEFSYSPATH;
731 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
732 struct timeval rightnow; /* to initialize random seed */
733 #ifdef MAKE_NATIVE
734 struct utsname utsname;
735 #endif
737 /* default to writing debug to stderr */
738 debug_file = stderr;
740 #ifdef SIGINFO
741 (void)signal(SIGINFO, siginfo);
742 #endif
744 * Set the seed to produce a different random sequence
745 * on each program execution.
747 gettimeofday(&rightnow, NULL);
748 srandom(rightnow.tv_sec + rightnow.tv_usec);
750 if ((progname = strrchr(argv[0], '/')) != NULL)
751 progname++;
752 else
753 progname = argv[0];
754 #ifdef RLIMIT_NOFILE
756 * get rid of resource limit on file descriptors
759 struct rlimit rl;
760 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
761 rl.rlim_cur != rl.rlim_max) {
762 rl.rlim_cur = rl.rlim_max;
763 (void)setrlimit(RLIMIT_NOFILE, &rl);
766 #endif
769 * Get the name of this type of MACHINE from utsname
770 * so we can share an executable for similar machines.
771 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
773 * Note that both MACHINE and MACHINE_ARCH are decided at
774 * run-time.
776 if (!machine) {
777 #ifdef MAKE_NATIVE
778 if (uname(&utsname) == -1) {
779 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
780 strerror(errno));
781 exit(2);
783 machine = utsname.machine;
784 #else
785 #ifdef MAKE_MACHINE
786 machine = MAKE_MACHINE;
787 #else
788 machine = "unknown";
789 #endif
790 #endif
793 if (!machine_arch) {
794 #ifndef MACHINE_ARCH
795 #ifdef MAKE_MACHINE_ARCH
796 machine_arch = MAKE_MACHINE_ARCH;
797 #else
798 machine_arch = "unknown";
799 #endif
800 #else
801 machine_arch = MACHINE_ARCH;
802 #endif
806 * Just in case MAKEOBJDIR wants us to do something tricky.
808 Var_Init(); /* Initialize the lists of variables for
809 * parsing arguments */
810 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
811 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
812 #ifdef MAKE_VERSION
813 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
814 #endif
815 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
817 create = Lst_Init(FALSE);
818 makefiles = Lst_Init(FALSE);
819 printVars = FALSE;
820 variables = Lst_Init(FALSE);
821 beSilent = FALSE; /* Print commands as executed */
822 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
823 noExecute = FALSE; /* Execute all commands */
824 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
825 keepgoing = FALSE; /* Stop on error */
826 allPrecious = FALSE; /* Remove targets when interrupted */
827 queryFlag = FALSE; /* This is not just a check-run */
828 noBuiltins = FALSE; /* Read the built-in rules */
829 touchFlag = FALSE; /* Actually update targets */
830 debug = 0; /* No debug verbosity, please. */
831 jobsRunning = FALSE;
833 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
834 maxJobTokens = maxJobs;
835 compatMake = FALSE; /* No compat mode */
836 ignorePWD = FALSE;
839 * Initialize the parsing, directory and variable modules to prepare
840 * for the reading of inclusion paths and variable settings on the
841 * command line
845 * Initialize various variables.
846 * MAKE also gets this name, for compatibility
847 * .MAKEFLAGS gets set to the empty string just in case.
848 * MFLAGS also gets initialized empty, for compatibility.
850 Parse_Init();
851 Var_Set("MAKE", argv[0], VAR_GLOBAL, 0);
852 Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0);
853 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
854 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
855 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
856 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
859 * Set some other useful macros
862 char tmp[64];
863 const char *ep;
865 if (!(ep = getenv(MAKE_LEVEL))) {
866 ep = "0";
868 Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
869 snprintf(tmp, sizeof(tmp), "%u", getpid());
870 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
871 snprintf(tmp, sizeof(tmp), "%u", getppid());
872 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
874 Job_SetPrefix();
877 * First snag any flags out of the MAKE environment variable.
878 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
879 * in a different format).
881 #ifdef POSIX
882 Main_ParseArgLine(getenv("MAKEFLAGS"));
883 #else
884 Main_ParseArgLine(getenv("MAKE"));
885 #endif
888 * Find where we are (now).
889 * We take care of PWD for the automounter below...
891 if (getcwd(curdir, MAXPATHLEN) == NULL) {
892 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
893 exit(2);
896 MainParseArgs(argc, argv);
899 * Verify that cwd is sane.
901 if (stat(curdir, &sa) == -1) {
902 (void)fprintf(stderr, "%s: %s: %s.\n",
903 progname, curdir, strerror(errno));
904 exit(2);
908 * All this code is so that we know where we are when we start up
909 * on a different machine with pmake.
910 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
911 * since the value of curdir can vary depending on how we got
912 * here. Ie sitting at a shell prompt (shell that provides $PWD)
913 * or via subdir.mk in which case its likely a shell which does
914 * not provide it.
915 * So, to stop it breaking this case only, we ignore PWD if
916 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
918 if (!ignorePWD &&
919 (pwd = getenv("PWD")) != NULL &&
920 getenv("MAKEOBJDIRPREFIX") == NULL) {
921 const char *makeobjdir = getenv("MAKEOBJDIR");
923 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
924 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
925 sa.st_dev == sb.st_dev)
926 (void)strncpy(curdir, pwd, MAXPATHLEN);
929 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
932 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
933 * MAKEOBJDIR is set in the environment, try only that value
934 * and fall back to .CURDIR if it does not exist.
936 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
937 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
938 * of these paths exist, just use .CURDIR.
940 Dir_Init(curdir);
941 (void)Main_SetObjdir(curdir);
943 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
944 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
945 (void)Main_SetObjdir(mdpath);
946 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
947 (void)Main_SetObjdir(path);
948 } else {
949 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
950 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
951 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
952 _PATH_OBJDIRPREFIX, curdir);
953 (void)Main_SetObjdir(mdpath);
958 * Be compatible if user did not specify -j and did not explicitly
959 * turned compatibility on
961 if (!compatMake && !forceJobs) {
962 compatMake = TRUE;
966 * Initialize archive, target and suffix modules in preparation for
967 * parsing the makefile(s)
969 Arch_Init();
970 Targ_Init();
971 Suff_Init();
972 Trace_Init(tracefile);
974 DEFAULT = NULL;
975 (void)time(&now);
977 Trace_Log(MAKESTART, NULL);
980 * Set up the .TARGETS variable to contain the list of targets to be
981 * created. If none specified, make the variable empty -- the parser
982 * will fill the thing in with the default or .MAIN target.
984 if (!Lst_IsEmpty(create)) {
985 LstNode ln;
987 for (ln = Lst_First(create); ln != NULL;
988 ln = Lst_Succ(ln)) {
989 char *name = (char *)Lst_Datum(ln);
991 Var_Append(".TARGETS", name, VAR_GLOBAL);
993 } else
994 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
998 * If no user-supplied system path was given (through the -m option)
999 * add the directories from the DEFSYSPATH (more than one may be given
1000 * as dir1:...:dirn) to the system include path.
1002 if (syspath == NULL || *syspath == '\0')
1003 syspath = defsyspath;
1004 else
1005 syspath = bmake_strdup(syspath);
1007 for (start = syspath; *start != '\0'; start = cp) {
1008 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1009 continue;
1010 if (*cp == ':') {
1011 *cp++ = '\0';
1013 /* look for magic parent directory search string */
1014 if (strncmp(".../", start, 4) != 0) {
1015 (void)Dir_AddDir(defIncPath, start);
1016 } else {
1017 if (Dir_FindHereOrAbove(curdir, start+4,
1018 found_path, sizeof(found_path))) {
1019 (void)Dir_AddDir(defIncPath, found_path);
1023 if (syspath != defsyspath)
1024 free(syspath);
1027 * Read in the built-in rules first, followed by the specified
1028 * makefile, if it was (makefile != NULL), or the default
1029 * makefile and Makefile, in that order, if it wasn't.
1031 if (!noBuiltins) {
1032 LstNode ln;
1034 sysMkPath = Lst_Init(FALSE);
1035 Dir_Expand(_PATH_DEFSYSMK,
1036 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1037 sysMkPath);
1038 if (Lst_IsEmpty(sysMkPath))
1039 Fatal("%s: no system rules (%s).", progname,
1040 _PATH_DEFSYSMK);
1041 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1042 if (ln == NULL)
1043 Fatal("%s: cannot open %s.", progname,
1044 (char *)Lst_Datum(ln));
1047 if (!Lst_IsEmpty(makefiles)) {
1048 LstNode ln;
1050 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1051 if (ln != NULL)
1052 Fatal("%s: cannot open %s.", progname,
1053 (char *)Lst_Datum(ln));
1054 } else if (ReadMakefile("makefile", NULL) != 0)
1055 (void)ReadMakefile("Makefile", NULL);
1057 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1058 if (!noBuiltins || !printVars) {
1059 doing_depend = TRUE;
1060 (void)ReadMakefile(".depend", NULL);
1061 doing_depend = FALSE;
1064 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1065 if (p1)
1066 free(p1);
1068 if (!compatMake)
1069 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1070 if (DEBUG(JOB))
1071 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1072 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1074 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1076 Check_Cwd_av(0, NULL, 0); /* initialize it */
1080 * For compatibility, look at the directories in the VPATH variable
1081 * and add them to the search path, if the variable is defined. The
1082 * variable's value is in the same format as the PATH envariable, i.e.
1083 * <directory>:<directory>:<directory>...
1085 if (Var_Exists("VPATH", VAR_CMD)) {
1086 char *vpath, savec;
1088 * GCC stores string constants in read-only memory, but
1089 * Var_Subst will want to write this thing, so store it
1090 * in an array
1092 static char VPATH[] = "${VPATH}";
1094 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1095 path = vpath;
1096 do {
1097 /* skip to end of directory */
1098 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1099 continue;
1100 /* Save terminator character so know when to stop */
1101 savec = *cp;
1102 *cp = '\0';
1103 /* Add directory to search path */
1104 (void)Dir_AddDir(dirSearchPath, path);
1105 *cp = savec;
1106 path = cp + 1;
1107 } while (savec == ':');
1108 free(vpath);
1112 * Now that all search paths have been read for suffixes et al, it's
1113 * time to add the default search path to their lists...
1115 Suff_DoPaths();
1118 * Propagate attributes through :: dependency lists.
1120 Targ_Propagate();
1122 /* print the initial graph, if the user requested it */
1123 if (DEBUG(GRAPH1))
1124 Targ_PrintGraph(1);
1126 /* print the values of any variables requested by the user */
1127 if (printVars) {
1128 LstNode ln;
1130 for (ln = Lst_First(variables); ln != NULL;
1131 ln = Lst_Succ(ln)) {
1132 char *var = (char *)Lst_Datum(ln);
1133 char *value;
1135 if (strchr(var, '$')) {
1136 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1137 } else {
1138 value = Var_Value(var, VAR_GLOBAL, &p1);
1140 printf("%s\n", value ? value : "");
1141 if (p1)
1142 free(p1);
1144 } else {
1146 * Have now read the entire graph and need to make a list of
1147 * targets to create. If none was given on the command line,
1148 * we consult the parsing module to find the main target(s)
1149 * to create.
1151 if (Lst_IsEmpty(create))
1152 targs = Parse_MainName();
1153 else
1154 targs = Targ_FindList(create, TARG_CREATE);
1156 if (!compatMake) {
1158 * Initialize job module before traversing the graph
1159 * now that any .BEGIN and .END targets have been read.
1160 * This is done only if the -q flag wasn't given
1161 * (to prevent the .BEGIN from being executed should
1162 * it exist).
1164 if (!queryFlag) {
1165 Job_Init();
1166 jobsRunning = TRUE;
1169 /* Traverse the graph, checking on all the targets */
1170 outOfDate = Make_Run(targs);
1171 } else {
1173 * Compat_Init will take care of creating all the
1174 * targets as well as initializing the module.
1176 Compat_Run(targs);
1180 #ifdef CLEANUP
1181 Lst_Destroy(targs, NULL);
1182 Lst_Destroy(variables, NULL);
1183 Lst_Destroy(makefiles, NULL);
1184 Lst_Destroy(create, (FreeProc *)free);
1185 #endif
1187 /* print the graph now it's been processed if the user requested it */
1188 if (DEBUG(GRAPH2))
1189 Targ_PrintGraph(2);
1191 Trace_Log(MAKEEND, 0);
1193 Suff_End();
1194 Targ_End();
1195 Arch_End();
1196 Var_End();
1197 Parse_End();
1198 Dir_End();
1199 Job_End();
1200 Trace_End();
1202 return outOfDate ? 1 : 0;
1206 * ReadMakefile --
1207 * Open and parse the given makefile.
1209 * Results:
1210 * 0 if ok. -1 if couldn't open file.
1212 * Side Effects:
1213 * lots
1215 static int
1216 ReadMakefile(const void *p, const void *q __unused)
1218 const char *fname = p; /* makefile to read */
1219 int fd;
1220 size_t len = MAXPATHLEN;
1221 char *name, *path = bmake_malloc(len);
1222 int setMAKEFILE;
1224 if (!strcmp(fname, "-")) {
1225 Parse_File("(stdin)", dup(fileno(stdin)));
1226 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1227 } else {
1228 setMAKEFILE = strcmp(fname, ".depend");
1230 /* if we've chdir'd, rebuild the path name */
1231 if (strcmp(curdir, objdir) && *fname != '/') {
1232 size_t plen = strlen(curdir) + strlen(fname) + 2;
1233 if (len < plen)
1234 path = bmake_realloc(path, len = 2 * plen);
1236 (void)snprintf(path, len, "%s/%s", curdir, fname);
1237 fd = open(path, O_RDONLY);
1238 if (fd != -1) {
1239 fname = path;
1240 goto found;
1243 /* If curdir failed, try objdir (ala .depend) */
1244 plen = strlen(objdir) + strlen(fname) + 2;
1245 if (len < plen)
1246 path = bmake_realloc(path, len = 2 * plen);
1247 (void)snprintf(path, len, "%s/%s", objdir, fname);
1248 fd = open(path, O_RDONLY);
1249 if (fd != -1) {
1250 fname = path;
1251 goto found;
1253 } else {
1254 fd = open(fname, O_RDONLY);
1255 if (fd != -1)
1256 goto found;
1258 /* look in -I and system include directories. */
1259 name = Dir_FindFile(fname, parseIncPath);
1260 if (!name)
1261 name = Dir_FindFile(fname,
1262 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1263 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1264 if (name)
1265 free(name);
1266 free(path);
1267 return(-1);
1269 fname = name;
1271 * set the MAKEFILE variable desired by System V fans -- the
1272 * placement of the setting here means it gets set to the last
1273 * makefile specified, as it is set by SysV make.
1275 found:
1276 if (setMAKEFILE)
1277 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1278 Parse_File(fname, fd);
1280 free(path);
1281 return(0);
1286 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1287 * in situations that would not arrise with ./obj (links or not).
1288 * This tends to break things like:
1290 * build:
1291 * ${MAKE} includes
1293 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1294 * opposed to an argument) in a command line and if so returns
1295 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1296 * the Makefile hold true.
1298 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1300 * The chdir() only happens in the child process, and does nothing if
1301 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1302 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1303 * do nothing - to ensure historic semantics can be retained.
1305 static int Check_Cwd_Off = 0;
1307 static char *
1308 Check_Cwd_av(int ac, char **av, int copy)
1310 static char *make[4];
1311 static char *cur_dir = NULL;
1312 char **mp;
1313 char *cp;
1314 int is_cmd, next_cmd;
1315 int i;
1316 int n;
1318 if (Check_Cwd_Off) {
1319 if (DEBUG(CWD))
1320 fprintf(debug_file, "check_cwd: check is off.\n");
1321 return NULL;
1324 if (make[0] == NULL) {
1325 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1326 Check_Cwd_Off = 1;
1327 if (DEBUG(CWD))
1328 fprintf(debug_file, "check_cwd: turning check off.\n");
1329 return NULL;
1332 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1333 if ((make[0] = strrchr(make[1], '/')) == NULL) {
1334 make[0] = make[1];
1335 make[1] = NULL;
1336 } else
1337 ++make[0];
1338 make[2] = NULL;
1339 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1341 if (ac == 0 || av == NULL) {
1342 if (DEBUG(CWD))
1343 fprintf(debug_file, "check_cwd: empty command.\n");
1344 return NULL; /* initialization only */
1347 if (getenv("MAKEOBJDIR") == NULL &&
1348 getenv("MAKEOBJDIRPREFIX") == NULL) {
1349 if (DEBUG(CWD))
1350 fprintf(debug_file, "check_cwd: no obj dirs.\n");
1351 return NULL;
1355 next_cmd = 1;
1356 for (i = 0; i < ac; ++i) {
1357 is_cmd = next_cmd;
1359 n = strlen(av[i]);
1360 cp = &(av[i])[n - 1];
1361 if (strspn(av[i], "|&;") == (size_t)n) {
1362 next_cmd = 1;
1363 continue;
1364 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1365 next_cmd = 1;
1366 if (copy) {
1367 do {
1368 *cp-- = '\0';
1369 } while (*cp == ';' || *cp == '&' || *cp == '|' ||
1370 *cp == ')' || *cp == '}') ;
1371 } else {
1373 * XXX this should not happen.
1375 fprintf(stderr, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1376 progname, av[i]);
1378 } else
1379 next_cmd = 0;
1381 cp = av[i];
1382 if (*cp == ';' || *cp == '&' || *cp == '|')
1383 is_cmd = 1;
1385 if (DEBUG(CWD))
1386 fprintf(debug_file, "av[%d] == %s '%s'",
1387 i, (is_cmd) ? "cmd" : "arg", av[i]);
1388 if (is_cmd != 0) {
1389 if (*cp == '(' || *cp == '{' ||
1390 *cp == ';' || *cp == '&' || *cp == '|') {
1391 do {
1392 ++cp;
1393 } while (*cp == '(' || *cp == '{' ||
1394 *cp == ';' || *cp == '&' || *cp == '|');
1395 if (*cp == '\0') {
1396 next_cmd = 1;
1397 continue;
1400 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1401 if (DEBUG(CWD))
1402 fprintf(debug_file, " == cd, done.\n");
1403 return NULL;
1405 for (mp = make; *mp != NULL; ++mp) {
1406 n = strlen(*mp);
1407 if (strcmp(cp, *mp) == 0) {
1408 if (DEBUG(CWD))
1409 fprintf(debug_file, " %s == '%s', chdir(%s)\n",
1410 cp, *mp, cur_dir);
1411 return cur_dir;
1415 if (DEBUG(CWD))
1416 fprintf(debug_file, "\n");
1418 return NULL;
1421 char *
1422 Check_Cwd_Cmd(const char *cmd)
1424 char *cp, *bp;
1425 char **av;
1426 int ac;
1428 if (Check_Cwd_Off)
1429 return NULL;
1431 if (cmd) {
1432 av = brk_string(cmd, &ac, TRUE, &bp);
1433 if (DEBUG(CWD))
1434 fprintf(debug_file, "splitting: '%s' -> %d words\n",
1435 cmd, ac);
1436 } else {
1437 ac = 0;
1438 av = NULL;
1439 bp = NULL;
1441 cp = Check_Cwd_av(ac, av, 1);
1442 if (bp)
1443 free(bp);
1444 if (av)
1445 free(av);
1446 return cp;
1449 void
1450 Check_Cwd(const char **argv)
1452 char *cp;
1453 int ac;
1455 if (Check_Cwd_Off)
1456 return;
1458 for (ac = 0; argv[ac] != NULL; ++ac)
1459 /* NOTHING */;
1460 if (ac == 3 && *argv[1] == '-') {
1461 cp = Check_Cwd_Cmd(argv[2]);
1462 } else {
1463 cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1465 if (cp) {
1466 chdir(cp);
1471 * Cmd_Exec --
1472 * Execute the command in cmd, and return the output of that command
1473 * in a string.
1475 * Results:
1476 * A string containing the output of the command, or the empty string
1477 * If errnum is not NULL, it contains the reason for the command failure
1479 * Side Effects:
1480 * The string must be freed by the caller.
1482 char *
1483 Cmd_Exec(const char *cmd, const char **errnum)
1485 const char *args[4]; /* Args for invoking the shell */
1486 int fds[2]; /* Pipe streams */
1487 int cpid; /* Child PID */
1488 int pid; /* PID from wait() */
1489 char *res; /* result */
1490 int status; /* command exit status */
1491 Buffer buf; /* buffer to store the result */
1492 char *cp;
1493 int cc;
1496 *errnum = NULL;
1498 if (!shellName)
1499 Shell_Init();
1501 * Set up arguments for shell
1503 args[0] = shellName;
1504 args[1] = "-c";
1505 args[2] = cmd;
1506 args[3] = NULL;
1509 * Open a pipe for fetching its output
1511 if (pipe(fds) == -1) {
1512 *errnum = "Couldn't create pipe for \"%s\"";
1513 goto bad;
1517 * Fork
1519 switch (cpid = vfork()) {
1520 case 0:
1522 * Close input side of pipe
1524 (void)close(fds[0]);
1527 * Duplicate the output stream to the shell's output, then
1528 * shut the extra thing down. Note we don't fetch the error
1529 * stream...why not? Why?
1531 (void)dup2(fds[1], 1);
1532 (void)close(fds[1]);
1534 Var_ExportVars();
1536 (void)execv(shellPath, UNCONST(args));
1537 _exit(1);
1538 /*NOTREACHED*/
1540 case -1:
1541 *errnum = "Couldn't exec \"%s\"";
1542 goto bad;
1544 default:
1546 * No need for the writing half
1548 (void)close(fds[1]);
1550 Buf_Init(&buf, 0);
1552 do {
1553 char result[BUFSIZ];
1554 cc = read(fds[0], result, sizeof(result));
1555 if (cc > 0)
1556 Buf_AddBytes(&buf, cc, result);
1558 while (cc > 0 || (cc == -1 && errno == EINTR));
1561 * Close the input side of the pipe.
1563 (void)close(fds[0]);
1566 * Wait for the process to exit.
1568 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0))
1569 continue;
1571 cc = Buf_Size(&buf);
1572 res = Buf_Destroy(&buf, FALSE);
1574 if (cc == 0)
1575 *errnum = "Couldn't read shell's output for \"%s\"";
1577 if (WIFSIGNALED(status))
1578 *errnum = "\"%s\" exited on a signal";
1579 else if (WEXITSTATUS(status) != 0)
1580 *errnum = "\"%s\" returned non-zero status";
1583 * Null-terminate the result, convert newlines to spaces and
1584 * install it in the variable.
1586 res[cc] = '\0';
1587 cp = &res[cc];
1589 if (cc > 0 && *--cp == '\n') {
1591 * A final newline is just stripped
1593 *cp-- = '\0';
1595 while (cp >= res) {
1596 if (*cp == '\n') {
1597 *cp = ' ';
1599 cp--;
1601 break;
1603 return res;
1604 bad:
1605 res = bmake_malloc(1);
1606 *res = '\0';
1607 return res;
1611 * Error --
1612 * Print an error message given its format.
1614 * Results:
1615 * None.
1617 * Side Effects:
1618 * The message is printed.
1620 /* VARARGS */
1621 void
1622 Error(const char *fmt, ...)
1624 va_list ap;
1625 FILE *err_file;
1627 err_file = debug_file;
1628 if (err_file == stdout)
1629 err_file = stderr;
1630 for (;;) {
1631 va_start(ap, fmt);
1632 fprintf(err_file, "%s: ", progname);
1633 (void)vfprintf(err_file, fmt, ap);
1634 va_end(ap);
1635 (void)fprintf(err_file, "\n");
1636 (void)fflush(err_file);
1637 if (err_file == stderr)
1638 break;
1639 err_file = stderr;
1644 * Fatal --
1645 * Produce a Fatal error message. If jobs are running, waits for them
1646 * to finish.
1648 * Results:
1649 * None
1651 * Side Effects:
1652 * The program exits
1654 /* VARARGS */
1655 void
1656 Fatal(const char *fmt, ...)
1658 va_list ap;
1660 va_start(ap, fmt);
1661 if (jobsRunning)
1662 Job_Wait();
1664 (void)vfprintf(stderr, fmt, ap);
1665 va_end(ap);
1666 (void)fprintf(stderr, "\n");
1667 (void)fflush(stderr);
1669 PrintOnError(NULL);
1671 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1672 Targ_PrintGraph(2);
1673 Trace_Log(MAKEERROR, 0);
1674 exit(2); /* Not 1 so -q can distinguish error */
1678 * Punt --
1679 * Major exception once jobs are being created. Kills all jobs, prints
1680 * a message and exits.
1682 * Results:
1683 * None
1685 * Side Effects:
1686 * All children are killed indiscriminately and the program Lib_Exits
1688 /* VARARGS */
1689 void
1690 Punt(const char *fmt, ...)
1692 va_list ap;
1694 va_start(ap, fmt);
1695 (void)fprintf(stderr, "%s: ", progname);
1696 (void)vfprintf(stderr, fmt, ap);
1697 va_end(ap);
1698 (void)fprintf(stderr, "\n");
1699 (void)fflush(stderr);
1701 PrintOnError(NULL);
1703 DieHorribly();
1707 * DieHorribly --
1708 * Exit without giving a message.
1710 * Results:
1711 * None
1713 * Side Effects:
1714 * A big one...
1716 void
1717 DieHorribly(void)
1719 if (jobsRunning)
1720 Job_AbortAll();
1721 if (DEBUG(GRAPH2))
1722 Targ_PrintGraph(2);
1723 Trace_Log(MAKEERROR, 0);
1724 exit(2); /* Not 1, so -q can distinguish error */
1728 * Finish --
1729 * Called when aborting due to errors in child shell to signal
1730 * abnormal exit.
1732 * Results:
1733 * None
1735 * Side Effects:
1736 * The program exits
1738 void
1739 Finish(int errors)
1740 /* number of errors encountered in Make_Make */
1742 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1746 * enunlink --
1747 * Remove a file carefully, avoiding directories.
1750 eunlink(const char *file)
1752 struct stat st;
1754 if (lstat(file, &st) == -1)
1755 return -1;
1757 if (S_ISDIR(st.st_mode)) {
1758 errno = EISDIR;
1759 return -1;
1761 return unlink(file);
1765 * execError --
1766 * Print why exec failed, avoiding stdio.
1768 void
1769 execError(const char *af, const char *av)
1771 #ifdef USE_IOVEC
1772 int i = 0;
1773 struct iovec iov[8];
1774 #define IOADD(s) \
1775 (void)(iov[i].iov_base = UNCONST(s), \
1776 iov[i].iov_len = strlen(iov[i].iov_base), \
1777 i++)
1778 #else
1779 #define IOADD(void)write(2, s, strlen(s))
1780 #endif
1782 IOADD(progname);
1783 IOADD(": ");
1784 IOADD(af);
1785 IOADD("(");
1786 IOADD(av);
1787 IOADD(") failed (");
1788 IOADD(strerror(errno));
1789 IOADD(")\n");
1791 #ifdef USE_IOVEC
1792 (void)writev(2, iov, 8);
1793 #endif
1797 * usage --
1798 * exit with usage message
1800 static void
1801 usage(void)
1803 (void)fprintf(stderr,
1804 "usage: %s [-BeikNnqrstWX] \n\
1805 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1806 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1807 [-V variable] [variable=value] [target ...]\n", progname);
1808 exit(2);
1813 PrintAddr(void *a, void *b)
1815 printf("%lx ", (unsigned long) a);
1816 return b ? 0 : 0;
1821 void
1822 PrintOnError(const char *s)
1824 char tmp[64];
1825 char *cp;
1827 if (s)
1828 printf("%s", s);
1830 printf("\n%s: stopped in %s\n", progname, curdir);
1831 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1832 sizeof(tmp) - 1);
1833 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1834 if (cp) {
1835 if (*cp)
1836 printf("%s", cp);
1837 free(cp);
1841 void
1842 Main_ExportMAKEFLAGS(Boolean first)
1844 static int once = 1;
1845 char tmp[64];
1846 char *s;
1848 if (once != first)
1849 return;
1850 once = 0;
1852 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1853 sizeof(tmp));
1854 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1855 if (s && *s) {
1856 #ifdef POSIX
1857 setenv("MAKEFLAGS", s, 1);
1858 #else
1859 setenv("MAKE", s, 1);
1860 #endif