pci: don't do sanity check for missing pci bus, the check can misfire.
[minix.git] / commands / make / main.c
blob54f4e674460011ac2f9950b8c1590595f83499aa
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 ignorePWD = TRUE;
397 break;
398 case 'D':
399 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
400 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
401 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
402 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
403 break;
404 case 'I':
405 if (argvalue == NULL) goto noarg;
406 Parse_AddIncludeDir(argvalue);
407 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
408 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
409 break;
410 case 'J':
411 if (argvalue == NULL) goto noarg;
412 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
413 (void)fprintf(stderr,
414 "%s: internal error -- J option malformed (%s)\n",
415 progname, argvalue);
416 usage();
418 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
419 (fcntl(jp_1, F_GETFD, 0) < 0)) {
420 #if 0
421 (void)fprintf(stderr,
422 "%s: ###### warning -- J descriptors were closed!\n",
423 progname);
424 exit(2);
425 #endif
426 jp_0 = -1;
427 jp_1 = -1;
428 compatMake = TRUE;
429 } else {
430 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
431 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
432 jobServer = TRUE;
434 break;
435 case 'N':
436 noExecute = TRUE;
437 noRecursiveExecute = TRUE;
438 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
439 break;
440 case 'S':
441 keepgoing = FALSE;
442 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
443 break;
444 case 'T':
445 if (argvalue == NULL) goto noarg;
446 tracefile = bmake_strdup(argvalue);
447 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
448 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
449 break;
450 case 'V':
451 if (argvalue == NULL) goto noarg;
452 printVars = TRUE;
453 (void)Lst_AtEnd(variables, argvalue);
454 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
455 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
456 break;
457 case 'W':
458 parseWarnFatal = TRUE;
459 break;
460 case 'X':
461 varNoExportEnv = TRUE;
462 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
463 break;
464 case 'd':
465 if (argvalue == NULL) goto noarg;
466 /* If '-d-opts' don't pass to children */
467 if (argvalue[0] == '-')
468 argvalue++;
469 else {
470 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
471 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
473 parse_debug_options(argvalue);
474 break;
475 case 'e':
476 checkEnvFirst = TRUE;
477 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
478 break;
479 case 'f':
480 if (argvalue == NULL) goto noarg;
481 (void)Lst_AtEnd(makefiles, argvalue);
482 break;
483 case 'i':
484 ignoreErrors = TRUE;
485 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
486 break;
487 case 'j':
488 if (argvalue == NULL) goto noarg;
489 forceJobs = TRUE;
490 maxJobs = strtol(argvalue, &p, 0);
491 if (*p != '\0' || maxJobs < 1) {
492 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
493 progname);
494 exit(1);
496 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
497 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
498 maxJobTokens = maxJobs;
499 break;
500 case 'k':
501 keepgoing = TRUE;
502 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
503 break;
504 case 'm':
505 if (argvalue == NULL) goto noarg;
506 /* look for magic parent directory search string */
507 if (strncmp(".../", argvalue, 4) == 0) {
508 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
509 found_path, sizeof(found_path)))
510 break; /* nothing doing */
511 (void)Dir_AddDir(sysIncPath, found_path);
513 } else {
514 (void)Dir_AddDir(sysIncPath, argvalue);
516 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
517 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
518 break;
519 case 'n':
520 noExecute = TRUE;
521 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
522 break;
523 case 'q':
524 queryFlag = TRUE;
525 /* Kind of nonsensical, wot? */
526 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
527 break;
528 case 'r':
529 noBuiltins = TRUE;
530 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
531 break;
532 case 's':
533 beSilent = TRUE;
534 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
535 break;
536 case 't':
537 touchFlag = TRUE;
538 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
539 break;
540 case '-':
541 dashDash = TRUE;
542 break;
543 default:
544 case '?':
545 usage();
547 argv += arginc;
548 argc -= arginc;
551 oldVars = TRUE;
554 * See if the rest of the arguments are variable assignments and
555 * perform them if so. Else take them to be targets and stuff them
556 * on the end of the "create" list.
558 for (; argc > 1; ++argv, --argc)
559 if (Parse_IsVar(argv[1])) {
560 Parse_DoVar(argv[1], VAR_CMD);
561 } else {
562 if (!*argv[1])
563 Punt("illegal (null) argument.");
564 if (*argv[1] == '-' && !dashDash)
565 goto rearg;
566 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
569 return;
570 noarg:
571 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
572 progname, c);
573 usage();
577 * Main_ParseArgLine --
578 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
579 * is encountered and by main() when reading the .MAKEFLAGS envariable.
580 * Takes a line of arguments and breaks it into its
581 * component words and passes those words and the number of them to the
582 * MainParseArgs function.
583 * The line should have all its leading whitespace removed.
585 * Input:
586 * line Line to fracture
588 * Results:
589 * None
591 * Side Effects:
592 * Only those that come from the various arguments.
594 void
595 Main_ParseArgLine(const char *line)
597 char **argv; /* Manufactured argument vector */
598 int argc; /* Number of arguments in argv */
599 char *args; /* Space used by the args */
600 char *buf, *p1;
601 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
602 size_t len;
604 if (line == NULL)
605 return;
606 for (; *line == ' '; ++line)
607 continue;
608 if (!*line)
609 return;
611 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
612 (void)snprintf(buf, len, "%s %s", argv0, line);
613 if (p1)
614 free(p1);
616 argv = brk_string(buf, &argc, TRUE, &args);
617 if (argv == NULL) {
618 Error("Unterminated quoted string [%s]", buf);
619 free(buf);
620 return;
622 free(buf);
623 MainParseArgs(argc, argv);
625 free(args);
626 free(argv);
629 Boolean
630 Main_SetObjdir(const char *path)
632 struct stat sb;
633 char *p = NULL;
634 char buf[MAXPATHLEN + 1];
635 Boolean rc = FALSE;
637 /* expand variable substitutions */
638 if (strchr(path, '$') != 0) {
639 snprintf(buf, MAXPATHLEN, "%s", path);
640 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
643 if (path[0] != '/') {
644 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
645 path = buf;
648 /* look for the directory and try to chdir there */
649 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
650 if (chdir(path)) {
651 (void)fprintf(stderr, "make warning: %s: %s.\n",
652 path, strerror(errno));
653 } else {
654 strncpy(objdir, path, MAXPATHLEN);
655 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
656 setenv("PWD", objdir, 1);
657 Dir_InitDot();
658 rc = TRUE;
662 if (p)
663 free(p);
664 return rc;
668 * ReadAllMakefiles --
669 * wrapper around ReadMakefile() to read all.
671 * Results:
672 * TRUE if ok, FALSE on error
674 static int
675 ReadAllMakefiles(const void *p, const void *q)
677 return (ReadMakefile(p, q) == 0);
680 #ifdef SIGINFO
681 /*ARGSUSED*/
682 static void
683 siginfo(int signo)
685 char dir[MAXPATHLEN];
686 char str[2 * MAXPATHLEN];
687 int len;
688 if (getcwd(dir, sizeof(dir)) == NULL)
689 return;
690 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
691 if (len > 0)
692 (void)write(STDERR_FILENO, str, (size_t)len);
694 #endif
697 * main --
698 * The main function, for obvious reasons. Initializes variables
699 * and a few modules, then parses the arguments give it in the
700 * environment and on the command line. Reads the system makefile
701 * followed by either Makefile, makefile or the file given by the
702 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
703 * flags it has received by then uses either the Make or the Compat
704 * module to create the initial list of targets.
706 * Results:
707 * If -q was given, exits -1 if anything was out-of-date. Else it exits
708 * 0.
710 * Side Effects:
711 * The program exits when done. Targets are created. etc. etc. etc.
714 main(int argc, char **argv)
716 Lst targs; /* target nodes to create -- passed to Make_Init */
717 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
718 struct stat sb, sa;
719 char *p1, *path, *pwd;
720 char mdpath[MAXPATHLEN];
721 char *machine = getenv("MACHINE");
722 const char *machine_arch = getenv("MACHINE_ARCH");
723 char *syspath = getenv("MAKESYSPATH");
724 Lst sysMkPath; /* Path of sys.mk */
725 char *cp = NULL, *start;
726 /* avoid faults on read-only strings */
727 static char defsyspath[] = _PATH_DEFSYSPATH;
728 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
729 struct timeval rightnow; /* to initialize random seed */
730 #ifdef MAKE_NATIVE
731 struct utsname utsname;
732 #endif
734 /* default to writing debug to stderr */
735 debug_file = stderr;
737 #ifdef SIGINFO
738 (void)signal(SIGINFO, siginfo);
739 #endif
741 * Set the seed to produce a different random sequence
742 * on each program execution.
744 gettimeofday(&rightnow, NULL);
745 srandom(rightnow.tv_sec + rightnow.tv_usec);
747 if ((progname = strrchr(argv[0], '/')) != NULL)
748 progname++;
749 else
750 progname = argv[0];
751 #if defined(RLIMIT_NOFILE) && !defined(__minix)
753 * get rid of resource limit on file descriptors
756 struct rlimit rl;
757 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
758 rl.rlim_cur != rl.rlim_max) {
759 rl.rlim_cur = rl.rlim_max;
760 (void)setrlimit(RLIMIT_NOFILE, &rl);
763 #endif
766 * Get the name of this type of MACHINE from utsname
767 * so we can share an executable for similar machines.
768 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
770 * Note that both MACHINE and MACHINE_ARCH are decided at
771 * run-time.
773 if (!machine) {
774 #ifdef MAKE_NATIVE
775 if (uname(&utsname) == -1) {
776 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
777 strerror(errno));
778 exit(2);
780 machine = utsname.machine;
781 #else
782 #ifdef MAKE_MACHINE
783 machine = MAKE_MACHINE;
784 #else
785 machine = "unknown";
786 #endif
787 #endif
790 if (!machine_arch) {
791 #ifndef MACHINE_ARCH
792 #ifdef MAKE_MACHINE_ARCH
793 machine_arch = MAKE_MACHINE_ARCH;
794 #else
795 machine_arch = "unknown";
796 #endif
797 #else
798 machine_arch = MACHINE_ARCH;
799 #endif
803 * Just in case MAKEOBJDIR wants us to do something tricky.
805 Var_Init(); /* Initialize the lists of variables for
806 * parsing arguments */
807 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
808 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
809 #ifdef MAKE_VERSION
810 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
811 #endif
812 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
814 create = Lst_Init(FALSE);
815 makefiles = Lst_Init(FALSE);
816 printVars = FALSE;
817 variables = Lst_Init(FALSE);
818 beSilent = FALSE; /* Print commands as executed */
819 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
820 noExecute = FALSE; /* Execute all commands */
821 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
822 keepgoing = FALSE; /* Stop on error */
823 allPrecious = FALSE; /* Remove targets when interrupted */
824 queryFlag = FALSE; /* This is not just a check-run */
825 noBuiltins = FALSE; /* Read the built-in rules */
826 touchFlag = FALSE; /* Actually update targets */
827 debug = 0; /* No debug verbosity, please. */
828 jobsRunning = FALSE;
830 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
831 maxJobTokens = maxJobs;
832 compatMake = FALSE; /* No compat mode */
833 ignorePWD = FALSE;
836 * Initialize the parsing, directory and variable modules to prepare
837 * for the reading of inclusion paths and variable settings on the
838 * command line
842 * Initialize various variables.
843 * MAKE also gets this name, for compatibility
844 * .MAKEFLAGS gets set to the empty string just in case.
845 * MFLAGS also gets initialized empty, for compatibility.
847 Parse_Init();
848 Var_Set("MAKE", argv[0], VAR_GLOBAL, 0);
849 Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0);
850 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
851 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
852 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
853 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
856 * Set some other useful macros
859 char tmp[64];
860 const char *ep;
862 if (!(ep = getenv(MAKE_LEVEL))) {
863 ep = "0";
865 Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
866 snprintf(tmp, sizeof(tmp), "%u", getpid());
867 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
868 snprintf(tmp, sizeof(tmp), "%u", getppid());
869 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
871 Job_SetPrefix();
874 * First snag any flags out of the MAKE environment variable.
875 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
876 * in a different format).
878 #ifdef POSIX
879 Main_ParseArgLine(getenv("MAKEFLAGS"));
880 #else
881 Main_ParseArgLine(getenv("MAKE"));
882 #endif
884 MainParseArgs(argc, argv);
887 * Find where we are (now) and take care of PWD for the automounter...
888 * All this code is so that we know where we are when we start up
889 * on a different machine with pmake.
891 if (getcwd(curdir, MAXPATHLEN) == NULL) {
892 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
893 exit(2);
896 if (stat(curdir, &sa) == -1) {
897 (void)fprintf(stderr, "%s: %s: %s.\n",
898 progname, curdir, strerror(errno));
899 exit(2);
903 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
904 * since the value of curdir can vary depending on how we got
905 * here. Ie sitting at a shell prompt (shell that provides $PWD)
906 * or via subdir.mk in which case its likely a shell which does
907 * not provide it.
908 * So, to stop it breaking this case only, we ignore PWD if
909 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
911 if (!ignorePWD &&
912 (pwd = getenv("PWD")) != NULL &&
913 getenv("MAKEOBJDIRPREFIX") == NULL) {
914 const char *makeobjdir = getenv("MAKEOBJDIR");
916 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
917 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
918 sa.st_dev == sb.st_dev)
919 (void)strncpy(curdir, pwd, MAXPATHLEN);
922 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
925 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
926 * MAKEOBJDIR is set in the environment, try only that value
927 * and fall back to .CURDIR if it does not exist.
929 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
930 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
931 * of these paths exist, just use .CURDIR.
933 Dir_Init(curdir);
934 (void)Main_SetObjdir(curdir);
936 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
937 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
938 (void)Main_SetObjdir(mdpath);
939 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
940 (void)Main_SetObjdir(path);
941 } else {
942 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
943 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
944 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
945 _PATH_OBJDIRPREFIX, curdir);
946 (void)Main_SetObjdir(mdpath);
951 * Be compatible if user did not specify -j and did not explicitly
952 * turned compatibility on
954 if (!compatMake && !forceJobs) {
955 compatMake = TRUE;
959 * Initialize archive, target and suffix modules in preparation for
960 * parsing the makefile(s)
962 Arch_Init();
963 Targ_Init();
964 Suff_Init();
965 Trace_Init(tracefile);
967 DEFAULT = NULL;
968 (void)time(&now);
970 Trace_Log(MAKESTART, NULL);
973 * Set up the .TARGETS variable to contain the list of targets to be
974 * created. If none specified, make the variable empty -- the parser
975 * will fill the thing in with the default or .MAIN target.
977 if (!Lst_IsEmpty(create)) {
978 LstNode ln;
980 for (ln = Lst_First(create); ln != NULL;
981 ln = Lst_Succ(ln)) {
982 char *name = (char *)Lst_Datum(ln);
984 Var_Append(".TARGETS", name, VAR_GLOBAL);
986 } else
987 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
991 * If no user-supplied system path was given (through the -m option)
992 * add the directories from the DEFSYSPATH (more than one may be given
993 * as dir1:...:dirn) to the system include path.
995 if (syspath == NULL || *syspath == '\0')
996 syspath = defsyspath;
997 else
998 syspath = bmake_strdup(syspath);
1000 for (start = syspath; *start != '\0'; start = cp) {
1001 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1002 continue;
1003 if (*cp == ':') {
1004 *cp++ = '\0';
1006 /* look for magic parent directory search string */
1007 if (strncmp(".../", start, 4) != 0) {
1008 (void)Dir_AddDir(defIncPath, start);
1009 } else {
1010 if (Dir_FindHereOrAbove(curdir, start+4,
1011 found_path, sizeof(found_path))) {
1012 (void)Dir_AddDir(defIncPath, found_path);
1016 if (syspath != defsyspath)
1017 free(syspath);
1020 * Read in the built-in rules first, followed by the specified
1021 * makefile, if it was (makefile != NULL), or the default
1022 * makefile and Makefile, in that order, if it wasn't.
1024 if (!noBuiltins) {
1025 LstNode ln;
1027 sysMkPath = Lst_Init(FALSE);
1028 Dir_Expand(_PATH_DEFSYSMK,
1029 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1030 sysMkPath);
1031 if (Lst_IsEmpty(sysMkPath))
1032 Fatal("%s: no system rules (%s).", progname,
1033 _PATH_DEFSYSMK);
1034 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1035 if (ln == NULL)
1036 Fatal("%s: cannot open %s.", progname,
1037 (char *)Lst_Datum(ln));
1040 if (!Lst_IsEmpty(makefiles)) {
1041 LstNode ln;
1043 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1044 if (ln != NULL)
1045 Fatal("%s: cannot open %s.", progname,
1046 (char *)Lst_Datum(ln));
1047 } else if (ReadMakefile("makefile", NULL) != 0)
1048 (void)ReadMakefile("Makefile", NULL);
1050 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1051 if (!noBuiltins || !printVars) {
1052 doing_depend = TRUE;
1053 (void)ReadMakefile(".depend", NULL);
1054 doing_depend = FALSE;
1057 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1058 if (p1)
1059 free(p1);
1061 if (!compatMake)
1062 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1063 if (DEBUG(JOB))
1064 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1065 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1067 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1069 Check_Cwd_av(0, NULL, 0); /* initialize it */
1073 * For compatibility, look at the directories in the VPATH variable
1074 * and add them to the search path, if the variable is defined. The
1075 * variable's value is in the same format as the PATH envariable, i.e.
1076 * <directory>:<directory>:<directory>...
1078 if (Var_Exists("VPATH", VAR_CMD)) {
1079 char *vpath, savec;
1081 * GCC stores string constants in read-only memory, but
1082 * Var_Subst will want to write this thing, so store it
1083 * in an array
1085 static char VPATH[] = "${VPATH}";
1087 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1088 path = vpath;
1089 do {
1090 /* skip to end of directory */
1091 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1092 continue;
1093 /* Save terminator character so know when to stop */
1094 savec = *cp;
1095 *cp = '\0';
1096 /* Add directory to search path */
1097 (void)Dir_AddDir(dirSearchPath, path);
1098 *cp = savec;
1099 path = cp + 1;
1100 } while (savec == ':');
1101 free(vpath);
1105 * Now that all search paths have been read for suffixes et al, it's
1106 * time to add the default search path to their lists...
1108 Suff_DoPaths();
1111 * Propagate attributes through :: dependency lists.
1113 Targ_Propagate();
1115 /* print the initial graph, if the user requested it */
1116 if (DEBUG(GRAPH1))
1117 Targ_PrintGraph(1);
1119 /* print the values of any variables requested by the user */
1120 if (printVars) {
1121 LstNode ln;
1123 for (ln = Lst_First(variables); ln != NULL;
1124 ln = Lst_Succ(ln)) {
1125 char *var = (char *)Lst_Datum(ln);
1126 char *value;
1128 if (strchr(var, '$')) {
1129 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1130 } else {
1131 value = Var_Value(var, VAR_GLOBAL, &p1);
1133 printf("%s\n", value ? value : "");
1134 if (p1)
1135 free(p1);
1137 } else {
1139 * Have now read the entire graph and need to make a list of
1140 * targets to create. If none was given on the command line,
1141 * we consult the parsing module to find the main target(s)
1142 * to create.
1144 if (Lst_IsEmpty(create))
1145 targs = Parse_MainName();
1146 else
1147 targs = Targ_FindList(create, TARG_CREATE);
1149 if (!compatMake) {
1151 * Initialize job module before traversing the graph
1152 * now that any .BEGIN and .END targets have been read.
1153 * This is done only if the -q flag wasn't given
1154 * (to prevent the .BEGIN from being executed should
1155 * it exist).
1157 if (!queryFlag) {
1158 Job_Init();
1159 jobsRunning = TRUE;
1162 /* Traverse the graph, checking on all the targets */
1163 outOfDate = Make_Run(targs);
1164 } else {
1166 * Compat_Init will take care of creating all the
1167 * targets as well as initializing the module.
1169 Compat_Run(targs);
1173 #ifdef CLEANUP
1174 Lst_Destroy(targs, NULL);
1175 Lst_Destroy(variables, NULL);
1176 Lst_Destroy(makefiles, NULL);
1177 Lst_Destroy(create, (FreeProc *)free);
1178 #endif
1180 /* print the graph now it's been processed if the user requested it */
1181 if (DEBUG(GRAPH2))
1182 Targ_PrintGraph(2);
1184 Trace_Log(MAKEEND, 0);
1186 Suff_End();
1187 Targ_End();
1188 Arch_End();
1189 Var_End();
1190 Parse_End();
1191 Dir_End();
1192 Job_End();
1193 Trace_End();
1195 return outOfDate ? 1 : 0;
1199 * ReadMakefile --
1200 * Open and parse the given makefile.
1202 * Results:
1203 * 0 if ok. -1 if couldn't open file.
1205 * Side Effects:
1206 * lots
1208 static int
1209 ReadMakefile(const void *p, const void *q __unused)
1211 const char *fname = p; /* makefile to read */
1212 int fd;
1213 size_t len = MAXPATHLEN;
1214 char *name, *path = bmake_malloc(len);
1215 int setMAKEFILE;
1217 if (!strcmp(fname, "-")) {
1218 Parse_File("(stdin)", dup(fileno(stdin)));
1219 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1220 } else {
1221 setMAKEFILE = strcmp(fname, ".depend");
1223 /* if we've chdir'd, rebuild the path name */
1224 if (strcmp(curdir, objdir) && *fname != '/') {
1225 size_t plen = strlen(curdir) + strlen(fname) + 2;
1226 if (len < plen)
1227 path = bmake_realloc(path, len = 2 * plen);
1229 (void)snprintf(path, len, "%s/%s", curdir, fname);
1230 fd = open(path, O_RDONLY);
1231 if (fd != -1) {
1232 fname = path;
1233 goto found;
1236 /* If curdir failed, try objdir (ala .depend) */
1237 plen = strlen(objdir) + strlen(fname) + 2;
1238 if (len < plen)
1239 path = bmake_realloc(path, len = 2 * plen);
1240 (void)snprintf(path, len, "%s/%s", objdir, fname);
1241 fd = open(path, O_RDONLY);
1242 if (fd != -1) {
1243 fname = path;
1244 goto found;
1246 } else {
1247 fd = open(fname, O_RDONLY);
1248 if (fd != -1)
1249 goto found;
1251 /* look in -I and system include directories. */
1252 name = Dir_FindFile(fname, parseIncPath);
1253 if (!name)
1254 name = Dir_FindFile(fname,
1255 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1256 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1257 if (name)
1258 free(name);
1259 free(path);
1260 return(-1);
1262 fname = name;
1264 * set the MAKEFILE variable desired by System V fans -- the
1265 * placement of the setting here means it gets set to the last
1266 * makefile specified, as it is set by SysV make.
1268 found:
1269 if (setMAKEFILE)
1270 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1271 Parse_File(fname, fd);
1273 free(path);
1274 return(0);
1279 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1280 * in situations that would not arrise with ./obj (links or not).
1281 * This tends to break things like:
1283 * build:
1284 * ${MAKE} includes
1286 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1287 * opposed to an argument) in a command line and if so returns
1288 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1289 * the Makefile hold true.
1291 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1293 * The chdir() only happens in the child process, and does nothing if
1294 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1295 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1296 * do nothing - to ensure historic semantics can be retained.
1298 static int Check_Cwd_Off = 0;
1300 static char *
1301 Check_Cwd_av(int ac, char **av, int copy)
1303 static char *make[4];
1304 static char *cur_dir = NULL;
1305 char **mp;
1306 char *cp;
1307 int is_cmd, next_cmd;
1308 int i;
1309 int n;
1311 if (Check_Cwd_Off) {
1312 if (DEBUG(CWD))
1313 fprintf(debug_file, "check_cwd: check is off.\n");
1314 return NULL;
1317 if (make[0] == NULL) {
1318 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1319 Check_Cwd_Off = 1;
1320 if (DEBUG(CWD))
1321 fprintf(debug_file, "check_cwd: turning check off.\n");
1322 return NULL;
1325 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1326 if ((make[0] = strrchr(make[1], '/')) == NULL) {
1327 make[0] = make[1];
1328 make[1] = NULL;
1329 } else
1330 ++make[0];
1331 make[2] = NULL;
1332 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1334 if (ac == 0 || av == NULL) {
1335 if (DEBUG(CWD))
1336 fprintf(debug_file, "check_cwd: empty command.\n");
1337 return NULL; /* initialization only */
1340 if (getenv("MAKEOBJDIR") == NULL &&
1341 getenv("MAKEOBJDIRPREFIX") == NULL) {
1342 if (DEBUG(CWD))
1343 fprintf(debug_file, "check_cwd: no obj dirs.\n");
1344 return NULL;
1348 next_cmd = 1;
1349 for (i = 0; i < ac; ++i) {
1350 is_cmd = next_cmd;
1352 n = strlen(av[i]);
1353 cp = &(av[i])[n - 1];
1354 if (strspn(av[i], "|&;") == (size_t)n) {
1355 next_cmd = 1;
1356 continue;
1357 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1358 next_cmd = 1;
1359 if (copy) {
1360 do {
1361 *cp-- = '\0';
1362 } while (*cp == ';' || *cp == '&' || *cp == '|' ||
1363 *cp == ')' || *cp == '}') ;
1364 } else {
1366 * XXX this should not happen.
1368 fprintf(stderr, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1369 progname, av[i]);
1371 } else
1372 next_cmd = 0;
1374 cp = av[i];
1375 if (*cp == ';' || *cp == '&' || *cp == '|')
1376 is_cmd = 1;
1378 if (DEBUG(CWD))
1379 fprintf(debug_file, "av[%d] == %s '%s'",
1380 i, (is_cmd) ? "cmd" : "arg", av[i]);
1381 if (is_cmd != 0) {
1382 if (*cp == '(' || *cp == '{' ||
1383 *cp == ';' || *cp == '&' || *cp == '|') {
1384 do {
1385 ++cp;
1386 } while (*cp == '(' || *cp == '{' ||
1387 *cp == ';' || *cp == '&' || *cp == '|');
1388 if (*cp == '\0') {
1389 next_cmd = 1;
1390 continue;
1393 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1394 if (DEBUG(CWD))
1395 fprintf(debug_file, " == cd, done.\n");
1396 return NULL;
1398 for (mp = make; *mp != NULL; ++mp) {
1399 n = strlen(*mp);
1400 if (strcmp(cp, *mp) == 0) {
1401 if (DEBUG(CWD))
1402 fprintf(debug_file, " %s == '%s', chdir(%s)\n",
1403 cp, *mp, cur_dir);
1404 return cur_dir;
1408 if (DEBUG(CWD))
1409 fprintf(debug_file, "\n");
1411 return NULL;
1414 char *
1415 Check_Cwd_Cmd(const char *cmd)
1417 char *cp, *bp;
1418 char **av;
1419 int ac;
1421 if (Check_Cwd_Off)
1422 return NULL;
1424 if (cmd) {
1425 av = brk_string(cmd, &ac, TRUE, &bp);
1426 if (DEBUG(CWD))
1427 fprintf(debug_file, "splitting: '%s' -> %d words\n",
1428 cmd, ac);
1429 } else {
1430 ac = 0;
1431 av = NULL;
1432 bp = NULL;
1434 cp = Check_Cwd_av(ac, av, 1);
1435 if (bp)
1436 free(bp);
1437 if (av)
1438 free(av);
1439 return cp;
1442 void
1443 Check_Cwd(const char **argv)
1445 char *cp;
1446 int ac;
1448 if (Check_Cwd_Off)
1449 return;
1451 for (ac = 0; argv[ac] != NULL; ++ac)
1452 /* NOTHING */;
1453 if (ac == 3 && *argv[1] == '-') {
1454 cp = Check_Cwd_Cmd(argv[2]);
1455 } else {
1456 cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1458 if (cp) {
1459 chdir(cp);
1464 * Cmd_Exec --
1465 * Execute the command in cmd, and return the output of that command
1466 * in a string.
1468 * Results:
1469 * A string containing the output of the command, or the empty string
1470 * If errnum is not NULL, it contains the reason for the command failure
1472 * Side Effects:
1473 * The string must be freed by the caller.
1475 char *
1476 Cmd_Exec(const char *cmd, const char **errnum)
1478 const char *args[4]; /* Args for invoking the shell */
1479 int fds[2]; /* Pipe streams */
1480 int cpid; /* Child PID */
1481 int pid; /* PID from wait() */
1482 char *res; /* result */
1483 int status; /* command exit status */
1484 Buffer buf; /* buffer to store the result */
1485 char *cp;
1486 int cc;
1489 *errnum = NULL;
1491 if (!shellName)
1492 Shell_Init();
1494 * Set up arguments for shell
1496 args[0] = shellName;
1497 args[1] = "-c";
1498 args[2] = cmd;
1499 args[3] = NULL;
1502 * Open a pipe for fetching its output
1504 if (pipe(fds) == -1) {
1505 *errnum = "Couldn't create pipe for \"%s\"";
1506 goto bad;
1510 * Fork
1512 #if defined(__minix)
1513 switch (cpid = fork()) {
1514 #else
1515 switch (cpid = vfork()) {
1516 #endif
1517 case 0:
1519 * Close input side of pipe
1521 (void)close(fds[0]);
1524 * Duplicate the output stream to the shell's output, then
1525 * shut the extra thing down. Note we don't fetch the error
1526 * stream...why not? Why?
1528 (void)dup2(fds[1], 1);
1529 (void)close(fds[1]);
1531 Var_ExportVars();
1533 (void)execv(shellPath, UNCONST(args));
1534 _exit(1);
1535 /*NOTREACHED*/
1537 case -1:
1538 *errnum = "Couldn't exec \"%s\"";
1539 goto bad;
1541 default:
1543 * No need for the writing half
1545 (void)close(fds[1]);
1547 Buf_Init(&buf, 0);
1549 do {
1550 char result[BUFSIZ];
1551 cc = read(fds[0], result, sizeof(result));
1552 if (cc > 0)
1553 Buf_AddBytes(&buf, cc, result);
1555 while (cc > 0 || (cc == -1 && errno == EINTR));
1558 * Close the input side of the pipe.
1560 (void)close(fds[0]);
1563 * Wait for the process to exit.
1565 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0))
1566 continue;
1568 cc = Buf_Size(&buf);
1569 res = Buf_Destroy(&buf, FALSE);
1571 if (cc == 0)
1572 *errnum = "Couldn't read shell's output for \"%s\"";
1574 if (WIFSIGNALED(status))
1575 *errnum = "\"%s\" exited on a signal";
1576 else if (WEXITSTATUS(status) != 0)
1577 *errnum = "\"%s\" returned non-zero status";
1580 * Null-terminate the result, convert newlines to spaces and
1581 * install it in the variable.
1583 res[cc] = '\0';
1584 cp = &res[cc];
1586 if (cc > 0 && *--cp == '\n') {
1588 * A final newline is just stripped
1590 *cp-- = '\0';
1592 while (cp >= res) {
1593 if (*cp == '\n') {
1594 *cp = ' ';
1596 cp--;
1598 break;
1600 return res;
1601 bad:
1602 res = bmake_malloc(1);
1603 *res = '\0';
1604 return res;
1608 * Error --
1609 * Print an error message given its format.
1611 * Results:
1612 * None.
1614 * Side Effects:
1615 * The message is printed.
1617 /* VARARGS */
1618 void
1619 Error(const char *fmt, ...)
1621 va_list ap;
1622 FILE *err_file;
1624 err_file = debug_file;
1625 if (err_file == stdout)
1626 err_file = stderr;
1627 for (;;) {
1628 va_start(ap, fmt);
1629 fprintf(err_file, "%s: ", progname);
1630 (void)vfprintf(err_file, fmt, ap);
1631 va_end(ap);
1632 (void)fprintf(err_file, "\n");
1633 (void)fflush(err_file);
1634 if (err_file == stderr)
1635 break;
1636 err_file = stderr;
1641 * Fatal --
1642 * Produce a Fatal error message. If jobs are running, waits for them
1643 * to finish.
1645 * Results:
1646 * None
1648 * Side Effects:
1649 * The program exits
1651 /* VARARGS */
1652 void
1653 Fatal(const char *fmt, ...)
1655 va_list ap;
1657 va_start(ap, fmt);
1658 if (jobsRunning)
1659 Job_Wait();
1661 (void)vfprintf(stderr, fmt, ap);
1662 va_end(ap);
1663 (void)fprintf(stderr, "\n");
1664 (void)fflush(stderr);
1666 PrintOnError(NULL);
1668 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1669 Targ_PrintGraph(2);
1670 Trace_Log(MAKEERROR, 0);
1671 exit(2); /* Not 1 so -q can distinguish error */
1675 * Punt --
1676 * Major exception once jobs are being created. Kills all jobs, prints
1677 * a message and exits.
1679 * Results:
1680 * None
1682 * Side Effects:
1683 * All children are killed indiscriminately and the program Lib_Exits
1685 /* VARARGS */
1686 void
1687 Punt(const char *fmt, ...)
1689 va_list ap;
1691 va_start(ap, fmt);
1692 (void)fprintf(stderr, "%s: ", progname);
1693 (void)vfprintf(stderr, fmt, ap);
1694 va_end(ap);
1695 (void)fprintf(stderr, "\n");
1696 (void)fflush(stderr);
1698 PrintOnError(NULL);
1700 DieHorribly();
1704 * DieHorribly --
1705 * Exit without giving a message.
1707 * Results:
1708 * None
1710 * Side Effects:
1711 * A big one...
1713 void
1714 DieHorribly(void)
1716 if (jobsRunning)
1717 Job_AbortAll();
1718 if (DEBUG(GRAPH2))
1719 Targ_PrintGraph(2);
1720 Trace_Log(MAKEERROR, 0);
1721 exit(2); /* Not 1, so -q can distinguish error */
1725 * Finish --
1726 * Called when aborting due to errors in child shell to signal
1727 * abnormal exit.
1729 * Results:
1730 * None
1732 * Side Effects:
1733 * The program exits
1735 void
1736 Finish(int errors)
1737 /* number of errors encountered in Make_Make */
1739 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1743 * enunlink --
1744 * Remove a file carefully, avoiding directories.
1747 eunlink(const char *file)
1749 struct stat st;
1751 if (lstat(file, &st) == -1)
1752 return -1;
1754 if (S_ISDIR(st.st_mode)) {
1755 errno = EISDIR;
1756 return -1;
1758 return unlink(file);
1762 * execError --
1763 * Print why exec failed, avoiding stdio.
1765 void
1766 execError(const char *af, const char *av)
1768 #ifdef USE_IOVEC
1769 int i = 0;
1770 struct iovec iov[8];
1771 #define IOADD(s) \
1772 (void)(iov[i].iov_base = UNCONST(s), \
1773 iov[i].iov_len = strlen(iov[i].iov_base), \
1774 i++)
1775 #else
1776 #define IOADD(void)write(2, s, strlen(s))
1777 #endif
1779 IOADD(progname);
1780 IOADD(": ");
1781 IOADD(af);
1782 IOADD("(");
1783 IOADD(av);
1784 IOADD(") failed (");
1785 IOADD(strerror(errno));
1786 IOADD(")\n");
1788 #ifdef USE_IOVEC
1789 (void)writev(2, iov, 8);
1790 #endif
1794 * usage --
1795 * exit with usage message
1797 static void
1798 usage(void)
1800 (void)fprintf(stderr,
1801 "usage: %s [-BeikNnqrstWX] \n\
1802 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1803 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1804 [-V variable] [variable=value] [target ...]\n", progname);
1805 exit(2);
1810 PrintAddr(void *a, void *b)
1812 printf("%lx ", (unsigned long) a);
1813 return b ? 0 : 0;
1818 void
1819 PrintOnError(const char *s)
1821 char tmp[64];
1822 char *cp;
1824 if (s)
1825 printf("%s", s);
1827 printf("\n%s: stopped in %s\n", progname, curdir);
1828 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1829 sizeof(tmp) - 1);
1830 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1831 if (cp) {
1832 if (*cp)
1833 printf("%s", cp);
1834 free(cp);
1838 void
1839 Main_ExportMAKEFLAGS(Boolean first)
1841 static int once = 1;
1842 char tmp[64];
1843 char *s;
1845 if (once != first)
1846 return;
1847 once = 0;
1849 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1850 sizeof(tmp));
1851 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1852 if (s && *s) {
1853 #ifdef POSIX
1854 setenv("MAKEFLAGS", s, 1);
1855 #else
1856 setenv("MAKE", s, 1);
1857 #endif