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