main.c revision 1.224 1 /* $NetBSD: main.c,v 1.224 2013/09/04 15:38:26 sjg Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
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.
21 *
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.
33 */
34
35 /*
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
38 *
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
41 *
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.
57 *
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.
69 */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.224 2013/09/04 15:38:26 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 */
79
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.224 2013/09/04 15:38:26 sjg Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
88
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
93 *
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.
99 *
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.
104 *
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
107 *
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
110 *
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
114 */
115
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/stat.h>
121 #include <sys/utsname.h>
122 #include <sys/wait.h>
123
124 #include <errno.h>
125 #include <fcntl.h>
126 #include <signal.h>
127 #include <stdarg.h>
128 #include <stdio.h>
129 #include <stdlib.h>
130 #include <time.h>
131 #include <ctype.h>
132
133 #include "make.h"
134 #include "hash.h"
135 #include "dir.h"
136 #include "job.h"
137 #include "pathnames.h"
138 #include "trace.h"
139
140 #ifdef USE_IOVEC
141 #include <sys/uio.h>
142 #endif
143
144 #ifndef DEFMAXLOCAL
145 #define DEFMAXLOCAL DEFMAXJOBS
146 #endif /* DEFMAXLOCAL */
147
148 Lst create; /* Targets to be made */
149 time_t now; /* Time at start of make */
150 GNode *DEFAULT; /* .DEFAULT node */
151 Boolean allPrecious; /* .PRECIOUS given on line by itself */
152
153 static Boolean noBuiltins; /* -r flag */
154 static Lst makefiles; /* ordered list of makefiles to read */
155 static Boolean printVars; /* print value of one or more vars */
156 static Lst variables; /* list of variables to print */
157 int maxJobs; /* -j argument */
158 static int maxJobTokens; /* -j argument */
159 Boolean compatMake; /* -B argument */
160 int debug; /* -d argument */
161 Boolean debugVflag; /* -dV */
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 enterFlag; /* -w flag */
168 Boolean ignoreErrors; /* -i flag */
169 Boolean beSilent; /* -s flag */
170 Boolean oldVars; /* variable substitution style */
171 Boolean checkEnvFirst; /* -e flag */
172 Boolean parseWarnFatal; /* -W flag */
173 Boolean jobServer; /* -J flag */
174 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
175 Boolean varNoExportEnv; /* -X flag */
176 Boolean doing_depend; /* Set while reading .depend */
177 static Boolean jobsRunning; /* TRUE if the jobs might be running */
178 static const char * tracefile;
179 static void MainParseArgs(int, char **);
180 static int ReadMakefile(const void *, const void *);
181 static void usage(void) MAKE_ATTR_DEAD;
182
183 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
184 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
185 char curdir[MAXPATHLEN + 1]; /* Startup directory */
186 char *progname; /* the program name */
187 char *makeDependfile;
188 pid_t myPid;
189 int makelevel;
190
191 Boolean forceJobs = FALSE;
192
193 extern Lst parseIncPath;
194
195 /*
196 * For compatibility with the POSIX version of MAKEFLAGS that includes
197 * all the options with out -, convert flags to -f -l -a -g -s.
198 */
199 static char *
200 explode(const char *flags)
201 {
202 size_t len;
203 char *nf, *st;
204 const char *f;
205
206 if (flags == NULL)
207 return NULL;
208
209 for (f = flags; *f; f++)
210 if (!isalpha((unsigned char)*f))
211 break;
212
213 if (*f)
214 return bmake_strdup(flags);
215
216 len = strlen(flags);
217 st = nf = bmake_malloc(len * 3 + 1);
218 while (*flags) {
219 *nf++ = '-';
220 *nf++ = *flags++;
221 *nf++ = ' ';
222 }
223 *nf = '\0';
224 return st;
225 }
226
227 static void
228 parse_debug_options(const char *argvalue)
229 {
230 const char *modules;
231 const char *mode;
232 char *fname;
233 int len;
234
235 for (modules = argvalue; *modules; ++modules) {
236 switch (*modules) {
237 case 'A':
238 debug = ~0;
239 break;
240 case 'a':
241 debug |= DEBUG_ARCH;
242 break;
243 case 'C':
244 debug |= DEBUG_CWD;
245 break;
246 case 'c':
247 debug |= DEBUG_COND;
248 break;
249 case 'd':
250 debug |= DEBUG_DIR;
251 break;
252 case 'e':
253 debug |= DEBUG_ERROR;
254 break;
255 case 'f':
256 debug |= DEBUG_FOR;
257 break;
258 case 'g':
259 if (modules[1] == '1') {
260 debug |= DEBUG_GRAPH1;
261 ++modules;
262 }
263 else if (modules[1] == '2') {
264 debug |= DEBUG_GRAPH2;
265 ++modules;
266 }
267 else if (modules[1] == '3') {
268 debug |= DEBUG_GRAPH3;
269 ++modules;
270 }
271 break;
272 case 'j':
273 debug |= DEBUG_JOB;
274 break;
275 case 'l':
276 debug |= DEBUG_LOUD;
277 break;
278 case 'M':
279 debug |= DEBUG_META;
280 break;
281 case 'm':
282 debug |= DEBUG_MAKE;
283 break;
284 case 'n':
285 debug |= DEBUG_SCRIPT;
286 break;
287 case 'p':
288 debug |= DEBUG_PARSE;
289 break;
290 case 's':
291 debug |= DEBUG_SUFF;
292 break;
293 case 't':
294 debug |= DEBUG_TARG;
295 break;
296 case 'V':
297 debugVflag = TRUE;
298 break;
299 case 'v':
300 debug |= DEBUG_VAR;
301 break;
302 case 'x':
303 debug |= DEBUG_SHELL;
304 break;
305 case 'F':
306 if (debug_file != stdout && debug_file != stderr)
307 fclose(debug_file);
308 if (*++modules == '+') {
309 modules++;
310 mode = "a";
311 } else
312 mode = "w";
313 if (strcmp(modules, "stdout") == 0) {
314 debug_file = stdout;
315 goto debug_setbuf;
316 }
317 if (strcmp(modules, "stderr") == 0) {
318 debug_file = stderr;
319 goto debug_setbuf;
320 }
321 len = strlen(modules);
322 fname = malloc(len + 20);
323 memcpy(fname, modules, len + 1);
324 /* Let the filename be modified by the pid */
325 if (strcmp(fname + len - 3, ".%d") == 0)
326 snprintf(fname + len - 2, 20, "%d", getpid());
327 debug_file = fopen(fname, mode);
328 if (!debug_file) {
329 fprintf(stderr, "Cannot open debug file %s\n",
330 fname);
331 usage();
332 }
333 free(fname);
334 goto debug_setbuf;
335 default:
336 (void)fprintf(stderr,
337 "%s: illegal argument to d option -- %c\n",
338 progname, *modules);
339 usage();
340 }
341 }
342 debug_setbuf:
343 /*
344 * Make the debug_file unbuffered, and make
345 * stdout line buffered (unless debugfile == stdout).
346 */
347 setvbuf(debug_file, NULL, _IONBF, 0);
348 if (debug_file != stdout) {
349 setvbuf(stdout, NULL, _IOLBF, 0);
350 }
351 }
352
353 /*-
354 * MainParseArgs --
355 * Parse a given argument vector. Called from main() and from
356 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
357 *
358 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
359 *
360 * Results:
361 * None
362 *
363 * Side Effects:
364 * Various global and local flags will be set depending on the flags
365 * given
366 */
367 static void
368 MainParseArgs(int argc, char **argv)
369 {
370 char *p;
371 int c = '?';
372 int arginc;
373 char *argvalue;
374 const char *getopt_def;
375 char *optscan;
376 Boolean inOption, dashDash = FALSE;
377 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
378
379 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstw"
380 /* Can't actually use getopt(3) because rescanning is not portable */
381
382 getopt_def = OPTFLAGS;
383 rearg:
384 inOption = FALSE;
385 optscan = NULL;
386 while(argc > 1) {
387 char *getopt_spec;
388 if(!inOption)
389 optscan = argv[1];
390 c = *optscan++;
391 arginc = 0;
392 if(inOption) {
393 if(c == '\0') {
394 ++argv;
395 --argc;
396 inOption = FALSE;
397 continue;
398 }
399 } else {
400 if (c != '-' || dashDash)
401 break;
402 inOption = TRUE;
403 c = *optscan++;
404 }
405 /* '-' found at some earlier point */
406 getopt_spec = strchr(getopt_def, c);
407 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
408 /* -<something> found, and <something> should have an arg */
409 inOption = FALSE;
410 arginc = 1;
411 argvalue = optscan;
412 if(*argvalue == '\0') {
413 if (argc < 3)
414 goto noarg;
415 argvalue = argv[2];
416 arginc = 2;
417 }
418 } else {
419 argvalue = NULL;
420 }
421 switch(c) {
422 case '\0':
423 arginc = 1;
424 inOption = FALSE;
425 break;
426 case 'B':
427 compatMake = TRUE;
428 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
429 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
430 break;
431 case 'C':
432 if (chdir(argvalue) == -1) {
433 (void)fprintf(stderr,
434 "%s: chdir %s: %s\n",
435 progname, argvalue,
436 strerror(errno));
437 exit(1);
438 }
439 if (getcwd(curdir, MAXPATHLEN) == NULL) {
440 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
441 exit(2);
442 }
443 ignorePWD = TRUE;
444 break;
445 case 'D':
446 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
447 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
448 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
449 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
450 break;
451 case 'I':
452 if (argvalue == NULL) goto noarg;
453 Parse_AddIncludeDir(argvalue);
454 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
455 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
456 break;
457 case 'J':
458 if (argvalue == NULL) goto noarg;
459 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
460 (void)fprintf(stderr,
461 "%s: internal error -- J option malformed (%s)\n",
462 progname, argvalue);
463 usage();
464 }
465 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
466 (fcntl(jp_1, F_GETFD, 0) < 0)) {
467 #if 0
468 (void)fprintf(stderr,
469 "%s: ###### warning -- J descriptors were closed!\n",
470 progname);
471 exit(2);
472 #endif
473 jp_0 = -1;
474 jp_1 = -1;
475 compatMake = TRUE;
476 } else {
477 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
478 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
479 jobServer = TRUE;
480 }
481 break;
482 case 'N':
483 noExecute = TRUE;
484 noRecursiveExecute = TRUE;
485 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
486 break;
487 case 'S':
488 keepgoing = FALSE;
489 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
490 break;
491 case 'T':
492 if (argvalue == NULL) goto noarg;
493 tracefile = bmake_strdup(argvalue);
494 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
495 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
496 break;
497 case 'V':
498 if (argvalue == NULL) goto noarg;
499 printVars = TRUE;
500 (void)Lst_AtEnd(variables, argvalue);
501 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
502 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
503 break;
504 case 'W':
505 parseWarnFatal = TRUE;
506 break;
507 case 'X':
508 varNoExportEnv = TRUE;
509 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
510 break;
511 case 'd':
512 if (argvalue == NULL) goto noarg;
513 /* If '-d-opts' don't pass to children */
514 if (argvalue[0] == '-')
515 argvalue++;
516 else {
517 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
518 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
519 }
520 parse_debug_options(argvalue);
521 break;
522 case 'e':
523 checkEnvFirst = TRUE;
524 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
525 break;
526 case 'f':
527 if (argvalue == NULL) goto noarg;
528 (void)Lst_AtEnd(makefiles, argvalue);
529 break;
530 case 'i':
531 ignoreErrors = TRUE;
532 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
533 break;
534 case 'j':
535 if (argvalue == NULL) goto noarg;
536 forceJobs = TRUE;
537 maxJobs = strtol(argvalue, &p, 0);
538 if (*p != '\0' || maxJobs < 1) {
539 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
540 progname);
541 exit(1);
542 }
543 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
544 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
545 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
546 maxJobTokens = maxJobs;
547 break;
548 case 'k':
549 keepgoing = TRUE;
550 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
551 break;
552 case 'm':
553 if (argvalue == NULL) goto noarg;
554 /* look for magic parent directory search string */
555 if (strncmp(".../", argvalue, 4) == 0) {
556 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
557 found_path, sizeof(found_path)))
558 break; /* nothing doing */
559 (void)Dir_AddDir(sysIncPath, found_path);
560 } else {
561 (void)Dir_AddDir(sysIncPath, argvalue);
562 }
563 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
564 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
565 break;
566 case 'n':
567 noExecute = TRUE;
568 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
569 break;
570 case 'q':
571 queryFlag = TRUE;
572 /* Kind of nonsensical, wot? */
573 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
574 break;
575 case 'r':
576 noBuiltins = TRUE;
577 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
578 break;
579 case 's':
580 beSilent = TRUE;
581 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
582 break;
583 case 't':
584 touchFlag = TRUE;
585 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
586 break;
587 case 'w':
588 enterFlag = TRUE;
589 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
590 break;
591 case '-':
592 dashDash = TRUE;
593 break;
594 default:
595 case '?':
596 usage();
597 }
598 argv += arginc;
599 argc -= arginc;
600 }
601
602 oldVars = TRUE;
603
604 /*
605 * See if the rest of the arguments are variable assignments and
606 * perform them if so. Else take them to be targets and stuff them
607 * on the end of the "create" list.
608 */
609 for (; argc > 1; ++argv, --argc)
610 if (Parse_IsVar(argv[1])) {
611 Parse_DoVar(argv[1], VAR_CMD);
612 } else {
613 if (!*argv[1])
614 Punt("illegal (null) argument.");
615 if (*argv[1] == '-' && !dashDash)
616 goto rearg;
617 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
618 }
619
620 return;
621 noarg:
622 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
623 progname, c);
624 usage();
625 }
626
627 /*-
628 * Main_ParseArgLine --
629 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
630 * is encountered and by main() when reading the .MAKEFLAGS envariable.
631 * Takes a line of arguments and breaks it into its
632 * component words and passes those words and the number of them to the
633 * MainParseArgs function.
634 * The line should have all its leading whitespace removed.
635 *
636 * Input:
637 * line Line to fracture
638 *
639 * Results:
640 * None
641 *
642 * Side Effects:
643 * Only those that come from the various arguments.
644 */
645 void
646 Main_ParseArgLine(const char *line)
647 {
648 char **argv; /* Manufactured argument vector */
649 int argc; /* Number of arguments in argv */
650 char *args; /* Space used by the args */
651 char *buf, *p1;
652 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
653 size_t len;
654
655 if (line == NULL)
656 return;
657 for (; *line == ' '; ++line)
658 continue;
659 if (!*line)
660 return;
661
662 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
663 (void)snprintf(buf, len, "%s %s", argv0, line);
664 if (p1)
665 free(p1);
666
667 argv = brk_string(buf, &argc, TRUE, &args);
668 if (argv == NULL) {
669 Error("Unterminated quoted string [%s]", buf);
670 free(buf);
671 return;
672 }
673 free(buf);
674 MainParseArgs(argc, argv);
675
676 free(args);
677 free(argv);
678 }
679
680 Boolean
681 Main_SetObjdir(const char *path)
682 {
683 struct stat sb;
684 char *p = NULL;
685 char buf[MAXPATHLEN + 1];
686 Boolean rc = FALSE;
687
688 /* expand variable substitutions */
689 if (strchr(path, '$') != 0) {
690 snprintf(buf, MAXPATHLEN, "%s", path);
691 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
692 }
693
694 if (path[0] != '/') {
695 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
696 path = buf;
697 }
698
699 /* look for the directory and try to chdir there */
700 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
701 if (chdir(path)) {
702 (void)fprintf(stderr, "make warning: %s: %s.\n",
703 path, strerror(errno));
704 } else {
705 strncpy(objdir, path, MAXPATHLEN);
706 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
707 setenv("PWD", objdir, 1);
708 Dir_InitDot();
709 rc = TRUE;
710 }
711 }
712
713 if (p)
714 free(p);
715 return rc;
716 }
717
718 /*-
719 * ReadAllMakefiles --
720 * wrapper around ReadMakefile() to read all.
721 *
722 * Results:
723 * TRUE if ok, FALSE on error
724 */
725 static int
726 ReadAllMakefiles(const void *p, const void *q)
727 {
728 return (ReadMakefile(p, q) == 0);
729 }
730
731 int
732 str2Lst_Append(Lst lp, char *str, const char *sep)
733 {
734 char *cp;
735 int n;
736
737 if (!sep)
738 sep = " \t";
739
740 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
741 (void)Lst_AtEnd(lp, cp);
742 n++;
743 }
744 return (n);
745 }
746
747 #ifdef SIGINFO
748 /*ARGSUSED*/
749 static void
750 siginfo(int signo MAKE_ATTR_UNUSED)
751 {
752 char dir[MAXPATHLEN];
753 char str[2 * MAXPATHLEN];
754 int len;
755 if (getcwd(dir, sizeof(dir)) == NULL)
756 return;
757 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
758 if (len > 0)
759 (void)write(STDERR_FILENO, str, (size_t)len);
760 }
761 #endif
762
763 /*
764 * Allow makefiles some control over the mode we run in.
765 */
766 void
767 MakeMode(const char *mode)
768 {
769 char *mp = NULL;
770
771 if (!mode)
772 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}", VAR_GLOBAL, 0);
773
774 if (mode && *mode) {
775 if (strstr(mode, "compat")) {
776 compatMake = TRUE;
777 forceJobs = FALSE;
778 }
779 #if USE_META
780 if (strstr(mode, "meta"))
781 meta_mode_init(mode);
782 #endif
783 }
784 if (mp)
785 free(mp);
786 }
787
788 /*-
789 * main --
790 * The main function, for obvious reasons. Initializes variables
791 * and a few modules, then parses the arguments give it in the
792 * environment and on the command line. Reads the system makefile
793 * followed by either Makefile, makefile or the file given by the
794 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
795 * flags it has received by then uses either the Make or the Compat
796 * module to create the initial list of targets.
797 *
798 * Results:
799 * If -q was given, exits -1 if anything was out-of-date. Else it exits
800 * 0.
801 *
802 * Side Effects:
803 * The program exits when done. Targets are created. etc. etc. etc.
804 */
805 int
806 main(int argc, char **argv)
807 {
808 Lst targs; /* target nodes to create -- passed to Make_Init */
809 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
810 struct stat sb, sa;
811 char *p1, *path;
812 char mdpath[MAXPATHLEN];
813 const char *machine = getenv("MACHINE");
814 const char *machine_arch = getenv("MACHINE_ARCH");
815 char *syspath = getenv("MAKESYSPATH");
816 Lst sysMkPath; /* Path of sys.mk */
817 char *cp = NULL, *start;
818 /* avoid faults on read-only strings */
819 static char defsyspath[] = _PATH_DEFSYSPATH;
820 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
821 struct timeval rightnow; /* to initialize random seed */
822 struct utsname utsname;
823
824 /* default to writing debug to stderr */
825 debug_file = stderr;
826
827 #ifdef SIGINFO
828 (void)bmake_signal(SIGINFO, siginfo);
829 #endif
830 /*
831 * Set the seed to produce a different random sequence
832 * on each program execution.
833 */
834 gettimeofday(&rightnow, NULL);
835 srandom(rightnow.tv_sec + rightnow.tv_usec);
836
837 if ((progname = strrchr(argv[0], '/')) != NULL)
838 progname++;
839 else
840 progname = argv[0];
841 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
842 /*
843 * get rid of resource limit on file descriptors
844 */
845 {
846 struct rlimit rl;
847 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
848 rl.rlim_cur != rl.rlim_max) {
849 rl.rlim_cur = rl.rlim_max;
850 (void)setrlimit(RLIMIT_NOFILE, &rl);
851 }
852 }
853 #endif
854
855 if (uname(&utsname) == -1) {
856 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
857 strerror(errno));
858 exit(2);
859 }
860
861 /*
862 * Get the name of this type of MACHINE from utsname
863 * so we can share an executable for similar machines.
864 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
865 *
866 * Note that both MACHINE and MACHINE_ARCH are decided at
867 * run-time.
868 */
869 if (!machine) {
870 #ifdef MAKE_NATIVE
871 machine = utsname.machine;
872 #else
873 #ifdef MAKE_MACHINE
874 machine = MAKE_MACHINE;
875 #else
876 machine = "unknown";
877 #endif
878 #endif
879 }
880
881 if (!machine_arch) {
882 #ifndef MACHINE_ARCH
883 #ifdef MAKE_MACHINE_ARCH
884 machine_arch = MAKE_MACHINE_ARCH;
885 #else
886 machine_arch = "unknown";
887 #endif
888 #else
889 machine_arch = MACHINE_ARCH;
890 #endif
891 }
892
893 myPid = getpid(); /* remember this for vFork() */
894
895 /*
896 * Just in case MAKEOBJDIR wants us to do something tricky.
897 */
898 Var_Init(); /* Initialize the lists of variables for
899 * parsing arguments */
900 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
901 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
902 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
903 #ifdef MAKE_VERSION
904 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
905 #endif
906 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
907 /*
908 * This is the traditional preference for makefiles.
909 */
910 #ifndef MAKEFILE_PREFERENCE_LIST
911 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
912 #endif
913 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
914 VAR_GLOBAL, 0);
915 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
916
917 create = Lst_Init(FALSE);
918 makefiles = Lst_Init(FALSE);
919 printVars = FALSE;
920 debugVflag = FALSE;
921 variables = Lst_Init(FALSE);
922 beSilent = FALSE; /* Print commands as executed */
923 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
924 noExecute = FALSE; /* Execute all commands */
925 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
926 keepgoing = FALSE; /* Stop on error */
927 allPrecious = FALSE; /* Remove targets when interrupted */
928 queryFlag = FALSE; /* This is not just a check-run */
929 noBuiltins = FALSE; /* Read the built-in rules */
930 touchFlag = FALSE; /* Actually update targets */
931 debug = 0; /* No debug verbosity, please. */
932 jobsRunning = FALSE;
933
934 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
935 maxJobTokens = maxJobs;
936 compatMake = FALSE; /* No compat mode */
937 ignorePWD = FALSE;
938
939 /*
940 * Initialize the parsing, directory and variable modules to prepare
941 * for the reading of inclusion paths and variable settings on the
942 * command line
943 */
944
945 /*
946 * Initialize various variables.
947 * MAKE also gets this name, for compatibility
948 * .MAKEFLAGS gets set to the empty string just in case.
949 * MFLAGS also gets initialized empty, for compatibility.
950 */
951 Parse_Init();
952 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
953 /*
954 * Leave alone if it is an absolute path, or if it does
955 * not contain a '/' in which case we need to find it in
956 * the path, like execvp(3) and the shells do.
957 */
958 p1 = argv[0];
959 } else {
960 /*
961 * A relative path, canonicalize it.
962 */
963 p1 = realpath(argv[0], mdpath);
964 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
965 p1 = argv[0]; /* realpath failed */
966 }
967 }
968 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
969 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
970 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
971 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
972 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
973 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
974 /* some makefiles need to know this */
975 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
976
977 /*
978 * Set some other useful macros
979 */
980 {
981 char tmp[64], *ep;
982
983 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
984 if (makelevel < 0)
985 makelevel = 0;
986 snprintf(tmp, sizeof(tmp), "%d", makelevel);
987 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
988 snprintf(tmp, sizeof(tmp), "%u", myPid);
989 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
990 snprintf(tmp, sizeof(tmp), "%u", getppid());
991 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
992 }
993 if (makelevel > 0) {
994 char pn[1024];
995 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
996 progname = bmake_strdup(pn);
997 }
998
999 #ifdef USE_META
1000 meta_init();
1001 #endif
1002 /*
1003 * First snag any flags out of the MAKE environment variable.
1004 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1005 * in a different format).
1006 */
1007 #ifdef POSIX
1008 p1 = explode(getenv("MAKEFLAGS"));
1009 Main_ParseArgLine(p1);
1010 free(p1);
1011 #else
1012 Main_ParseArgLine(getenv("MAKE"));
1013 #endif
1014
1015 /*
1016 * Find where we are (now).
1017 * We take care of PWD for the automounter below...
1018 */
1019 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1020 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1021 progname, strerror(errno));
1022 exit(2);
1023 }
1024
1025 MainParseArgs(argc, argv);
1026
1027 if (enterFlag)
1028 printf("%s: Entering directory `%s'\n", progname, curdir);
1029
1030 /*
1031 * Verify that cwd is sane.
1032 */
1033 if (stat(curdir, &sa) == -1) {
1034 (void)fprintf(stderr, "%s: %s: %s.\n",
1035 progname, curdir, strerror(errno));
1036 exit(2);
1037 }
1038
1039 /*
1040 * All this code is so that we know where we are when we start up
1041 * on a different machine with pmake.
1042 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1043 * since the value of curdir can vary depending on how we got
1044 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1045 * or via subdir.mk in which case its likely a shell which does
1046 * not provide it.
1047 * So, to stop it breaking this case only, we ignore PWD if
1048 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1049 */
1050 #ifndef NO_PWD_OVERRIDE
1051 if (!ignorePWD) {
1052 char *pwd;
1053
1054 if ((pwd = getenv("PWD")) != NULL &&
1055 getenv("MAKEOBJDIRPREFIX") == NULL) {
1056 const char *makeobjdir = getenv("MAKEOBJDIR");
1057
1058 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1059 if (stat(pwd, &sb) == 0 &&
1060 sa.st_ino == sb.st_ino &&
1061 sa.st_dev == sb.st_dev)
1062 (void)strncpy(curdir, pwd, MAXPATHLEN);
1063 }
1064 }
1065 }
1066 #endif
1067 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1068
1069 /*
1070 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1071 * MAKEOBJDIR is set in the environment, try only that value
1072 * and fall back to .CURDIR if it does not exist.
1073 *
1074 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1075 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1076 * of these paths exist, just use .CURDIR.
1077 */
1078 Dir_Init(curdir);
1079 (void)Main_SetObjdir(curdir);
1080
1081 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1082 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1083 (void)Main_SetObjdir(mdpath);
1084 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1085 (void)Main_SetObjdir(path);
1086 } else {
1087 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1088 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1089 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1090 _PATH_OBJDIRPREFIX, curdir);
1091 (void)Main_SetObjdir(mdpath);
1092 }
1093 }
1094
1095 /*
1096 * Be compatible if user did not specify -j and did not explicitly
1097 * turned compatibility on
1098 */
1099 if (!compatMake && !forceJobs) {
1100 compatMake = TRUE;
1101 }
1102
1103 /*
1104 * Initialize archive, target and suffix modules in preparation for
1105 * parsing the makefile(s)
1106 */
1107 Arch_Init();
1108 Targ_Init();
1109 Suff_Init();
1110 Trace_Init(tracefile);
1111
1112 DEFAULT = NULL;
1113 (void)time(&now);
1114
1115 Trace_Log(MAKESTART, NULL);
1116
1117 /*
1118 * Set up the .TARGETS variable to contain the list of targets to be
1119 * created. If none specified, make the variable empty -- the parser
1120 * will fill the thing in with the default or .MAIN target.
1121 */
1122 if (!Lst_IsEmpty(create)) {
1123 LstNode ln;
1124
1125 for (ln = Lst_First(create); ln != NULL;
1126 ln = Lst_Succ(ln)) {
1127 char *name = (char *)Lst_Datum(ln);
1128
1129 Var_Append(".TARGETS", name, VAR_GLOBAL);
1130 }
1131 } else
1132 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1133
1134
1135 /*
1136 * If no user-supplied system path was given (through the -m option)
1137 * add the directories from the DEFSYSPATH (more than one may be given
1138 * as dir1:...:dirn) to the system include path.
1139 */
1140 if (syspath == NULL || *syspath == '\0')
1141 syspath = defsyspath;
1142 else
1143 syspath = bmake_strdup(syspath);
1144
1145 for (start = syspath; *start != '\0'; start = cp) {
1146 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1147 continue;
1148 if (*cp == ':') {
1149 *cp++ = '\0';
1150 }
1151 /* look for magic parent directory search string */
1152 if (strncmp(".../", start, 4) != 0) {
1153 (void)Dir_AddDir(defIncPath, start);
1154 } else {
1155 if (Dir_FindHereOrAbove(curdir, start+4,
1156 found_path, sizeof(found_path))) {
1157 (void)Dir_AddDir(defIncPath, found_path);
1158 }
1159 }
1160 }
1161 if (syspath != defsyspath)
1162 free(syspath);
1163
1164 /*
1165 * Read in the built-in rules first, followed by the specified
1166 * makefile, if it was (makefile != NULL), or the default
1167 * makefile and Makefile, in that order, if it wasn't.
1168 */
1169 if (!noBuiltins) {
1170 LstNode ln;
1171
1172 sysMkPath = Lst_Init(FALSE);
1173 Dir_Expand(_PATH_DEFSYSMK,
1174 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1175 sysMkPath);
1176 if (Lst_IsEmpty(sysMkPath))
1177 Fatal("%s: no system rules (%s).", progname,
1178 _PATH_DEFSYSMK);
1179 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1180 if (ln == NULL)
1181 Fatal("%s: cannot open %s.", progname,
1182 (char *)Lst_Datum(ln));
1183 }
1184
1185 if (!Lst_IsEmpty(makefiles)) {
1186 LstNode ln;
1187
1188 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1189 if (ln != NULL)
1190 Fatal("%s: cannot open %s.", progname,
1191 (char *)Lst_Datum(ln));
1192 } else {
1193 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1194 VAR_CMD, 0);
1195 if (p1) {
1196 (void)str2Lst_Append(makefiles, p1, NULL);
1197 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1198 free(p1);
1199 }
1200 }
1201
1202 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1203 if (!noBuiltins || !printVars) {
1204 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1205 VAR_CMD, 0);
1206 doing_depend = TRUE;
1207 (void)ReadMakefile(makeDependfile, NULL);
1208 doing_depend = FALSE;
1209 }
1210
1211 MakeMode(NULL);
1212
1213 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1214 if (p1)
1215 free(p1);
1216
1217 if (!compatMake)
1218 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1219 if (DEBUG(JOB))
1220 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1221 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1222
1223 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1224
1225
1226 /*
1227 * For compatibility, look at the directories in the VPATH variable
1228 * and add them to the search path, if the variable is defined. The
1229 * variable's value is in the same format as the PATH envariable, i.e.
1230 * <directory>:<directory>:<directory>...
1231 */
1232 if (Var_Exists("VPATH", VAR_CMD)) {
1233 char *vpath, savec;
1234 /*
1235 * GCC stores string constants in read-only memory, but
1236 * Var_Subst will want to write this thing, so store it
1237 * in an array
1238 */
1239 static char VPATH[] = "${VPATH}";
1240
1241 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1242 path = vpath;
1243 do {
1244 /* skip to end of directory */
1245 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1246 continue;
1247 /* Save terminator character so know when to stop */
1248 savec = *cp;
1249 *cp = '\0';
1250 /* Add directory to search path */
1251 (void)Dir_AddDir(dirSearchPath, path);
1252 *cp = savec;
1253 path = cp + 1;
1254 } while (savec == ':');
1255 free(vpath);
1256 }
1257
1258 /*
1259 * Now that all search paths have been read for suffixes et al, it's
1260 * time to add the default search path to their lists...
1261 */
1262 Suff_DoPaths();
1263
1264 /*
1265 * Propagate attributes through :: dependency lists.
1266 */
1267 Targ_Propagate();
1268
1269 /* print the initial graph, if the user requested it */
1270 if (DEBUG(GRAPH1))
1271 Targ_PrintGraph(1);
1272
1273 /* print the values of any variables requested by the user */
1274 if (printVars) {
1275 LstNode ln;
1276 Boolean expandVars;
1277
1278 if (debugVflag)
1279 expandVars = FALSE;
1280 else
1281 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1282 for (ln = Lst_First(variables); ln != NULL;
1283 ln = Lst_Succ(ln)) {
1284 char *var = (char *)Lst_Datum(ln);
1285 char *value;
1286
1287 if (strchr(var, '$')) {
1288 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1289 } else if (expandVars) {
1290 char tmp[128];
1291
1292 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1293 Fatal("%s: variable name too big: %s",
1294 progname, var);
1295 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1296 } else {
1297 value = Var_Value(var, VAR_GLOBAL, &p1);
1298 }
1299 printf("%s\n", value ? value : "");
1300 if (p1)
1301 free(p1);
1302 }
1303 } else {
1304 /*
1305 * Have now read the entire graph and need to make a list of
1306 * targets to create. If none was given on the command line,
1307 * we consult the parsing module to find the main target(s)
1308 * to create.
1309 */
1310 if (Lst_IsEmpty(create))
1311 targs = Parse_MainName();
1312 else
1313 targs = Targ_FindList(create, TARG_CREATE);
1314
1315 if (!compatMake) {
1316 /*
1317 * Initialize job module before traversing the graph
1318 * now that any .BEGIN and .END targets have been read.
1319 * This is done only if the -q flag wasn't given
1320 * (to prevent the .BEGIN from being executed should
1321 * it exist).
1322 */
1323 if (!queryFlag) {
1324 Job_Init();
1325 jobsRunning = TRUE;
1326 }
1327
1328 /* Traverse the graph, checking on all the targets */
1329 outOfDate = Make_Run(targs);
1330 } else {
1331 /*
1332 * Compat_Init will take care of creating all the
1333 * targets as well as initializing the module.
1334 */
1335 Compat_Run(targs);
1336 }
1337 }
1338
1339 #ifdef CLEANUP
1340 Lst_Destroy(targs, NULL);
1341 Lst_Destroy(variables, NULL);
1342 Lst_Destroy(makefiles, NULL);
1343 Lst_Destroy(create, (FreeProc *)free);
1344 #endif
1345
1346 /* print the graph now it's been processed if the user requested it */
1347 if (DEBUG(GRAPH2))
1348 Targ_PrintGraph(2);
1349
1350 Trace_Log(MAKEEND, 0);
1351
1352 if (enterFlag)
1353 printf("%s: Leaving directory `%s'\n", progname, curdir);
1354
1355 Suff_End();
1356 Targ_End();
1357 Arch_End();
1358 Var_End();
1359 Parse_End();
1360 Dir_End();
1361 Job_End();
1362 Trace_End();
1363
1364 return outOfDate ? 1 : 0;
1365 }
1366
1367 /*-
1368 * ReadMakefile --
1369 * Open and parse the given makefile.
1370 *
1371 * Results:
1372 * 0 if ok. -1 if couldn't open file.
1373 *
1374 * Side Effects:
1375 * lots
1376 */
1377 static int
1378 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1379 {
1380 const char *fname = p; /* makefile to read */
1381 int fd;
1382 size_t len = MAXPATHLEN;
1383 char *name, *path = bmake_malloc(len);
1384
1385 if (!strcmp(fname, "-")) {
1386 Parse_File(NULL /*stdin*/, -1);
1387 Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1388 } else {
1389 /* if we've chdir'd, rebuild the path name */
1390 if (strcmp(curdir, objdir) && *fname != '/') {
1391 size_t plen = strlen(curdir) + strlen(fname) + 2;
1392 if (len < plen)
1393 path = bmake_realloc(path, len = 2 * plen);
1394
1395 (void)snprintf(path, len, "%s/%s", curdir, fname);
1396 fd = open(path, O_RDONLY);
1397 if (fd != -1) {
1398 fname = path;
1399 goto found;
1400 }
1401
1402 /* If curdir failed, try objdir (ala .depend) */
1403 plen = strlen(objdir) + strlen(fname) + 2;
1404 if (len < plen)
1405 path = bmake_realloc(path, len = 2 * plen);
1406 (void)snprintf(path, len, "%s/%s", objdir, fname);
1407 fd = open(path, O_RDONLY);
1408 if (fd != -1) {
1409 fname = path;
1410 goto found;
1411 }
1412 } else {
1413 fd = open(fname, O_RDONLY);
1414 if (fd != -1)
1415 goto found;
1416 }
1417 /* look in -I and system include directories. */
1418 name = Dir_FindFile(fname, parseIncPath);
1419 if (!name)
1420 name = Dir_FindFile(fname,
1421 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1422 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1423 if (name)
1424 free(name);
1425 free(path);
1426 return(-1);
1427 }
1428 fname = name;
1429 /*
1430 * set the MAKEFILE variable desired by System V fans -- the
1431 * placement of the setting here means it gets set to the last
1432 * makefile specified, as it is set by SysV make.
1433 */
1434 found:
1435 if (!doing_depend)
1436 Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1437 Parse_File(fname, fd);
1438 }
1439 free(path);
1440 return(0);
1441 }
1442
1443
1444
1445 /*-
1446 * Cmd_Exec --
1447 * Execute the command in cmd, and return the output of that command
1448 * in a string.
1449 *
1450 * Results:
1451 * A string containing the output of the command, or the empty string
1452 * If errnum is not NULL, it contains the reason for the command failure
1453 *
1454 * Side Effects:
1455 * The string must be freed by the caller.
1456 */
1457 char *
1458 Cmd_Exec(const char *cmd, const char **errnum)
1459 {
1460 const char *args[4]; /* Args for invoking the shell */
1461 int fds[2]; /* Pipe streams */
1462 int cpid; /* Child PID */
1463 int pid; /* PID from wait() */
1464 char *res; /* result */
1465 int status; /* command exit status */
1466 Buffer buf; /* buffer to store the result */
1467 char *cp;
1468 int cc;
1469
1470
1471 *errnum = NULL;
1472
1473 if (!shellName)
1474 Shell_Init();
1475 /*
1476 * Set up arguments for shell
1477 */
1478 args[0] = shellName;
1479 args[1] = "-c";
1480 args[2] = cmd;
1481 args[3] = NULL;
1482
1483 /*
1484 * Open a pipe for fetching its output
1485 */
1486 if (pipe(fds) == -1) {
1487 *errnum = "Couldn't create pipe for \"%s\"";
1488 goto bad;
1489 }
1490
1491 /*
1492 * Fork
1493 */
1494 switch (cpid = vFork()) {
1495 case 0:
1496 /*
1497 * Close input side of pipe
1498 */
1499 (void)close(fds[0]);
1500
1501 /*
1502 * Duplicate the output stream to the shell's output, then
1503 * shut the extra thing down. Note we don't fetch the error
1504 * stream...why not? Why?
1505 */
1506 (void)dup2(fds[1], 1);
1507 (void)close(fds[1]);
1508
1509 Var_ExportVars();
1510
1511 (void)execv(shellPath, UNCONST(args));
1512 _exit(1);
1513 /*NOTREACHED*/
1514
1515 case -1:
1516 *errnum = "Couldn't exec \"%s\"";
1517 goto bad;
1518
1519 default:
1520 /*
1521 * No need for the writing half
1522 */
1523 (void)close(fds[1]);
1524
1525 Buf_Init(&buf, 0);
1526
1527 do {
1528 char result[BUFSIZ];
1529 cc = read(fds[0], result, sizeof(result));
1530 if (cc > 0)
1531 Buf_AddBytes(&buf, cc, result);
1532 }
1533 while (cc > 0 || (cc == -1 && errno == EINTR));
1534
1535 /*
1536 * Close the input side of the pipe.
1537 */
1538 (void)close(fds[0]);
1539
1540 /*
1541 * Wait for the process to exit.
1542 */
1543 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1544 JobReapChild(pid, status, FALSE);
1545 continue;
1546 }
1547 cc = Buf_Size(&buf);
1548 res = Buf_Destroy(&buf, FALSE);
1549
1550 if (cc == 0)
1551 *errnum = "Couldn't read shell's output for \"%s\"";
1552
1553 if (WIFSIGNALED(status))
1554 *errnum = "\"%s\" exited on a signal";
1555 else if (WEXITSTATUS(status) != 0)
1556 *errnum = "\"%s\" returned non-zero status";
1557
1558 /*
1559 * Null-terminate the result, convert newlines to spaces and
1560 * install it in the variable.
1561 */
1562 res[cc] = '\0';
1563 cp = &res[cc];
1564
1565 if (cc > 0 && *--cp == '\n') {
1566 /*
1567 * A final newline is just stripped
1568 */
1569 *cp-- = '\0';
1570 }
1571 while (cp >= res) {
1572 if (*cp == '\n') {
1573 *cp = ' ';
1574 }
1575 cp--;
1576 }
1577 break;
1578 }
1579 return res;
1580 bad:
1581 res = bmake_malloc(1);
1582 *res = '\0';
1583 return res;
1584 }
1585
1586 /*-
1587 * Error --
1588 * Print an error message given its format.
1589 *
1590 * Results:
1591 * None.
1592 *
1593 * Side Effects:
1594 * The message is printed.
1595 */
1596 /* VARARGS */
1597 void
1598 Error(const char *fmt, ...)
1599 {
1600 va_list ap;
1601 FILE *err_file;
1602
1603 err_file = debug_file;
1604 if (err_file == stdout)
1605 err_file = stderr;
1606 (void)fflush(stdout);
1607 for (;;) {
1608 va_start(ap, fmt);
1609 fprintf(err_file, "%s: ", progname);
1610 (void)vfprintf(err_file, fmt, ap);
1611 va_end(ap);
1612 (void)fprintf(err_file, "\n");
1613 (void)fflush(err_file);
1614 if (err_file == stderr)
1615 break;
1616 err_file = stderr;
1617 }
1618 }
1619
1620 /*-
1621 * Fatal --
1622 * Produce a Fatal error message. If jobs are running, waits for them
1623 * to finish.
1624 *
1625 * Results:
1626 * None
1627 *
1628 * Side Effects:
1629 * The program exits
1630 */
1631 /* VARARGS */
1632 void
1633 Fatal(const char *fmt, ...)
1634 {
1635 va_list ap;
1636
1637 va_start(ap, fmt);
1638 if (jobsRunning)
1639 Job_Wait();
1640
1641 (void)fflush(stdout);
1642 (void)vfprintf(stderr, fmt, ap);
1643 va_end(ap);
1644 (void)fprintf(stderr, "\n");
1645 (void)fflush(stderr);
1646
1647 PrintOnError(NULL, NULL);
1648
1649 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1650 Targ_PrintGraph(2);
1651 Trace_Log(MAKEERROR, 0);
1652 exit(2); /* Not 1 so -q can distinguish error */
1653 }
1654
1655 /*
1656 * Punt --
1657 * Major exception once jobs are being created. Kills all jobs, prints
1658 * a message and exits.
1659 *
1660 * Results:
1661 * None
1662 *
1663 * Side Effects:
1664 * All children are killed indiscriminately and the program Lib_Exits
1665 */
1666 /* VARARGS */
1667 void
1668 Punt(const char *fmt, ...)
1669 {
1670 va_list ap;
1671
1672 va_start(ap, fmt);
1673 (void)fflush(stdout);
1674 (void)fprintf(stderr, "%s: ", progname);
1675 (void)vfprintf(stderr, fmt, ap);
1676 va_end(ap);
1677 (void)fprintf(stderr, "\n");
1678 (void)fflush(stderr);
1679
1680 PrintOnError(NULL, NULL);
1681
1682 DieHorribly();
1683 }
1684
1685 /*-
1686 * DieHorribly --
1687 * Exit without giving a message.
1688 *
1689 * Results:
1690 * None
1691 *
1692 * Side Effects:
1693 * A big one...
1694 */
1695 void
1696 DieHorribly(void)
1697 {
1698 if (jobsRunning)
1699 Job_AbortAll();
1700 if (DEBUG(GRAPH2))
1701 Targ_PrintGraph(2);
1702 Trace_Log(MAKEERROR, 0);
1703 exit(2); /* Not 1, so -q can distinguish error */
1704 }
1705
1706 /*
1707 * Finish --
1708 * Called when aborting due to errors in child shell to signal
1709 * abnormal exit.
1710 *
1711 * Results:
1712 * None
1713 *
1714 * Side Effects:
1715 * The program exits
1716 */
1717 void
1718 Finish(int errors)
1719 /* number of errors encountered in Make_Make */
1720 {
1721 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1722 }
1723
1724 /*
1725 * eunlink --
1726 * Remove a file carefully, avoiding directories.
1727 */
1728 int
1729 eunlink(const char *file)
1730 {
1731 struct stat st;
1732
1733 if (lstat(file, &st) == -1)
1734 return -1;
1735
1736 if (S_ISDIR(st.st_mode)) {
1737 errno = EISDIR;
1738 return -1;
1739 }
1740 return unlink(file);
1741 }
1742
1743 /*
1744 * execError --
1745 * Print why exec failed, avoiding stdio.
1746 */
1747 void
1748 execError(const char *af, const char *av)
1749 {
1750 #ifdef USE_IOVEC
1751 int i = 0;
1752 struct iovec iov[8];
1753 #define IOADD(s) \
1754 (void)(iov[i].iov_base = UNCONST(s), \
1755 iov[i].iov_len = strlen(iov[i].iov_base), \
1756 i++)
1757 #else
1758 #define IOADD(void)write(2, s, strlen(s))
1759 #endif
1760
1761 IOADD(progname);
1762 IOADD(": ");
1763 IOADD(af);
1764 IOADD("(");
1765 IOADD(av);
1766 IOADD(") failed (");
1767 IOADD(strerror(errno));
1768 IOADD(")\n");
1769
1770 #ifdef USE_IOVEC
1771 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1772 continue;
1773 #endif
1774 }
1775
1776 /*
1777 * usage --
1778 * exit with usage message
1779 */
1780 static void
1781 usage(void)
1782 {
1783 char *p;
1784 if ((p = strchr(progname, '[')) != NULL)
1785 *p = '\0';
1786
1787 (void)fprintf(stderr,
1788 "usage: %s [-BeikNnqrstWwX] \n\
1789 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1790 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1791 [-V variable] [variable=value] [target ...]\n", progname);
1792 exit(2);
1793 }
1794
1795
1796 int
1797 PrintAddr(void *a, void *b)
1798 {
1799 printf("%lx ", (unsigned long) a);
1800 return b ? 0 : 0;
1801 }
1802
1803
1804
1805 void
1806 PrintOnError(GNode *gn, const char *s)
1807 {
1808 static GNode *en = NULL;
1809 char tmp[64];
1810 char *cp;
1811
1812 if (s)
1813 printf("%s", s);
1814
1815 printf("\n%s: stopped in %s\n", progname, curdir);
1816
1817 if (en)
1818 return; /* we've been here! */
1819 if (gn) {
1820 /*
1821 * We can print this even if there is no .ERROR target.
1822 */
1823 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1824 }
1825 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1826 sizeof(tmp) - 1);
1827 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1828 if (cp) {
1829 if (*cp)
1830 printf("%s", cp);
1831 free(cp);
1832 }
1833 /*
1834 * Finally, see if there is a .ERROR target, and run it if so.
1835 */
1836 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1837 if (en) {
1838 en->type |= OP_SPECIAL;
1839 Compat_Make(en, en);
1840 }
1841 }
1842
1843 void
1844 Main_ExportMAKEFLAGS(Boolean first)
1845 {
1846 static int once = 1;
1847 char tmp[64];
1848 char *s;
1849
1850 if (once != first)
1851 return;
1852 once = 0;
1853
1854 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1855 sizeof(tmp));
1856 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1857 if (s && *s) {
1858 #ifdef POSIX
1859 setenv("MAKEFLAGS", s, 1);
1860 #else
1861 setenv("MAKE", s, 1);
1862 #endif
1863 }
1864 }
1865
1866 char *
1867 getTmpdir(void)
1868 {
1869 static char *tmpdir = NULL;
1870
1871 if (!tmpdir) {
1872 struct stat st;
1873
1874 /*
1875 * Honor $TMPDIR but only if it is valid.
1876 * Ensure it ends with /.
1877 */
1878 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1879 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1880 free(tmpdir);
1881 tmpdir = bmake_strdup(_PATH_TMP);
1882 }
1883 }
1884 return tmpdir;
1885 }
1886
1887 /*
1888 * Create and open a temp file using "pattern".
1889 * If "fnamep" is provided set it to a copy of the filename created.
1890 * Otherwise unlink the file once open.
1891 */
1892 int
1893 mkTempFile(const char *pattern, char **fnamep)
1894 {
1895 static char *tmpdir = NULL;
1896 char tfile[MAXPATHLEN];
1897 int fd;
1898
1899 if (!pattern)
1900 pattern = TMPPAT;
1901 if (!tmpdir)
1902 tmpdir = getTmpdir();
1903 if (pattern[0] == '/') {
1904 snprintf(tfile, sizeof(tfile), "%s", pattern);
1905 } else {
1906 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1907 }
1908 if ((fd = mkstemp(tfile)) < 0)
1909 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1910 if (fnamep) {
1911 *fnamep = bmake_strdup(tfile);
1912 } else {
1913 unlink(tfile); /* we just want the descriptor */
1914 }
1915 return fd;
1916 }
1917
1918
1919 /*
1920 * Return a Boolean based on setting of a knob.
1921 *
1922 * If the knob is not set, the supplied default is the return value.
1923 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1924 * is FALSE, otherwise TRUE.
1925 */
1926 Boolean
1927 getBoolean(const char *name, Boolean bf)
1928 {
1929 char tmp[64];
1930 char *cp;
1931
1932 if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1933 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1934
1935 if (cp) {
1936 switch(*cp) {
1937 case '\0': /* not set - the default wins */
1938 break;
1939 case '0':
1940 case 'f':
1941 case 'n':
1942 bf = FALSE;
1943 break;
1944 case 'o':
1945 switch (cp[1]) {
1946 case 'f':
1947 bf = FALSE;
1948 break;
1949 default:
1950 bf = TRUE;
1951 break;
1952 }
1953 break;
1954 default:
1955 bf = TRUE;
1956 break;
1957 }
1958 free(cp);
1959 }
1960 }
1961 return (bf);
1962 }
1963