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