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