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