main.c revision 1.204 1 /* $NetBSD: main.c,v 1.204 2013/01/25 02:01:10 sjg Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
38 *
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.204 2013/01/25 02:01:10 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
77 The Regents of the University of California. All rights reserved.");
78 #endif /* not lint */
79
80 #ifndef lint
81 #if 0
82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94";
83 #else
84 __RCSID("$NetBSD: main.c,v 1.204 2013/01/25 02:01:10 sjg Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
88
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
93 *
94 * Utility functions defined in this file:
95 * Main_ParseArgLine Takes a line of arguments, breaks them and
96 * treats them as if they were given when first
97 * invoked. Used by the parse module to implement
98 * the .MFLAGS target.
99 *
100 * Error Print a tagged error message. The global
101 * MAKE variable must have been defined. This
102 * takes a format string and two optional
103 * arguments for it.
104 *
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
107 *
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
110 *
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
114 */
115
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/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 /*
821 * Get the name of this type of MACHINE from utsname
822 * so we can share an executable for similar machines.
823 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
824 *
825 * Note that both MACHINE and MACHINE_ARCH are decided at
826 * run-time.
827 */
828 if (!machine) {
829 #ifdef MAKE_NATIVE
830 if (uname(&utsname) == -1) {
831 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
832 strerror(errno));
833 exit(2);
834 }
835 machine = utsname.machine;
836 #else
837 #ifdef MAKE_MACHINE
838 machine = MAKE_MACHINE;
839 #else
840 machine = "unknown";
841 #endif
842 #endif
843 }
844
845 if (!machine_arch) {
846 #ifndef MACHINE_ARCH
847 #ifdef MAKE_MACHINE_ARCH
848 machine_arch = MAKE_MACHINE_ARCH;
849 #else
850 machine_arch = "unknown";
851 #endif
852 #else
853 machine_arch = MACHINE_ARCH;
854 #endif
855 }
856
857 myPid = getpid(); /* remember this for vFork() */
858
859 /*
860 * Just in case MAKEOBJDIR wants us to do something tricky.
861 */
862 Var_Init(); /* Initialize the lists of variables for
863 * parsing arguments */
864 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
865 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
866 #ifdef MAKE_VERSION
867 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
868 #endif
869 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
870 /*
871 * This is the traditional preference for makefiles.
872 */
873 #ifndef MAKEFILE_PREFERENCE_LIST
874 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
875 #endif
876 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
877 VAR_GLOBAL, 0);
878 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
879
880 create = Lst_Init(FALSE);
881 makefiles = Lst_Init(FALSE);
882 printVars = FALSE;
883 debugVflag = FALSE;
884 variables = Lst_Init(FALSE);
885 beSilent = FALSE; /* Print commands as executed */
886 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
887 noExecute = FALSE; /* Execute all commands */
888 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
889 keepgoing = FALSE; /* Stop on error */
890 allPrecious = FALSE; /* Remove targets when interrupted */
891 queryFlag = FALSE; /* This is not just a check-run */
892 noBuiltins = FALSE; /* Read the built-in rules */
893 touchFlag = FALSE; /* Actually update targets */
894 debug = 0; /* No debug verbosity, please. */
895 jobsRunning = FALSE;
896
897 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
898 maxJobTokens = maxJobs;
899 compatMake = FALSE; /* No compat mode */
900 ignorePWD = FALSE;
901
902 /*
903 * Initialize the parsing, directory and variable modules to prepare
904 * for the reading of inclusion paths and variable settings on the
905 * command line
906 */
907
908 /*
909 * Initialize various variables.
910 * MAKE also gets this name, for compatibility
911 * .MAKEFLAGS gets set to the empty string just in case.
912 * MFLAGS also gets initialized empty, for compatibility.
913 */
914 Parse_Init();
915 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
916 /*
917 * Leave alone if it is an absolute path, or if it does
918 * not contain a '/' in which case we need to find it in
919 * the path, like execvp(3) and the shells do.
920 */
921 p1 = argv[0];
922 } else {
923 /*
924 * A relative path, canonicalize it.
925 */
926 p1 = realpath(argv[0], mdpath);
927 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
928 p1 = argv[0]; /* realpath failed */
929 }
930 }
931 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
932 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
933 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
934 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
935 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
936 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
937
938 /*
939 * Set some other useful macros
940 */
941 {
942 char tmp[64];
943 const char *ep;
944
945 if (!(ep = getenv(MAKE_LEVEL))) {
946 ep = "0";
947 }
948 Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
949 snprintf(tmp, sizeof(tmp), "%u", myPid);
950 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
951 snprintf(tmp, sizeof(tmp), "%u", getppid());
952 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
953 }
954 Job_SetPrefix();
955
956 /*
957 * First snag any flags out of the MAKE environment variable.
958 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
959 * in a different format).
960 */
961 #ifdef POSIX
962 Main_ParseArgLine(getenv("MAKEFLAGS"));
963 #else
964 Main_ParseArgLine(getenv("MAKE"));
965 #endif
966
967 /*
968 * Find where we are (now).
969 * We take care of PWD for the automounter below...
970 */
971 if (getcwd(curdir, MAXPATHLEN) == NULL) {
972 (void)fprintf(stderr, "%s: getcwd: %s.\n",
973 progname, strerror(errno));
974 exit(2);
975 }
976
977 MainParseArgs(argc, argv);
978
979 /*
980 * Verify that cwd is sane.
981 */
982 if (stat(curdir, &sa) == -1) {
983 (void)fprintf(stderr, "%s: %s: %s.\n",
984 progname, curdir, strerror(errno));
985 exit(2);
986 }
987
988 /*
989 * All this code is so that we know where we are when we start up
990 * on a different machine with pmake.
991 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
992 * since the value of curdir can vary depending on how we got
993 * here. Ie sitting at a shell prompt (shell that provides $PWD)
994 * or via subdir.mk in which case its likely a shell which does
995 * not provide it.
996 * So, to stop it breaking this case only, we ignore PWD if
997 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
998 */
999 if (!ignorePWD &&
1000 (pwd = getenv("PWD")) != NULL &&
1001 getenv("MAKEOBJDIRPREFIX") == NULL) {
1002 const char *makeobjdir = getenv("MAKEOBJDIR");
1003
1004 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1005 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
1006 sa.st_dev == sb.st_dev)
1007 (void)strncpy(curdir, pwd, MAXPATHLEN);
1008 }
1009 }
1010 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1011
1012 /*
1013 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1014 * MAKEOBJDIR is set in the environment, try only that value
1015 * and fall back to .CURDIR if it does not exist.
1016 *
1017 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1018 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1019 * of these paths exist, just use .CURDIR.
1020 */
1021 Dir_Init(curdir);
1022 (void)Main_SetObjdir(curdir);
1023
1024 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1025 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1026 (void)Main_SetObjdir(mdpath);
1027 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1028 (void)Main_SetObjdir(path);
1029 } else {
1030 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1031 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1032 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1033 _PATH_OBJDIRPREFIX, curdir);
1034 (void)Main_SetObjdir(mdpath);
1035 }
1036 }
1037
1038 /*
1039 * Be compatible if user did not specify -j and did not explicitly
1040 * turned compatibility on
1041 */
1042 if (!compatMake && !forceJobs) {
1043 compatMake = TRUE;
1044 }
1045
1046 /*
1047 * Initialize archive, target and suffix modules in preparation for
1048 * parsing the makefile(s)
1049 */
1050 Arch_Init();
1051 Targ_Init();
1052 Suff_Init();
1053 Trace_Init(tracefile);
1054
1055 DEFAULT = NULL;
1056 (void)time(&now);
1057
1058 Trace_Log(MAKESTART, NULL);
1059
1060 /*
1061 * Set up the .TARGETS variable to contain the list of targets to be
1062 * created. If none specified, make the variable empty -- the parser
1063 * will fill the thing in with the default or .MAIN target.
1064 */
1065 if (!Lst_IsEmpty(create)) {
1066 LstNode ln;
1067
1068 for (ln = Lst_First(create); ln != NULL;
1069 ln = Lst_Succ(ln)) {
1070 char *name = (char *)Lst_Datum(ln);
1071
1072 Var_Append(".TARGETS", name, VAR_GLOBAL);
1073 }
1074 } else
1075 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1076
1077
1078 /*
1079 * If no user-supplied system path was given (through the -m option)
1080 * add the directories from the DEFSYSPATH (more than one may be given
1081 * as dir1:...:dirn) to the system include path.
1082 */
1083 if (syspath == NULL || *syspath == '\0')
1084 syspath = defsyspath;
1085 else
1086 syspath = bmake_strdup(syspath);
1087
1088 for (start = syspath; *start != '\0'; start = cp) {
1089 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1090 continue;
1091 if (*cp == ':') {
1092 *cp++ = '\0';
1093 }
1094 /* look for magic parent directory search string */
1095 if (strncmp(".../", start, 4) != 0) {
1096 (void)Dir_AddDir(defIncPath, start);
1097 } else {
1098 if (Dir_FindHereOrAbove(curdir, start+4,
1099 found_path, sizeof(found_path))) {
1100 (void)Dir_AddDir(defIncPath, found_path);
1101 }
1102 }
1103 }
1104 if (syspath != defsyspath)
1105 free(syspath);
1106
1107 /*
1108 * Read in the built-in rules first, followed by the specified
1109 * makefile, if it was (makefile != NULL), or the default
1110 * makefile and Makefile, in that order, if it wasn't.
1111 */
1112 if (!noBuiltins) {
1113 LstNode ln;
1114
1115 sysMkPath = Lst_Init(FALSE);
1116 Dir_Expand(_PATH_DEFSYSMK,
1117 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1118 sysMkPath);
1119 if (Lst_IsEmpty(sysMkPath))
1120 Fatal("%s: no system rules (%s).", progname,
1121 _PATH_DEFSYSMK);
1122 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1123 if (ln == NULL)
1124 Fatal("%s: cannot open %s.", progname,
1125 (char *)Lst_Datum(ln));
1126 }
1127
1128 if (!Lst_IsEmpty(makefiles)) {
1129 LstNode ln;
1130
1131 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1132 if (ln != NULL)
1133 Fatal("%s: cannot open %s.", progname,
1134 (char *)Lst_Datum(ln));
1135 } else {
1136 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1137 VAR_CMD, 0);
1138 if (p1) {
1139 (void)str2Lst_Append(makefiles, p1, NULL);
1140 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1141 free(p1);
1142 }
1143 }
1144
1145 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1146 if (!noBuiltins || !printVars) {
1147 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1148 VAR_CMD, 0);
1149 doing_depend = TRUE;
1150 (void)ReadMakefile(makeDependfile, NULL);
1151 doing_depend = FALSE;
1152 }
1153
1154 MakeMode(NULL);
1155
1156 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1157 if (p1)
1158 free(p1);
1159
1160 if (!compatMake)
1161 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1162 if (DEBUG(JOB))
1163 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1164 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1165
1166 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1167
1168
1169 /*
1170 * For compatibility, look at the directories in the VPATH variable
1171 * and add them to the search path, if the variable is defined. The
1172 * variable's value is in the same format as the PATH envariable, i.e.
1173 * <directory>:<directory>:<directory>...
1174 */
1175 if (Var_Exists("VPATH", VAR_CMD)) {
1176 char *vpath, savec;
1177 /*
1178 * GCC stores string constants in read-only memory, but
1179 * Var_Subst will want to write this thing, so store it
1180 * in an array
1181 */
1182 static char VPATH[] = "${VPATH}";
1183
1184 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1185 path = vpath;
1186 do {
1187 /* skip to end of directory */
1188 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1189 continue;
1190 /* Save terminator character so know when to stop */
1191 savec = *cp;
1192 *cp = '\0';
1193 /* Add directory to search path */
1194 (void)Dir_AddDir(dirSearchPath, path);
1195 *cp = savec;
1196 path = cp + 1;
1197 } while (savec == ':');
1198 free(vpath);
1199 }
1200
1201 /*
1202 * Now that all search paths have been read for suffixes et al, it's
1203 * time to add the default search path to their lists...
1204 */
1205 Suff_DoPaths();
1206
1207 /*
1208 * Propagate attributes through :: dependency lists.
1209 */
1210 Targ_Propagate();
1211
1212 /* print the initial graph, if the user requested it */
1213 if (DEBUG(GRAPH1))
1214 Targ_PrintGraph(1);
1215
1216 /* print the values of any variables requested by the user */
1217 if (printVars) {
1218 LstNode ln;
1219 Boolean expandVars;
1220
1221 if (debugVflag)
1222 expandVars = FALSE;
1223 else
1224 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1225 for (ln = Lst_First(variables); ln != NULL;
1226 ln = Lst_Succ(ln)) {
1227 char *var = (char *)Lst_Datum(ln);
1228 char *value;
1229
1230 if (strchr(var, '$')) {
1231 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1232 } else if (expandVars) {
1233 char tmp[128];
1234
1235 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1236 Fatal("%s: variable name too big: %s",
1237 progname, var);
1238 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1239 } else {
1240 value = Var_Value(var, VAR_GLOBAL, &p1);
1241 }
1242 printf("%s\n", value ? value : "");
1243 if (p1)
1244 free(p1);
1245 }
1246 } else {
1247 /*
1248 * Have now read the entire graph and need to make a list of
1249 * targets to create. If none was given on the command line,
1250 * we consult the parsing module to find the main target(s)
1251 * to create.
1252 */
1253 if (Lst_IsEmpty(create))
1254 targs = Parse_MainName();
1255 else
1256 targs = Targ_FindList(create, TARG_CREATE);
1257
1258 if (!compatMake) {
1259 /*
1260 * Initialize job module before traversing the graph
1261 * now that any .BEGIN and .END targets have been read.
1262 * This is done only if the -q flag wasn't given
1263 * (to prevent the .BEGIN from being executed should
1264 * it exist).
1265 */
1266 if (!queryFlag) {
1267 Job_Init();
1268 jobsRunning = TRUE;
1269 }
1270
1271 /* Traverse the graph, checking on all the targets */
1272 outOfDate = Make_Run(targs);
1273 } else {
1274 /*
1275 * Compat_Init will take care of creating all the
1276 * targets as well as initializing the module.
1277 */
1278 Compat_Run(targs);
1279 }
1280 }
1281
1282 #ifdef CLEANUP
1283 Lst_Destroy(targs, NULL);
1284 Lst_Destroy(variables, NULL);
1285 Lst_Destroy(makefiles, NULL);
1286 Lst_Destroy(create, (FreeProc *)free);
1287 #endif
1288
1289 /* print the graph now it's been processed if the user requested it */
1290 if (DEBUG(GRAPH2))
1291 Targ_PrintGraph(2);
1292
1293 Trace_Log(MAKEEND, 0);
1294
1295 Suff_End();
1296 Targ_End();
1297 Arch_End();
1298 Var_End();
1299 Parse_End();
1300 Dir_End();
1301 Job_End();
1302 Trace_End();
1303
1304 return outOfDate ? 1 : 0;
1305 }
1306
1307 /*-
1308 * ReadMakefile --
1309 * Open and parse the given makefile.
1310 *
1311 * Results:
1312 * 0 if ok. -1 if couldn't open file.
1313 *
1314 * Side Effects:
1315 * lots
1316 */
1317 static int
1318 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1319 {
1320 const char *fname = p; /* makefile to read */
1321 int fd;
1322 size_t len = MAXPATHLEN;
1323 char *name, *path = bmake_malloc(len);
1324
1325 if (!strcmp(fname, "-")) {
1326 Parse_File(NULL /*stdin*/, -1);
1327 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1328 } else {
1329 /* if we've chdir'd, rebuild the path name */
1330 if (strcmp(curdir, objdir) && *fname != '/') {
1331 size_t plen = strlen(curdir) + strlen(fname) + 2;
1332 if (len < plen)
1333 path = bmake_realloc(path, len = 2 * plen);
1334
1335 (void)snprintf(path, len, "%s/%s", curdir, fname);
1336 fd = open(path, O_RDONLY);
1337 if (fd != -1) {
1338 fname = path;
1339 goto found;
1340 }
1341
1342 /* If curdir failed, try objdir (ala .depend) */
1343 plen = strlen(objdir) + strlen(fname) + 2;
1344 if (len < plen)
1345 path = bmake_realloc(path, len = 2 * plen);
1346 (void)snprintf(path, len, "%s/%s", objdir, fname);
1347 fd = open(path, O_RDONLY);
1348 if (fd != -1) {
1349 fname = path;
1350 goto found;
1351 }
1352 } else {
1353 fd = open(fname, O_RDONLY);
1354 if (fd != -1)
1355 goto found;
1356 }
1357 /* look in -I and system include directories. */
1358 name = Dir_FindFile(fname, parseIncPath);
1359 if (!name)
1360 name = Dir_FindFile(fname,
1361 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1362 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1363 if (name)
1364 free(name);
1365 free(path);
1366 return(-1);
1367 }
1368 fname = name;
1369 /*
1370 * set the MAKEFILE variable desired by System V fans -- the
1371 * placement of the setting here means it gets set to the last
1372 * makefile specified, as it is set by SysV make.
1373 */
1374 found:
1375 if (!doing_depend)
1376 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1377 Parse_File(fname, fd);
1378 }
1379 free(path);
1380 return(0);
1381 }
1382
1383
1384
1385 /*-
1386 * Cmd_Exec --
1387 * Execute the command in cmd, and return the output of that command
1388 * in a string.
1389 *
1390 * Results:
1391 * A string containing the output of the command, or the empty string
1392 * If errnum is not NULL, it contains the reason for the command failure
1393 *
1394 * Side Effects:
1395 * The string must be freed by the caller.
1396 */
1397 char *
1398 Cmd_Exec(const char *cmd, const char **errnum)
1399 {
1400 const char *args[4]; /* Args for invoking the shell */
1401 int fds[2]; /* Pipe streams */
1402 int cpid; /* Child PID */
1403 int pid; /* PID from wait() */
1404 char *res; /* result */
1405 int status; /* command exit status */
1406 Buffer buf; /* buffer to store the result */
1407 char *cp;
1408 int cc;
1409
1410
1411 *errnum = NULL;
1412
1413 if (!shellName)
1414 Shell_Init();
1415 /*
1416 * Set up arguments for shell
1417 */
1418 args[0] = shellName;
1419 args[1] = "-c";
1420 args[2] = cmd;
1421 args[3] = NULL;
1422
1423 /*
1424 * Open a pipe for fetching its output
1425 */
1426 if (pipe(fds) == -1) {
1427 *errnum = "Couldn't create pipe for \"%s\"";
1428 goto bad;
1429 }
1430
1431 /*
1432 * Fork
1433 */
1434 switch (cpid = vFork()) {
1435 case 0:
1436 /*
1437 * Close input side of pipe
1438 */
1439 (void)close(fds[0]);
1440
1441 /*
1442 * Duplicate the output stream to the shell's output, then
1443 * shut the extra thing down. Note we don't fetch the error
1444 * stream...why not? Why?
1445 */
1446 (void)dup2(fds[1], 1);
1447 (void)close(fds[1]);
1448
1449 Var_ExportVars();
1450
1451 (void)execv(shellPath, UNCONST(args));
1452 _exit(1);
1453 /*NOTREACHED*/
1454
1455 case -1:
1456 *errnum = "Couldn't exec \"%s\"";
1457 goto bad;
1458
1459 default:
1460 /*
1461 * No need for the writing half
1462 */
1463 (void)close(fds[1]);
1464
1465 Buf_Init(&buf, 0);
1466
1467 do {
1468 char result[BUFSIZ];
1469 cc = read(fds[0], result, sizeof(result));
1470 if (cc > 0)
1471 Buf_AddBytes(&buf, cc, result);
1472 }
1473 while (cc > 0 || (cc == -1 && errno == EINTR));
1474
1475 /*
1476 * Close the input side of the pipe.
1477 */
1478 (void)close(fds[0]);
1479
1480 /*
1481 * Wait for the process to exit.
1482 */
1483 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1484 JobReapChild(pid, status, FALSE);
1485 continue;
1486 }
1487 cc = Buf_Size(&buf);
1488 res = Buf_Destroy(&buf, FALSE);
1489
1490 if (cc == 0)
1491 *errnum = "Couldn't read shell's output for \"%s\"";
1492
1493 if (WIFSIGNALED(status))
1494 *errnum = "\"%s\" exited on a signal";
1495 else if (WEXITSTATUS(status) != 0)
1496 *errnum = "\"%s\" returned non-zero status";
1497
1498 /*
1499 * Null-terminate the result, convert newlines to spaces and
1500 * install it in the variable.
1501 */
1502 res[cc] = '\0';
1503 cp = &res[cc];
1504
1505 if (cc > 0 && *--cp == '\n') {
1506 /*
1507 * A final newline is just stripped
1508 */
1509 *cp-- = '\0';
1510 }
1511 while (cp >= res) {
1512 if (*cp == '\n') {
1513 *cp = ' ';
1514 }
1515 cp--;
1516 }
1517 break;
1518 }
1519 return res;
1520 bad:
1521 res = bmake_malloc(1);
1522 *res = '\0';
1523 return res;
1524 }
1525
1526 /*-
1527 * Error --
1528 * Print an error message given its format.
1529 *
1530 * Results:
1531 * None.
1532 *
1533 * Side Effects:
1534 * The message is printed.
1535 */
1536 /* VARARGS */
1537 void
1538 Error(const char *fmt, ...)
1539 {
1540 va_list ap;
1541 FILE *err_file;
1542
1543 err_file = debug_file;
1544 if (err_file == stdout)
1545 err_file = stderr;
1546 (void)fflush(stdout);
1547 for (;;) {
1548 va_start(ap, fmt);
1549 fprintf(err_file, "%s: ", progname);
1550 (void)vfprintf(err_file, fmt, ap);
1551 va_end(ap);
1552 (void)fprintf(err_file, "\n");
1553 (void)fflush(err_file);
1554 if (err_file == stderr)
1555 break;
1556 err_file = stderr;
1557 }
1558 }
1559
1560 /*-
1561 * Fatal --
1562 * Produce a Fatal error message. If jobs are running, waits for them
1563 * to finish.
1564 *
1565 * Results:
1566 * None
1567 *
1568 * Side Effects:
1569 * The program exits
1570 */
1571 /* VARARGS */
1572 void
1573 Fatal(const char *fmt, ...)
1574 {
1575 va_list ap;
1576
1577 va_start(ap, fmt);
1578 if (jobsRunning)
1579 Job_Wait();
1580
1581 (void)fflush(stdout);
1582 (void)vfprintf(stderr, fmt, ap);
1583 va_end(ap);
1584 (void)fprintf(stderr, "\n");
1585 (void)fflush(stderr);
1586
1587 PrintOnError(NULL, NULL);
1588
1589 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1590 Targ_PrintGraph(2);
1591 Trace_Log(MAKEERROR, 0);
1592 exit(2); /* Not 1 so -q can distinguish error */
1593 }
1594
1595 /*
1596 * Punt --
1597 * Major exception once jobs are being created. Kills all jobs, prints
1598 * a message and exits.
1599 *
1600 * Results:
1601 * None
1602 *
1603 * Side Effects:
1604 * All children are killed indiscriminately and the program Lib_Exits
1605 */
1606 /* VARARGS */
1607 void
1608 Punt(const char *fmt, ...)
1609 {
1610 va_list ap;
1611
1612 va_start(ap, fmt);
1613 (void)fflush(stdout);
1614 (void)fprintf(stderr, "%s: ", progname);
1615 (void)vfprintf(stderr, fmt, ap);
1616 va_end(ap);
1617 (void)fprintf(stderr, "\n");
1618 (void)fflush(stderr);
1619
1620 PrintOnError(NULL, NULL);
1621
1622 DieHorribly();
1623 }
1624
1625 /*-
1626 * DieHorribly --
1627 * Exit without giving a message.
1628 *
1629 * Results:
1630 * None
1631 *
1632 * Side Effects:
1633 * A big one...
1634 */
1635 void
1636 DieHorribly(void)
1637 {
1638 if (jobsRunning)
1639 Job_AbortAll();
1640 if (DEBUG(GRAPH2))
1641 Targ_PrintGraph(2);
1642 Trace_Log(MAKEERROR, 0);
1643 exit(2); /* Not 1, so -q can distinguish error */
1644 }
1645
1646 /*
1647 * Finish --
1648 * Called when aborting due to errors in child shell to signal
1649 * abnormal exit.
1650 *
1651 * Results:
1652 * None
1653 *
1654 * Side Effects:
1655 * The program exits
1656 */
1657 void
1658 Finish(int errors)
1659 /* number of errors encountered in Make_Make */
1660 {
1661 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1662 }
1663
1664 /*
1665 * enunlink --
1666 * Remove a file carefully, avoiding directories.
1667 */
1668 int
1669 eunlink(const char *file)
1670 {
1671 struct stat st;
1672
1673 if (lstat(file, &st) == -1)
1674 return -1;
1675
1676 if (S_ISDIR(st.st_mode)) {
1677 errno = EISDIR;
1678 return -1;
1679 }
1680 return unlink(file);
1681 }
1682
1683 /*
1684 * execError --
1685 * Print why exec failed, avoiding stdio.
1686 */
1687 void
1688 execError(const char *af, const char *av)
1689 {
1690 #ifdef USE_IOVEC
1691 int i = 0;
1692 struct iovec iov[8];
1693 #define IOADD(s) \
1694 (void)(iov[i].iov_base = UNCONST(s), \
1695 iov[i].iov_len = strlen(iov[i].iov_base), \
1696 i++)
1697 #else
1698 #define IOADD(void)write(2, s, strlen(s))
1699 #endif
1700
1701 IOADD(progname);
1702 IOADD(": ");
1703 IOADD(af);
1704 IOADD("(");
1705 IOADD(av);
1706 IOADD(") failed (");
1707 IOADD(strerror(errno));
1708 IOADD(")\n");
1709
1710 #ifdef USE_IOVEC
1711 (void)writev(2, iov, 8);
1712 #endif
1713 }
1714
1715 /*
1716 * usage --
1717 * exit with usage message
1718 */
1719 static void
1720 usage(void)
1721 {
1722 (void)fprintf(stderr,
1723 "usage: %s [-BeikNnqrstWX] \n\
1724 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1725 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1726 [-V variable] [variable=value] [target ...]\n", progname);
1727 exit(2);
1728 }
1729
1730
1731 int
1732 PrintAddr(void *a, void *b)
1733 {
1734 printf("%lx ", (unsigned long) a);
1735 return b ? 0 : 0;
1736 }
1737
1738
1739
1740 void
1741 PrintOnError(GNode *gn, const char *s)
1742 {
1743 static GNode *en = NULL;
1744 char tmp[64];
1745 char *cp;
1746
1747 if (s)
1748 printf("%s", s);
1749
1750 printf("\n%s: stopped in %s\n", progname, curdir);
1751
1752 if (en)
1753 return; /* we've been here! */
1754 if (gn) {
1755 /*
1756 * We can print this even if there is no .ERROR target.
1757 */
1758 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1759 }
1760 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1761 sizeof(tmp) - 1);
1762 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1763 if (cp) {
1764 if (*cp)
1765 printf("%s", cp);
1766 free(cp);
1767 }
1768 /*
1769 * Finally, see if there is a .ERROR target, and run it if so.
1770 */
1771 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1772 if (en) {
1773 en->type |= OP_SPECIAL;
1774 Compat_Make(en, en);
1775 }
1776 }
1777
1778 void
1779 Main_ExportMAKEFLAGS(Boolean first)
1780 {
1781 static int once = 1;
1782 char tmp[64];
1783 char *s;
1784
1785 if (once != first)
1786 return;
1787 once = 0;
1788
1789 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1790 sizeof(tmp));
1791 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1792 if (s && *s) {
1793 #ifdef POSIX
1794 setenv("MAKEFLAGS", s, 1);
1795 #else
1796 setenv("MAKE", s, 1);
1797 #endif
1798 }
1799 }
1800
1801 char *
1802 getTmpdir(void)
1803 {
1804 static char *tmpdir = NULL;
1805
1806 if (!tmpdir) {
1807 struct stat st;
1808
1809 /*
1810 * Honor $TMPDIR but only if it is valid.
1811 * Ensure it ends with /.
1812 */
1813 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1814 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1815 free(tmpdir);
1816 tmpdir = bmake_strdup(_PATH_TMP);
1817 }
1818 }
1819 return tmpdir;
1820 }
1821
1822 /*
1823 * Create and open a temp file using "pattern".
1824 * If "fnamep" is provided set it to a copy of the filename created.
1825 * Otherwise unlink the file once open.
1826 */
1827 int
1828 mkTempFile(const char *pattern, char **fnamep)
1829 {
1830 static char *tmpdir = NULL;
1831 char tfile[MAXPATHLEN];
1832 int fd;
1833
1834 if (!pattern)
1835 pattern = TMPPAT;
1836 if (!tmpdir)
1837 tmpdir = getTmpdir();
1838 if (pattern[0] == '/') {
1839 snprintf(tfile, sizeof(tfile), "%s", pattern);
1840 } else {
1841 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1842 }
1843 if ((fd = mkstemp(tfile)) < 0)
1844 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1845 if (fnamep) {
1846 *fnamep = bmake_strdup(tfile);
1847 } else {
1848 unlink(tfile); /* we just want the descriptor */
1849 }
1850 return fd;
1851 }
1852
1853
1854 /*
1855 * Return a Boolean based on setting of a knob.
1856 *
1857 * If the knob is not set, the supplied default is the return value.
1858 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1859 * is FALSE, otherwise TRUE.
1860 */
1861 Boolean
1862 getBoolean(const char *name, Boolean bf)
1863 {
1864 char tmp[64];
1865 char *cp;
1866
1867 if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1868 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1869
1870 if (cp) {
1871 switch(*cp) {
1872 case '\0': /* not set - the default wins */
1873 break;
1874 case '0':
1875 case 'f':
1876 case 'n':
1877 bf = FALSE;
1878 break;
1879 case 'o':
1880 switch (cp[1]) {
1881 case 'f':
1882 bf = FALSE;
1883 break;
1884 default:
1885 bf = TRUE;
1886 break;
1887 }
1888 break;
1889 default:
1890 bf = TRUE;
1891 break;
1892 }
1893 free(cp);
1894 }
1895 }
1896 return (bf);
1897 }
1898