main.c revision 1.222 1 /* $NetBSD: main.c,v 1.222 2013/07/18 15:31:49 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.222 2013/07/18 15:31: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 */
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.222 2013/07/18 15:31:49 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 Job_SetPrefix();
999
1000 #ifdef USE_META
1001 meta_init();
1002 #endif
1003 /*
1004 * First snag any flags out of the MAKE environment variable.
1005 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1006 * in a different format).
1007 */
1008 #ifdef POSIX
1009 p1 = explode(getenv("MAKEFLAGS"));
1010 Main_ParseArgLine(p1);
1011 free(p1);
1012 #else
1013 Main_ParseArgLine(getenv("MAKE"));
1014 #endif
1015
1016 /*
1017 * Find where we are (now).
1018 * We take care of PWD for the automounter below...
1019 */
1020 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1021 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1022 progname, strerror(errno));
1023 exit(2);
1024 }
1025
1026 MainParseArgs(argc, argv);
1027
1028 if (enterFlag)
1029 printf("%s: Entering directory `%s'\n", progname, curdir);
1030
1031 /*
1032 * Verify that cwd is sane.
1033 */
1034 if (stat(curdir, &sa) == -1) {
1035 (void)fprintf(stderr, "%s: %s: %s.\n",
1036 progname, curdir, strerror(errno));
1037 exit(2);
1038 }
1039
1040 /*
1041 * All this code is so that we know where we are when we start up
1042 * on a different machine with pmake.
1043 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1044 * since the value of curdir can vary depending on how we got
1045 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1046 * or via subdir.mk in which case its likely a shell which does
1047 * not provide it.
1048 * So, to stop it breaking this case only, we ignore PWD if
1049 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1050 */
1051 #ifndef NO_PWD_OVERRIDE
1052 if (!ignorePWD) {
1053 char *pwd;
1054
1055 if ((pwd = getenv("PWD")) != NULL &&
1056 getenv("MAKEOBJDIRPREFIX") == NULL) {
1057 const char *makeobjdir = getenv("MAKEOBJDIR");
1058
1059 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1060 if (stat(pwd, &sb) == 0 &&
1061 sa.st_ino == sb.st_ino &&
1062 sa.st_dev == sb.st_dev)
1063 (void)strncpy(curdir, pwd, MAXPATHLEN);
1064 }
1065 }
1066 }
1067 #endif
1068 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1069
1070 /*
1071 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1072 * MAKEOBJDIR is set in the environment, try only that value
1073 * and fall back to .CURDIR if it does not exist.
1074 *
1075 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1076 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1077 * of these paths exist, just use .CURDIR.
1078 */
1079 Dir_Init(curdir);
1080 (void)Main_SetObjdir(curdir);
1081
1082 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1083 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1084 (void)Main_SetObjdir(mdpath);
1085 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1086 (void)Main_SetObjdir(path);
1087 } else {
1088 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1089 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1090 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1091 _PATH_OBJDIRPREFIX, curdir);
1092 (void)Main_SetObjdir(mdpath);
1093 }
1094 }
1095
1096 /*
1097 * Be compatible if user did not specify -j and did not explicitly
1098 * turned compatibility on
1099 */
1100 if (!compatMake && !forceJobs) {
1101 compatMake = TRUE;
1102 }
1103
1104 /*
1105 * Initialize archive, target and suffix modules in preparation for
1106 * parsing the makefile(s)
1107 */
1108 Arch_Init();
1109 Targ_Init();
1110 Suff_Init();
1111 Trace_Init(tracefile);
1112
1113 DEFAULT = NULL;
1114 (void)time(&now);
1115
1116 Trace_Log(MAKESTART, NULL);
1117
1118 /*
1119 * Set up the .TARGETS variable to contain the list of targets to be
1120 * created. If none specified, make the variable empty -- the parser
1121 * will fill the thing in with the default or .MAIN target.
1122 */
1123 if (!Lst_IsEmpty(create)) {
1124 LstNode ln;
1125
1126 for (ln = Lst_First(create); ln != NULL;
1127 ln = Lst_Succ(ln)) {
1128 char *name = (char *)Lst_Datum(ln);
1129
1130 Var_Append(".TARGETS", name, VAR_GLOBAL);
1131 }
1132 } else
1133 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1134
1135
1136 /*
1137 * If no user-supplied system path was given (through the -m option)
1138 * add the directories from the DEFSYSPATH (more than one may be given
1139 * as dir1:...:dirn) to the system include path.
1140 */
1141 if (syspath == NULL || *syspath == '\0')
1142 syspath = defsyspath;
1143 else
1144 syspath = bmake_strdup(syspath);
1145
1146 for (start = syspath; *start != '\0'; start = cp) {
1147 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1148 continue;
1149 if (*cp == ':') {
1150 *cp++ = '\0';
1151 }
1152 /* look for magic parent directory search string */
1153 if (strncmp(".../", start, 4) != 0) {
1154 (void)Dir_AddDir(defIncPath, start);
1155 } else {
1156 if (Dir_FindHereOrAbove(curdir, start+4,
1157 found_path, sizeof(found_path))) {
1158 (void)Dir_AddDir(defIncPath, found_path);
1159 }
1160 }
1161 }
1162 if (syspath != defsyspath)
1163 free(syspath);
1164
1165 /*
1166 * Read in the built-in rules first, followed by the specified
1167 * makefile, if it was (makefile != NULL), or the default
1168 * makefile and Makefile, in that order, if it wasn't.
1169 */
1170 if (!noBuiltins) {
1171 LstNode ln;
1172
1173 sysMkPath = Lst_Init(FALSE);
1174 Dir_Expand(_PATH_DEFSYSMK,
1175 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1176 sysMkPath);
1177 if (Lst_IsEmpty(sysMkPath))
1178 Fatal("%s: no system rules (%s).", progname,
1179 _PATH_DEFSYSMK);
1180 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1181 if (ln == NULL)
1182 Fatal("%s: cannot open %s.", progname,
1183 (char *)Lst_Datum(ln));
1184 }
1185
1186 if (!Lst_IsEmpty(makefiles)) {
1187 LstNode ln;
1188
1189 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1190 if (ln != NULL)
1191 Fatal("%s: cannot open %s.", progname,
1192 (char *)Lst_Datum(ln));
1193 } else {
1194 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1195 VAR_CMD, 0);
1196 if (p1) {
1197 (void)str2Lst_Append(makefiles, p1, NULL);
1198 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1199 free(p1);
1200 }
1201 }
1202
1203 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1204 if (!noBuiltins || !printVars) {
1205 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1206 VAR_CMD, 0);
1207 doing_depend = TRUE;
1208 (void)ReadMakefile(makeDependfile, NULL);
1209 doing_depend = FALSE;
1210 }
1211
1212 MakeMode(NULL);
1213
1214 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1215 if (p1)
1216 free(p1);
1217
1218 if (!compatMake)
1219 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1220 if (DEBUG(JOB))
1221 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1222 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1223
1224 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1225
1226
1227 /*
1228 * For compatibility, look at the directories in the VPATH variable
1229 * and add them to the search path, if the variable is defined. The
1230 * variable's value is in the same format as the PATH envariable, i.e.
1231 * <directory>:<directory>:<directory>...
1232 */
1233 if (Var_Exists("VPATH", VAR_CMD)) {
1234 char *vpath, savec;
1235 /*
1236 * GCC stores string constants in read-only memory, but
1237 * Var_Subst will want to write this thing, so store it
1238 * in an array
1239 */
1240 static char VPATH[] = "${VPATH}";
1241
1242 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1243 path = vpath;
1244 do {
1245 /* skip to end of directory */
1246 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1247 continue;
1248 /* Save terminator character so know when to stop */
1249 savec = *cp;
1250 *cp = '\0';
1251 /* Add directory to search path */
1252 (void)Dir_AddDir(dirSearchPath, path);
1253 *cp = savec;
1254 path = cp + 1;
1255 } while (savec == ':');
1256 free(vpath);
1257 }
1258
1259 /*
1260 * Now that all search paths have been read for suffixes et al, it's
1261 * time to add the default search path to their lists...
1262 */
1263 Suff_DoPaths();
1264
1265 /*
1266 * Propagate attributes through :: dependency lists.
1267 */
1268 Targ_Propagate();
1269
1270 /* print the initial graph, if the user requested it */
1271 if (DEBUG(GRAPH1))
1272 Targ_PrintGraph(1);
1273
1274 /* print the values of any variables requested by the user */
1275 if (printVars) {
1276 LstNode ln;
1277 Boolean expandVars;
1278
1279 if (debugVflag)
1280 expandVars = FALSE;
1281 else
1282 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1283 for (ln = Lst_First(variables); ln != NULL;
1284 ln = Lst_Succ(ln)) {
1285 char *var = (char *)Lst_Datum(ln);
1286 char *value;
1287
1288 if (strchr(var, '$')) {
1289 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1290 } else if (expandVars) {
1291 char tmp[128];
1292
1293 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1294 Fatal("%s: variable name too big: %s",
1295 progname, var);
1296 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1297 } else {
1298 value = Var_Value(var, VAR_GLOBAL, &p1);
1299 }
1300 printf("%s\n", value ? value : "");
1301 if (p1)
1302 free(p1);
1303 }
1304 } else {
1305 /*
1306 * Have now read the entire graph and need to make a list of
1307 * targets to create. If none was given on the command line,
1308 * we consult the parsing module to find the main target(s)
1309 * to create.
1310 */
1311 if (Lst_IsEmpty(create))
1312 targs = Parse_MainName();
1313 else
1314 targs = Targ_FindList(create, TARG_CREATE);
1315
1316 if (!compatMake) {
1317 /*
1318 * Initialize job module before traversing the graph
1319 * now that any .BEGIN and .END targets have been read.
1320 * This is done only if the -q flag wasn't given
1321 * (to prevent the .BEGIN from being executed should
1322 * it exist).
1323 */
1324 if (!queryFlag) {
1325 Job_Init();
1326 jobsRunning = TRUE;
1327 }
1328
1329 /* Traverse the graph, checking on all the targets */
1330 outOfDate = Make_Run(targs);
1331 } else {
1332 /*
1333 * Compat_Init will take care of creating all the
1334 * targets as well as initializing the module.
1335 */
1336 Compat_Run(targs);
1337 }
1338 }
1339
1340 #ifdef CLEANUP
1341 Lst_Destroy(targs, NULL);
1342 Lst_Destroy(variables, NULL);
1343 Lst_Destroy(makefiles, NULL);
1344 Lst_Destroy(create, (FreeProc *)free);
1345 #endif
1346
1347 /* print the graph now it's been processed if the user requested it */
1348 if (DEBUG(GRAPH2))
1349 Targ_PrintGraph(2);
1350
1351 Trace_Log(MAKEEND, 0);
1352
1353 if (enterFlag)
1354 printf("%s: Leaving directory `%s'\n", progname, curdir);
1355
1356 Suff_End();
1357 Targ_End();
1358 Arch_End();
1359 Var_End();
1360 Parse_End();
1361 Dir_End();
1362 Job_End();
1363 Trace_End();
1364
1365 return outOfDate ? 1 : 0;
1366 }
1367
1368 /*-
1369 * ReadMakefile --
1370 * Open and parse the given makefile.
1371 *
1372 * Results:
1373 * 0 if ok. -1 if couldn't open file.
1374 *
1375 * Side Effects:
1376 * lots
1377 */
1378 static int
1379 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1380 {
1381 const char *fname = p; /* makefile to read */
1382 int fd;
1383 size_t len = MAXPATHLEN;
1384 char *name, *path = bmake_malloc(len);
1385
1386 if (!strcmp(fname, "-")) {
1387 Parse_File(NULL /*stdin*/, -1);
1388 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1389 } else {
1390 /* if we've chdir'd, rebuild the path name */
1391 if (strcmp(curdir, objdir) && *fname != '/') {
1392 size_t plen = strlen(curdir) + strlen(fname) + 2;
1393 if (len < plen)
1394 path = bmake_realloc(path, len = 2 * plen);
1395
1396 (void)snprintf(path, len, "%s/%s", curdir, fname);
1397 fd = open(path, O_RDONLY);
1398 if (fd != -1) {
1399 fname = path;
1400 goto found;
1401 }
1402
1403 /* If curdir failed, try objdir (ala .depend) */
1404 plen = strlen(objdir) + strlen(fname) + 2;
1405 if (len < plen)
1406 path = bmake_realloc(path, len = 2 * plen);
1407 (void)snprintf(path, len, "%s/%s", objdir, fname);
1408 fd = open(path, O_RDONLY);
1409 if (fd != -1) {
1410 fname = path;
1411 goto found;
1412 }
1413 } else {
1414 fd = open(fname, O_RDONLY);
1415 if (fd != -1)
1416 goto found;
1417 }
1418 /* look in -I and system include directories. */
1419 name = Dir_FindFile(fname, parseIncPath);
1420 if (!name)
1421 name = Dir_FindFile(fname,
1422 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1423 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1424 if (name)
1425 free(name);
1426 free(path);
1427 return(-1);
1428 }
1429 fname = name;
1430 /*
1431 * set the MAKEFILE variable desired by System V fans -- the
1432 * placement of the setting here means it gets set to the last
1433 * makefile specified, as it is set by SysV make.
1434 */
1435 found:
1436 if (!doing_depend)
1437 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1438 Parse_File(fname, fd);
1439 }
1440 free(path);
1441 return(0);
1442 }
1443
1444
1445
1446 /*-
1447 * Cmd_Exec --
1448 * Execute the command in cmd, and return the output of that command
1449 * in a string.
1450 *
1451 * Results:
1452 * A string containing the output of the command, or the empty string
1453 * If errnum is not NULL, it contains the reason for the command failure
1454 *
1455 * Side Effects:
1456 * The string must be freed by the caller.
1457 */
1458 char *
1459 Cmd_Exec(const char *cmd, const char **errnum)
1460 {
1461 const char *args[4]; /* Args for invoking the shell */
1462 int fds[2]; /* Pipe streams */
1463 int cpid; /* Child PID */
1464 int pid; /* PID from wait() */
1465 char *res; /* result */
1466 int status; /* command exit status */
1467 Buffer buf; /* buffer to store the result */
1468 char *cp;
1469 int cc;
1470
1471
1472 *errnum = NULL;
1473
1474 if (!shellName)
1475 Shell_Init();
1476 /*
1477 * Set up arguments for shell
1478 */
1479 args[0] = shellName;
1480 args[1] = "-c";
1481 args[2] = cmd;
1482 args[3] = NULL;
1483
1484 /*
1485 * Open a pipe for fetching its output
1486 */
1487 if (pipe(fds) == -1) {
1488 *errnum = "Couldn't create pipe for \"%s\"";
1489 goto bad;
1490 }
1491
1492 /*
1493 * Fork
1494 */
1495 switch (cpid = vFork()) {
1496 case 0:
1497 /*
1498 * Close input side of pipe
1499 */
1500 (void)close(fds[0]);
1501
1502 /*
1503 * Duplicate the output stream to the shell's output, then
1504 * shut the extra thing down. Note we don't fetch the error
1505 * stream...why not? Why?
1506 */
1507 (void)dup2(fds[1], 1);
1508 (void)close(fds[1]);
1509
1510 Var_ExportVars();
1511
1512 (void)execv(shellPath, UNCONST(args));
1513 _exit(1);
1514 /*NOTREACHED*/
1515
1516 case -1:
1517 *errnum = "Couldn't exec \"%s\"";
1518 goto bad;
1519
1520 default:
1521 /*
1522 * No need for the writing half
1523 */
1524 (void)close(fds[1]);
1525
1526 Buf_Init(&buf, 0);
1527
1528 do {
1529 char result[BUFSIZ];
1530 cc = read(fds[0], result, sizeof(result));
1531 if (cc > 0)
1532 Buf_AddBytes(&buf, cc, result);
1533 }
1534 while (cc > 0 || (cc == -1 && errno == EINTR));
1535
1536 /*
1537 * Close the input side of the pipe.
1538 */
1539 (void)close(fds[0]);
1540
1541 /*
1542 * Wait for the process to exit.
1543 */
1544 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1545 JobReapChild(pid, status, FALSE);
1546 continue;
1547 }
1548 cc = Buf_Size(&buf);
1549 res = Buf_Destroy(&buf, FALSE);
1550
1551 if (cc == 0)
1552 *errnum = "Couldn't read shell's output for \"%s\"";
1553
1554 if (WIFSIGNALED(status))
1555 *errnum = "\"%s\" exited on a signal";
1556 else if (WEXITSTATUS(status) != 0)
1557 *errnum = "\"%s\" returned non-zero status";
1558
1559 /*
1560 * Null-terminate the result, convert newlines to spaces and
1561 * install it in the variable.
1562 */
1563 res[cc] = '\0';
1564 cp = &res[cc];
1565
1566 if (cc > 0 && *--cp == '\n') {
1567 /*
1568 * A final newline is just stripped
1569 */
1570 *cp-- = '\0';
1571 }
1572 while (cp >= res) {
1573 if (*cp == '\n') {
1574 *cp = ' ';
1575 }
1576 cp--;
1577 }
1578 break;
1579 }
1580 return res;
1581 bad:
1582 res = bmake_malloc(1);
1583 *res = '\0';
1584 return res;
1585 }
1586
1587 /*-
1588 * Error --
1589 * Print an error message given its format.
1590 *
1591 * Results:
1592 * None.
1593 *
1594 * Side Effects:
1595 * The message is printed.
1596 */
1597 /* VARARGS */
1598 void
1599 Error(const char *fmt, ...)
1600 {
1601 va_list ap;
1602 FILE *err_file;
1603
1604 err_file = debug_file;
1605 if (err_file == stdout)
1606 err_file = stderr;
1607 (void)fflush(stdout);
1608 for (;;) {
1609 va_start(ap, fmt);
1610 fprintf(err_file, "%s: ", progname);
1611 (void)vfprintf(err_file, fmt, ap);
1612 va_end(ap);
1613 (void)fprintf(err_file, "\n");
1614 (void)fflush(err_file);
1615 if (err_file == stderr)
1616 break;
1617 err_file = stderr;
1618 }
1619 }
1620
1621 /*-
1622 * Fatal --
1623 * Produce a Fatal error message. If jobs are running, waits for them
1624 * to finish.
1625 *
1626 * Results:
1627 * None
1628 *
1629 * Side Effects:
1630 * The program exits
1631 */
1632 /* VARARGS */
1633 void
1634 Fatal(const char *fmt, ...)
1635 {
1636 va_list ap;
1637
1638 va_start(ap, fmt);
1639 if (jobsRunning)
1640 Job_Wait();
1641
1642 (void)fflush(stdout);
1643 (void)vfprintf(stderr, fmt, ap);
1644 va_end(ap);
1645 (void)fprintf(stderr, "\n");
1646 (void)fflush(stderr);
1647
1648 PrintOnError(NULL, NULL);
1649
1650 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1651 Targ_PrintGraph(2);
1652 Trace_Log(MAKEERROR, 0);
1653 exit(2); /* Not 1 so -q can distinguish error */
1654 }
1655
1656 /*
1657 * Punt --
1658 * Major exception once jobs are being created. Kills all jobs, prints
1659 * a message and exits.
1660 *
1661 * Results:
1662 * None
1663 *
1664 * Side Effects:
1665 * All children are killed indiscriminately and the program Lib_Exits
1666 */
1667 /* VARARGS */
1668 void
1669 Punt(const char *fmt, ...)
1670 {
1671 va_list ap;
1672
1673 va_start(ap, fmt);
1674 (void)fflush(stdout);
1675 (void)fprintf(stderr, "%s: ", progname);
1676 (void)vfprintf(stderr, fmt, ap);
1677 va_end(ap);
1678 (void)fprintf(stderr, "\n");
1679 (void)fflush(stderr);
1680
1681 PrintOnError(NULL, NULL);
1682
1683 DieHorribly();
1684 }
1685
1686 /*-
1687 * DieHorribly --
1688 * Exit without giving a message.
1689 *
1690 * Results:
1691 * None
1692 *
1693 * Side Effects:
1694 * A big one...
1695 */
1696 void
1697 DieHorribly(void)
1698 {
1699 if (jobsRunning)
1700 Job_AbortAll();
1701 if (DEBUG(GRAPH2))
1702 Targ_PrintGraph(2);
1703 Trace_Log(MAKEERROR, 0);
1704 exit(2); /* Not 1, so -q can distinguish error */
1705 }
1706
1707 /*
1708 * Finish --
1709 * Called when aborting due to errors in child shell to signal
1710 * abnormal exit.
1711 *
1712 * Results:
1713 * None
1714 *
1715 * Side Effects:
1716 * The program exits
1717 */
1718 void
1719 Finish(int errors)
1720 /* number of errors encountered in Make_Make */
1721 {
1722 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1723 }
1724
1725 /*
1726 * eunlink --
1727 * Remove a file carefully, avoiding directories.
1728 */
1729 int
1730 eunlink(const char *file)
1731 {
1732 struct stat st;
1733
1734 if (lstat(file, &st) == -1)
1735 return -1;
1736
1737 if (S_ISDIR(st.st_mode)) {
1738 errno = EISDIR;
1739 return -1;
1740 }
1741 return unlink(file);
1742 }
1743
1744 /*
1745 * execError --
1746 * Print why exec failed, avoiding stdio.
1747 */
1748 void
1749 execError(const char *af, const char *av)
1750 {
1751 #ifdef USE_IOVEC
1752 int i = 0;
1753 struct iovec iov[8];
1754 #define IOADD(s) \
1755 (void)(iov[i].iov_base = UNCONST(s), \
1756 iov[i].iov_len = strlen(iov[i].iov_base), \
1757 i++)
1758 #else
1759 #define IOADD(void)write(2, s, strlen(s))
1760 #endif
1761
1762 IOADD(progname);
1763 IOADD(": ");
1764 IOADD(af);
1765 IOADD("(");
1766 IOADD(av);
1767 IOADD(") failed (");
1768 IOADD(strerror(errno));
1769 IOADD(")\n");
1770
1771 #ifdef USE_IOVEC
1772 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1773 continue;
1774 #endif
1775 }
1776
1777 /*
1778 * usage --
1779 * exit with usage message
1780 */
1781 static void
1782 usage(void)
1783 {
1784 char *p;
1785 if ((p = strchr(progname, '[')) != NULL)
1786 *p = '\0';
1787
1788 (void)fprintf(stderr,
1789 "usage: %s [-BeikNnqrstWwX] \n\
1790 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1791 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1792 [-V variable] [variable=value] [target ...]\n", progname);
1793 exit(2);
1794 }
1795
1796
1797 int
1798 PrintAddr(void *a, void *b)
1799 {
1800 printf("%lx ", (unsigned long) a);
1801 return b ? 0 : 0;
1802 }
1803
1804
1805
1806 void
1807 PrintOnError(GNode *gn, const char *s)
1808 {
1809 static GNode *en = NULL;
1810 char tmp[64];
1811 char *cp;
1812
1813 if (s)
1814 printf("%s", s);
1815
1816 printf("\n%s: stopped in %s\n", progname, curdir);
1817
1818 if (en)
1819 return; /* we've been here! */
1820 if (gn) {
1821 /*
1822 * We can print this even if there is no .ERROR target.
1823 */
1824 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1825 }
1826 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1827 sizeof(tmp) - 1);
1828 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1829 if (cp) {
1830 if (*cp)
1831 printf("%s", cp);
1832 free(cp);
1833 }
1834 /*
1835 * Finally, see if there is a .ERROR target, and run it if so.
1836 */
1837 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1838 if (en) {
1839 en->type |= OP_SPECIAL;
1840 Compat_Make(en, en);
1841 }
1842 }
1843
1844 void
1845 Main_ExportMAKEFLAGS(Boolean first)
1846 {
1847 static int once = 1;
1848 char tmp[64];
1849 char *s;
1850
1851 if (once != first)
1852 return;
1853 once = 0;
1854
1855 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1856 sizeof(tmp));
1857 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1858 if (s && *s) {
1859 #ifdef POSIX
1860 setenv("MAKEFLAGS", s, 1);
1861 #else
1862 setenv("MAKE", s, 1);
1863 #endif
1864 }
1865 }
1866
1867 char *
1868 getTmpdir(void)
1869 {
1870 static char *tmpdir = NULL;
1871
1872 if (!tmpdir) {
1873 struct stat st;
1874
1875 /*
1876 * Honor $TMPDIR but only if it is valid.
1877 * Ensure it ends with /.
1878 */
1879 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1880 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1881 free(tmpdir);
1882 tmpdir = bmake_strdup(_PATH_TMP);
1883 }
1884 }
1885 return tmpdir;
1886 }
1887
1888 /*
1889 * Create and open a temp file using "pattern".
1890 * If "fnamep" is provided set it to a copy of the filename created.
1891 * Otherwise unlink the file once open.
1892 */
1893 int
1894 mkTempFile(const char *pattern, char **fnamep)
1895 {
1896 static char *tmpdir = NULL;
1897 char tfile[MAXPATHLEN];
1898 int fd;
1899
1900 if (!pattern)
1901 pattern = TMPPAT;
1902 if (!tmpdir)
1903 tmpdir = getTmpdir();
1904 if (pattern[0] == '/') {
1905 snprintf(tfile, sizeof(tfile), "%s", pattern);
1906 } else {
1907 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1908 }
1909 if ((fd = mkstemp(tfile)) < 0)
1910 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1911 if (fnamep) {
1912 *fnamep = bmake_strdup(tfile);
1913 } else {
1914 unlink(tfile); /* we just want the descriptor */
1915 }
1916 return fd;
1917 }
1918
1919
1920 /*
1921 * Return a Boolean based on setting of a knob.
1922 *
1923 * If the knob is not set, the supplied default is the return value.
1924 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1925 * is FALSE, otherwise TRUE.
1926 */
1927 Boolean
1928 getBoolean(const char *name, Boolean bf)
1929 {
1930 char tmp[64];
1931 char *cp;
1932
1933 if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1934 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1935
1936 if (cp) {
1937 switch(*cp) {
1938 case '\0': /* not set - the default wins */
1939 break;
1940 case '0':
1941 case 'f':
1942 case 'n':
1943 bf = FALSE;
1944 break;
1945 case 'o':
1946 switch (cp[1]) {
1947 case 'f':
1948 bf = FALSE;
1949 break;
1950 default:
1951 bf = TRUE;
1952 break;
1953 }
1954 break;
1955 default:
1956 bf = TRUE;
1957 break;
1958 }
1959 free(cp);
1960 }
1961 }
1962 return (bf);
1963 }
1964