main.c revision 1.261 1 /* $NetBSD: main.c,v 1.261 2017/04/16 20:00:58 maya 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.261 2017/04/16 20:00:58 maya 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.261 2017/04/16 20:00:58 maya 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 = bmake_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 *path;
695 char buf[MAXPATHLEN + 1];
696 Boolean rc = FALSE;
697 va_list ap;
698
699 va_start(ap, fmt);
700 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
701 va_end(ap);
702
703 if (path[0] != '/') {
704 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
705 path = buf;
706 }
707
708 /* look for the directory and try to chdir there */
709 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
710 if (chdir(path)) {
711 (void)fprintf(stderr, "make warning: %s: %s.\n",
712 path, strerror(errno));
713 } else {
714 strncpy(objdir, path, MAXPATHLEN);
715 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
716 setenv("PWD", objdir, 1);
717 Dir_InitDot();
718 cached_realpath(".OBJDIR", NULL); /* purge */
719 rc = TRUE;
720 if (enterFlag && strcmp(objdir, curdir) != 0)
721 enterFlagObj = TRUE;
722 }
723 }
724
725 return rc;
726 }
727
728 static Boolean
729 Main_SetVarObjdir(const char *var, const char *suffix)
730 {
731 char *p, *path, *xpath;
732
733 if ((path = Var_Value(var, VAR_CMD, &p)) == NULL)
734 return FALSE;
735
736 /* expand variable substitutions */
737 if (strchr(path, '$') != 0)
738 xpath = Var_Subst(NULL, path, VAR_GLOBAL, VARF_WANTRES);
739 else
740 xpath = path;
741
742 (void)Main_SetObjdir("%s%s", xpath, suffix);
743
744 if (xpath != path)
745 free(xpath);
746 free(p);
747 return TRUE;
748 }
749
750 /*-
751 * ReadAllMakefiles --
752 * wrapper around ReadMakefile() to read all.
753 *
754 * Results:
755 * TRUE if ok, FALSE on error
756 */
757 static int
758 ReadAllMakefiles(const void *p, const void *q)
759 {
760 return (ReadMakefile(p, q) == 0);
761 }
762
763 int
764 str2Lst_Append(Lst lp, char *str, const char *sep)
765 {
766 char *cp;
767 int n;
768
769 if (!sep)
770 sep = " \t";
771
772 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
773 (void)Lst_AtEnd(lp, cp);
774 n++;
775 }
776 return (n);
777 }
778
779 #ifdef SIGINFO
780 /*ARGSUSED*/
781 static void
782 siginfo(int signo MAKE_ATTR_UNUSED)
783 {
784 char dir[MAXPATHLEN];
785 char str[2 * MAXPATHLEN];
786 int len;
787 if (getcwd(dir, sizeof(dir)) == NULL)
788 return;
789 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
790 if (len > 0)
791 (void)write(STDERR_FILENO, str, (size_t)len);
792 }
793 #endif
794
795 /*
796 * Allow makefiles some control over the mode we run in.
797 */
798 void
799 MakeMode(const char *mode)
800 {
801 char *mp = NULL;
802
803 if (!mode)
804 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}",
805 VAR_GLOBAL, VARF_WANTRES);
806
807 if (mode && *mode) {
808 if (strstr(mode, "compat")) {
809 compatMake = TRUE;
810 forceJobs = FALSE;
811 }
812 #if USE_META
813 if (strstr(mode, "meta"))
814 meta_mode_init(mode);
815 #endif
816 }
817
818 free(mp);
819 }
820
821 /*-
822 * main --
823 * The main function, for obvious reasons. Initializes variables
824 * and a few modules, then parses the arguments give it in the
825 * environment and on the command line. Reads the system makefile
826 * followed by either Makefile, makefile or the file given by the
827 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
828 * flags it has received by then uses either the Make or the Compat
829 * module to create the initial list of targets.
830 *
831 * Results:
832 * If -q was given, exits -1 if anything was out-of-date. Else it exits
833 * 0.
834 *
835 * Side Effects:
836 * The program exits when done. Targets are created. etc. etc. etc.
837 */
838 int
839 main(int argc, char **argv)
840 {
841 Lst targs; /* target nodes to create -- passed to Make_Init */
842 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
843 struct stat sb, sa;
844 char *p1, *path;
845 char mdpath[MAXPATHLEN];
846 const char *machine = getenv("MACHINE");
847 const char *machine_arch = getenv("MACHINE_ARCH");
848 char *syspath = getenv("MAKESYSPATH");
849 Lst sysMkPath; /* Path of sys.mk */
850 char *cp = NULL, *start;
851 /* avoid faults on read-only strings */
852 static char defsyspath[] = _PATH_DEFSYSPATH;
853 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
854 struct timeval rightnow; /* to initialize random seed */
855 struct utsname utsname;
856
857 /* default to writing debug to stderr */
858 debug_file = stderr;
859
860 #ifdef SIGINFO
861 (void)bmake_signal(SIGINFO, siginfo);
862 #endif
863 /*
864 * Set the seed to produce a different random sequence
865 * on each program execution.
866 */
867 gettimeofday(&rightnow, NULL);
868 srandom(rightnow.tv_sec + rightnow.tv_usec);
869
870 if ((progname = strrchr(argv[0], '/')) != NULL)
871 progname++;
872 else
873 progname = argv[0];
874 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
875 /*
876 * get rid of resource limit on file descriptors
877 */
878 {
879 struct rlimit rl;
880 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
881 rl.rlim_cur != rl.rlim_max) {
882 rl.rlim_cur = rl.rlim_max;
883 (void)setrlimit(RLIMIT_NOFILE, &rl);
884 }
885 }
886 #endif
887
888 if (uname(&utsname) == -1) {
889 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
890 strerror(errno));
891 exit(2);
892 }
893
894 /*
895 * Get the name of this type of MACHINE from utsname
896 * so we can share an executable for similar machines.
897 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
898 *
899 * Note that both MACHINE and MACHINE_ARCH are decided at
900 * run-time.
901 */
902 if (!machine) {
903 #ifdef MAKE_NATIVE
904 machine = utsname.machine;
905 #else
906 #ifdef MAKE_MACHINE
907 machine = MAKE_MACHINE;
908 #else
909 machine = "unknown";
910 #endif
911 #endif
912 }
913
914 if (!machine_arch) {
915 #ifdef MAKE_NATIVE
916 static char machine_arch_buf[sizeof(utsname.machine)];
917 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
918 size_t len = sizeof(machine_arch_buf);
919
920 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
921 &len, NULL, 0) < 0) {
922 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
923 strerror(errno));
924 exit(2);
925 }
926
927 machine_arch = machine_arch_buf;
928 #else
929 #ifndef MACHINE_ARCH
930 #ifdef MAKE_MACHINE_ARCH
931 machine_arch = MAKE_MACHINE_ARCH;
932 #else
933 machine_arch = "unknown";
934 #endif
935 #else
936 machine_arch = MACHINE_ARCH;
937 #endif
938 #endif
939 }
940
941 myPid = getpid(); /* remember this for vFork() */
942
943 /*
944 * Just in case MAKEOBJDIR wants us to do something tricky.
945 */
946 Var_Init(); /* Initialize the lists of variables for
947 * parsing arguments */
948 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
949 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
950 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
951 #ifdef MAKE_VERSION
952 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
953 #endif
954 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
955 /*
956 * This is the traditional preference for makefiles.
957 */
958 #ifndef MAKEFILE_PREFERENCE_LIST
959 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
960 #endif
961 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
962 VAR_GLOBAL, 0);
963 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
964
965 create = Lst_Init(FALSE);
966 makefiles = Lst_Init(FALSE);
967 printVars = FALSE;
968 debugVflag = FALSE;
969 variables = Lst_Init(FALSE);
970 beSilent = FALSE; /* Print commands as executed */
971 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
972 noExecute = FALSE; /* Execute all commands */
973 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
974 keepgoing = FALSE; /* Stop on error */
975 allPrecious = FALSE; /* Remove targets when interrupted */
976 deleteOnError = FALSE; /* Historical default behavior */
977 queryFlag = FALSE; /* This is not just a check-run */
978 noBuiltins = FALSE; /* Read the built-in rules */
979 touchFlag = FALSE; /* Actually update targets */
980 debug = 0; /* No debug verbosity, please. */
981 jobsRunning = FALSE;
982
983 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
984 maxJobTokens = maxJobs;
985 compatMake = FALSE; /* No compat mode */
986 ignorePWD = FALSE;
987
988 /*
989 * Initialize the parsing, directory and variable modules to prepare
990 * for the reading of inclusion paths and variable settings on the
991 * command line
992 */
993
994 /*
995 * Initialize various variables.
996 * MAKE also gets this name, for compatibility
997 * .MAKEFLAGS gets set to the empty string just in case.
998 * MFLAGS also gets initialized empty, for compatibility.
999 */
1000 Parse_Init();
1001 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1002 /*
1003 * Leave alone if it is an absolute path, or if it does
1004 * not contain a '/' in which case we need to find it in
1005 * the path, like execvp(3) and the shells do.
1006 */
1007 p1 = argv[0];
1008 } else {
1009 /*
1010 * A relative path, canonicalize it.
1011 */
1012 p1 = cached_realpath(argv[0], mdpath);
1013 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1014 p1 = argv[0]; /* realpath failed */
1015 }
1016 }
1017 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
1018 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
1019 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
1020 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
1021 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
1022 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
1023 /* some makefiles need to know this */
1024 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
1025
1026 /*
1027 * Set some other useful macros
1028 */
1029 {
1030 char tmp[64], *ep;
1031
1032 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1033 if (makelevel < 0)
1034 makelevel = 0;
1035 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1036 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
1037 snprintf(tmp, sizeof(tmp), "%u", myPid);
1038 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
1039 snprintf(tmp, sizeof(tmp), "%u", getppid());
1040 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
1041 }
1042 if (makelevel > 0) {
1043 char pn[1024];
1044 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1045 progname = bmake_strdup(pn);
1046 }
1047
1048 #ifdef USE_META
1049 meta_init();
1050 #endif
1051 Dir_Init(NULL); /* Dir_* safe to call from MainParseArgs */
1052
1053 /*
1054 * First snag any flags out of the MAKE environment variable.
1055 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1056 * in a different format).
1057 */
1058 #ifdef POSIX
1059 p1 = explode(getenv("MAKEFLAGS"));
1060 Main_ParseArgLine(p1);
1061 free(p1);
1062 #else
1063 Main_ParseArgLine(getenv("MAKE"));
1064 #endif
1065
1066 /*
1067 * Find where we are (now).
1068 * We take care of PWD for the automounter below...
1069 */
1070 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1071 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1072 progname, strerror(errno));
1073 exit(2);
1074 }
1075
1076 MainParseArgs(argc, argv);
1077
1078 if (enterFlag)
1079 printf("%s: Entering directory `%s'\n", progname, curdir);
1080
1081 /*
1082 * Verify that cwd is sane.
1083 */
1084 if (stat(curdir, &sa) == -1) {
1085 (void)fprintf(stderr, "%s: %s: %s.\n",
1086 progname, curdir, strerror(errno));
1087 exit(2);
1088 }
1089
1090 /*
1091 * All this code is so that we know where we are when we start up
1092 * on a different machine with pmake.
1093 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1094 * since the value of curdir can vary depending on how we got
1095 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1096 * or via subdir.mk in which case its likely a shell which does
1097 * not provide it.
1098 * So, to stop it breaking this case only, we ignore PWD if
1099 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1100 */
1101 #ifndef NO_PWD_OVERRIDE
1102 if (!ignorePWD) {
1103 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1104
1105 if ((pwd = getenv("PWD")) != NULL &&
1106 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1107 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1108 VAR_CMD, &ptmp2);
1109
1110 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1111 if (stat(pwd, &sb) == 0 &&
1112 sa.st_ino == sb.st_ino &&
1113 sa.st_dev == sb.st_dev)
1114 (void)strncpy(curdir, pwd, MAXPATHLEN);
1115 }
1116 }
1117 free(ptmp1);
1118 free(ptmp2);
1119 }
1120 #endif
1121 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1122
1123 /*
1124 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1125 * MAKEOBJDIR is set in the environment, try only that value
1126 * and fall back to .CURDIR if it does not exist.
1127 *
1128 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1129 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1130 * of these paths exist, just use .CURDIR.
1131 */
1132 Dir_Init(curdir);
1133 (void)Main_SetObjdir("%s", curdir);
1134
1135 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1136 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1137 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1138 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1139 !Main_SetObjdir("%s", _PATH_OBJDIR))
1140 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1141
1142 /*
1143 * Initialize archive, target and suffix modules in preparation for
1144 * parsing the makefile(s)
1145 */
1146 Arch_Init();
1147 Targ_Init();
1148 Suff_Init();
1149 Trace_Init(tracefile);
1150
1151 DEFAULT = NULL;
1152 (void)time(&now);
1153
1154 Trace_Log(MAKESTART, NULL);
1155
1156 /*
1157 * Set up the .TARGETS variable to contain the list of targets to be
1158 * created. If none specified, make the variable empty -- the parser
1159 * will fill the thing in with the default or .MAIN target.
1160 */
1161 if (!Lst_IsEmpty(create)) {
1162 LstNode ln;
1163
1164 for (ln = Lst_First(create); ln != NULL;
1165 ln = Lst_Succ(ln)) {
1166 char *name = (char *)Lst_Datum(ln);
1167
1168 Var_Append(".TARGETS", name, VAR_GLOBAL);
1169 }
1170 } else
1171 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1172
1173
1174 /*
1175 * If no user-supplied system path was given (through the -m option)
1176 * add the directories from the DEFSYSPATH (more than one may be given
1177 * as dir1:...:dirn) to the system include path.
1178 */
1179 if (syspath == NULL || *syspath == '\0')
1180 syspath = defsyspath;
1181 else
1182 syspath = bmake_strdup(syspath);
1183
1184 for (start = syspath; *start != '\0'; start = cp) {
1185 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1186 continue;
1187 if (*cp == ':') {
1188 *cp++ = '\0';
1189 }
1190 /* look for magic parent directory search string */
1191 if (strncmp(".../", start, 4) != 0) {
1192 (void)Dir_AddDir(defIncPath, start);
1193 } else {
1194 if (Dir_FindHereOrAbove(curdir, start+4,
1195 found_path, sizeof(found_path))) {
1196 (void)Dir_AddDir(defIncPath, found_path);
1197 }
1198 }
1199 }
1200 if (syspath != defsyspath)
1201 free(syspath);
1202
1203 /*
1204 * Read in the built-in rules first, followed by the specified
1205 * makefile, if it was (makefile != NULL), or the default
1206 * makefile and Makefile, in that order, if it wasn't.
1207 */
1208 if (!noBuiltins) {
1209 LstNode ln;
1210
1211 sysMkPath = Lst_Init(FALSE);
1212 Dir_Expand(_PATH_DEFSYSMK,
1213 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1214 sysMkPath);
1215 if (Lst_IsEmpty(sysMkPath))
1216 Fatal("%s: no system rules (%s).", progname,
1217 _PATH_DEFSYSMK);
1218 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1219 if (ln == NULL)
1220 Fatal("%s: cannot open %s.", progname,
1221 (char *)Lst_Datum(ln));
1222 }
1223
1224 if (!Lst_IsEmpty(makefiles)) {
1225 LstNode ln;
1226
1227 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1228 if (ln != NULL)
1229 Fatal("%s: cannot open %s.", progname,
1230 (char *)Lst_Datum(ln));
1231 } else {
1232 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1233 VAR_CMD, VARF_WANTRES);
1234 if (p1) {
1235 (void)str2Lst_Append(makefiles, p1, NULL);
1236 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1237 free(p1);
1238 }
1239 }
1240
1241 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1242 if (!noBuiltins || !printVars) {
1243 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1244 VAR_CMD, VARF_WANTRES);
1245 doing_depend = TRUE;
1246 (void)ReadMakefile(makeDependfile, NULL);
1247 doing_depend = FALSE;
1248 }
1249
1250 if (enterFlagObj)
1251 printf("%s: Entering directory `%s'\n", progname, objdir);
1252
1253 MakeMode(NULL);
1254
1255 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1256 free(p1);
1257
1258 if (!forceJobs && !compatMake &&
1259 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1260 char *value;
1261 int n;
1262
1263 value = Var_Subst(NULL, "${.MAKE.JOBS}", VAR_GLOBAL, VARF_WANTRES);
1264 n = strtol(value, NULL, 0);
1265 if (n < 1) {
1266 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1267 progname);
1268 exit(1);
1269 }
1270 if (n != maxJobs) {
1271 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1272 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1273 }
1274 maxJobs = n;
1275 maxJobTokens = maxJobs;
1276 forceJobs = TRUE;
1277 free(value);
1278 }
1279
1280 /*
1281 * Be compatible if user did not specify -j and did not explicitly
1282 * turned compatibility on
1283 */
1284 if (!compatMake && !forceJobs) {
1285 compatMake = TRUE;
1286 }
1287
1288 if (!compatMake)
1289 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1290 if (DEBUG(JOB))
1291 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1292 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1293
1294 if (!printVars)
1295 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1296
1297
1298 /*
1299 * For compatibility, look at the directories in the VPATH variable
1300 * and add them to the search path, if the variable is defined. The
1301 * variable's value is in the same format as the PATH envariable, i.e.
1302 * <directory>:<directory>:<directory>...
1303 */
1304 if (Var_Exists("VPATH", VAR_CMD)) {
1305 char *vpath, savec;
1306 /*
1307 * GCC stores string constants in read-only memory, but
1308 * Var_Subst will want to write this thing, so store it
1309 * in an array
1310 */
1311 static char VPATH[] = "${VPATH}";
1312
1313 vpath = Var_Subst(NULL, VPATH, VAR_CMD, VARF_WANTRES);
1314 path = vpath;
1315 do {
1316 /* skip to end of directory */
1317 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1318 continue;
1319 /* Save terminator character so know when to stop */
1320 savec = *cp;
1321 *cp = '\0';
1322 /* Add directory to search path */
1323 (void)Dir_AddDir(dirSearchPath, path);
1324 *cp = savec;
1325 path = cp + 1;
1326 } while (savec == ':');
1327 free(vpath);
1328 }
1329
1330 /*
1331 * Now that all search paths have been read for suffixes et al, it's
1332 * time to add the default search path to their lists...
1333 */
1334 Suff_DoPaths();
1335
1336 /*
1337 * Propagate attributes through :: dependency lists.
1338 */
1339 Targ_Propagate();
1340
1341 /* print the initial graph, if the user requested it */
1342 if (DEBUG(GRAPH1))
1343 Targ_PrintGraph(1);
1344
1345 /* print the values of any variables requested by the user */
1346 if (printVars) {
1347 LstNode ln;
1348 Boolean expandVars;
1349
1350 if (debugVflag)
1351 expandVars = FALSE;
1352 else
1353 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1354 for (ln = Lst_First(variables); ln != NULL;
1355 ln = Lst_Succ(ln)) {
1356 char *var = (char *)Lst_Datum(ln);
1357 char *value;
1358
1359 if (strchr(var, '$')) {
1360 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL,
1361 VARF_WANTRES);
1362 } else if (expandVars) {
1363 char tmp[128];
1364
1365 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1366 Fatal("%s: variable name too big: %s",
1367 progname, var);
1368 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL,
1369 VARF_WANTRES);
1370 } else {
1371 value = Var_Value(var, VAR_GLOBAL, &p1);
1372 }
1373 printf("%s\n", value ? value : "");
1374 free(p1);
1375 }
1376 } else {
1377 /*
1378 * Have now read the entire graph and need to make a list of
1379 * targets to create. If none was given on the command line,
1380 * we consult the parsing module to find the main target(s)
1381 * to create.
1382 */
1383 if (Lst_IsEmpty(create))
1384 targs = Parse_MainName();
1385 else
1386 targs = Targ_FindList(create, TARG_CREATE);
1387
1388 if (!compatMake) {
1389 /*
1390 * Initialize job module before traversing the graph
1391 * now that any .BEGIN and .END targets have been read.
1392 * This is done only if the -q flag wasn't given
1393 * (to prevent the .BEGIN from being executed should
1394 * it exist).
1395 */
1396 if (!queryFlag) {
1397 Job_Init();
1398 jobsRunning = TRUE;
1399 }
1400
1401 /* Traverse the graph, checking on all the targets */
1402 outOfDate = Make_Run(targs);
1403 } else {
1404 /*
1405 * Compat_Init will take care of creating all the
1406 * targets as well as initializing the module.
1407 */
1408 Compat_Run(targs);
1409 }
1410 }
1411
1412 #ifdef CLEANUP
1413 Lst_Destroy(targs, NULL);
1414 Lst_Destroy(variables, NULL);
1415 Lst_Destroy(makefiles, NULL);
1416 Lst_Destroy(create, (FreeProc *)free);
1417 #endif
1418
1419 /* print the graph now it's been processed if the user requested it */
1420 if (DEBUG(GRAPH2))
1421 Targ_PrintGraph(2);
1422
1423 Trace_Log(MAKEEND, 0);
1424
1425 if (enterFlagObj)
1426 printf("%s: Leaving directory `%s'\n", progname, objdir);
1427 if (enterFlag)
1428 printf("%s: Leaving directory `%s'\n", progname, curdir);
1429
1430 #ifdef USE_META
1431 meta_finish();
1432 #endif
1433 Suff_End();
1434 Targ_End();
1435 Arch_End();
1436 Var_End();
1437 Parse_End();
1438 Dir_End();
1439 Job_End();
1440 Trace_End();
1441
1442 return outOfDate ? 1 : 0;
1443 }
1444
1445 /*-
1446 * ReadMakefile --
1447 * Open and parse the given makefile.
1448 *
1449 * Results:
1450 * 0 if ok. -1 if couldn't open file.
1451 *
1452 * Side Effects:
1453 * lots
1454 */
1455 static int
1456 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1457 {
1458 const char *fname = p; /* makefile to read */
1459 int fd;
1460 size_t len = MAXPATHLEN;
1461 char *name, *path = bmake_malloc(len);
1462
1463 if (!strcmp(fname, "-")) {
1464 Parse_File(NULL /*stdin*/, -1);
1465 Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1466 } else {
1467 /* if we've chdir'd, rebuild the path name */
1468 if (strcmp(curdir, objdir) && *fname != '/') {
1469 size_t plen = strlen(curdir) + strlen(fname) + 2;
1470 if (len < plen)
1471 path = bmake_realloc(path, len = 2 * plen);
1472
1473 (void)snprintf(path, len, "%s/%s", curdir, fname);
1474 fd = open(path, O_RDONLY);
1475 if (fd != -1) {
1476 fname = path;
1477 goto found;
1478 }
1479
1480 /* If curdir failed, try objdir (ala .depend) */
1481 plen = strlen(objdir) + strlen(fname) + 2;
1482 if (len < plen)
1483 path = bmake_realloc(path, len = 2 * plen);
1484 (void)snprintf(path, len, "%s/%s", objdir, fname);
1485 fd = open(path, O_RDONLY);
1486 if (fd != -1) {
1487 fname = path;
1488 goto found;
1489 }
1490 } else {
1491 fd = open(fname, O_RDONLY);
1492 if (fd != -1)
1493 goto found;
1494 }
1495 /* look in -I and system include directories. */
1496 name = Dir_FindFile(fname, parseIncPath);
1497 if (!name)
1498 name = Dir_FindFile(fname,
1499 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1500 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1501 free(name);
1502 free(path);
1503 return(-1);
1504 }
1505 fname = name;
1506 /*
1507 * set the MAKEFILE variable desired by System V fans -- the
1508 * placement of the setting here means it gets set to the last
1509 * makefile specified, as it is set by SysV make.
1510 */
1511 found:
1512 if (!doing_depend)
1513 Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1514 Parse_File(fname, fd);
1515 }
1516 free(path);
1517 return(0);
1518 }
1519
1520
1521
1522 /*-
1523 * Cmd_Exec --
1524 * Execute the command in cmd, and return the output of that command
1525 * in a string.
1526 *
1527 * Results:
1528 * A string containing the output of the command, or the empty string
1529 * If errnum is not NULL, it contains the reason for the command failure
1530 *
1531 * Side Effects:
1532 * The string must be freed by the caller.
1533 */
1534 char *
1535 Cmd_Exec(const char *cmd, const char **errnum)
1536 {
1537 const char *args[4]; /* Args for invoking the shell */
1538 int fds[2]; /* Pipe streams */
1539 int cpid; /* Child PID */
1540 int pid; /* PID from wait() */
1541 char *res; /* result */
1542 int status; /* command exit status */
1543 Buffer buf; /* buffer to store the result */
1544 char *cp;
1545 int cc; /* bytes read, or -1 */
1546 int savederr; /* saved errno */
1547
1548
1549 *errnum = NULL;
1550
1551 if (!shellName)
1552 Shell_Init();
1553 /*
1554 * Set up arguments for shell
1555 */
1556 args[0] = shellName;
1557 args[1] = "-c";
1558 args[2] = cmd;
1559 args[3] = NULL;
1560
1561 /*
1562 * Open a pipe for fetching its output
1563 */
1564 if (pipe(fds) == -1) {
1565 *errnum = "Couldn't create pipe for \"%s\"";
1566 goto bad;
1567 }
1568
1569 /*
1570 * Fork
1571 */
1572 switch (cpid = vFork()) {
1573 case 0:
1574 /*
1575 * Close input side of pipe
1576 */
1577 (void)close(fds[0]);
1578
1579 /*
1580 * Duplicate the output stream to the shell's output, then
1581 * shut the extra thing down. Note we don't fetch the error
1582 * stream...why not? Why?
1583 */
1584 (void)dup2(fds[1], 1);
1585 (void)close(fds[1]);
1586
1587 Var_ExportVars();
1588
1589 (void)execv(shellPath, UNCONST(args));
1590 _exit(1);
1591 /*NOTREACHED*/
1592
1593 case -1:
1594 *errnum = "Couldn't exec \"%s\"";
1595 goto bad;
1596
1597 default:
1598 /*
1599 * No need for the writing half
1600 */
1601 (void)close(fds[1]);
1602
1603 savederr = 0;
1604 Buf_Init(&buf, 0);
1605
1606 do {
1607 char result[BUFSIZ];
1608 cc = read(fds[0], result, sizeof(result));
1609 if (cc > 0)
1610 Buf_AddBytes(&buf, cc, result);
1611 }
1612 while (cc > 0 || (cc == -1 && errno == EINTR));
1613 if (cc == -1)
1614 savederr = errno;
1615
1616 /*
1617 * Close the input side of the pipe.
1618 */
1619 (void)close(fds[0]);
1620
1621 /*
1622 * Wait for the process to exit.
1623 */
1624 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1625 JobReapChild(pid, status, FALSE);
1626 continue;
1627 }
1628 cc = Buf_Size(&buf);
1629 res = Buf_Destroy(&buf, FALSE);
1630
1631 if (savederr != 0)
1632 *errnum = "Couldn't read shell's output for \"%s\"";
1633
1634 if (WIFSIGNALED(status))
1635 *errnum = "\"%s\" exited on a signal";
1636 else if (WEXITSTATUS(status) != 0)
1637 *errnum = "\"%s\" returned non-zero status";
1638
1639 /*
1640 * Null-terminate the result, convert newlines to spaces and
1641 * install it in the variable.
1642 */
1643 res[cc] = '\0';
1644 cp = &res[cc];
1645
1646 if (cc > 0 && *--cp == '\n') {
1647 /*
1648 * A final newline is just stripped
1649 */
1650 *cp-- = '\0';
1651 }
1652 while (cp >= res) {
1653 if (*cp == '\n') {
1654 *cp = ' ';
1655 }
1656 cp--;
1657 }
1658 break;
1659 }
1660 return res;
1661 bad:
1662 res = bmake_malloc(1);
1663 *res = '\0';
1664 return res;
1665 }
1666
1667 /*-
1668 * Error --
1669 * Print an error message given its format.
1670 *
1671 * Results:
1672 * None.
1673 *
1674 * Side Effects:
1675 * The message is printed.
1676 */
1677 /* VARARGS */
1678 void
1679 Error(const char *fmt, ...)
1680 {
1681 va_list ap;
1682 FILE *err_file;
1683
1684 err_file = debug_file;
1685 if (err_file == stdout)
1686 err_file = stderr;
1687 (void)fflush(stdout);
1688 for (;;) {
1689 va_start(ap, fmt);
1690 fprintf(err_file, "%s: ", progname);
1691 (void)vfprintf(err_file, fmt, ap);
1692 va_end(ap);
1693 (void)fprintf(err_file, "\n");
1694 (void)fflush(err_file);
1695 if (err_file == stderr)
1696 break;
1697 err_file = stderr;
1698 }
1699 }
1700
1701 /*-
1702 * Fatal --
1703 * Produce a Fatal error message. If jobs are running, waits for them
1704 * to finish.
1705 *
1706 * Results:
1707 * None
1708 *
1709 * Side Effects:
1710 * The program exits
1711 */
1712 /* VARARGS */
1713 void
1714 Fatal(const char *fmt, ...)
1715 {
1716 va_list ap;
1717
1718 va_start(ap, fmt);
1719 if (jobsRunning)
1720 Job_Wait();
1721
1722 (void)fflush(stdout);
1723 (void)vfprintf(stderr, fmt, ap);
1724 va_end(ap);
1725 (void)fprintf(stderr, "\n");
1726 (void)fflush(stderr);
1727
1728 PrintOnError(NULL, NULL);
1729
1730 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1731 Targ_PrintGraph(2);
1732 Trace_Log(MAKEERROR, 0);
1733 exit(2); /* Not 1 so -q can distinguish error */
1734 }
1735
1736 /*
1737 * Punt --
1738 * Major exception once jobs are being created. Kills all jobs, prints
1739 * a message and exits.
1740 *
1741 * Results:
1742 * None
1743 *
1744 * Side Effects:
1745 * All children are killed indiscriminately and the program Lib_Exits
1746 */
1747 /* VARARGS */
1748 void
1749 Punt(const char *fmt, ...)
1750 {
1751 va_list ap;
1752
1753 va_start(ap, fmt);
1754 (void)fflush(stdout);
1755 (void)fprintf(stderr, "%s: ", progname);
1756 (void)vfprintf(stderr, fmt, ap);
1757 va_end(ap);
1758 (void)fprintf(stderr, "\n");
1759 (void)fflush(stderr);
1760
1761 PrintOnError(NULL, NULL);
1762
1763 DieHorribly();
1764 }
1765
1766 /*-
1767 * DieHorribly --
1768 * Exit without giving a message.
1769 *
1770 * Results:
1771 * None
1772 *
1773 * Side Effects:
1774 * A big one...
1775 */
1776 void
1777 DieHorribly(void)
1778 {
1779 if (jobsRunning)
1780 Job_AbortAll();
1781 if (DEBUG(GRAPH2))
1782 Targ_PrintGraph(2);
1783 Trace_Log(MAKEERROR, 0);
1784 exit(2); /* Not 1, so -q can distinguish error */
1785 }
1786
1787 /*
1788 * Finish --
1789 * Called when aborting due to errors in child shell to signal
1790 * abnormal exit.
1791 *
1792 * Results:
1793 * None
1794 *
1795 * Side Effects:
1796 * The program exits
1797 */
1798 void
1799 Finish(int errors)
1800 /* number of errors encountered in Make_Make */
1801 {
1802 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1803 }
1804
1805 /*
1806 * eunlink --
1807 * Remove a file carefully, avoiding directories.
1808 */
1809 int
1810 eunlink(const char *file)
1811 {
1812 struct stat st;
1813
1814 if (lstat(file, &st) == -1)
1815 return -1;
1816
1817 if (S_ISDIR(st.st_mode)) {
1818 errno = EISDIR;
1819 return -1;
1820 }
1821 return unlink(file);
1822 }
1823
1824 /*
1825 * execError --
1826 * Print why exec failed, avoiding stdio.
1827 */
1828 void
1829 execError(const char *af, const char *av)
1830 {
1831 #ifdef USE_IOVEC
1832 int i = 0;
1833 struct iovec iov[8];
1834 #define IOADD(s) \
1835 (void)(iov[i].iov_base = UNCONST(s), \
1836 iov[i].iov_len = strlen(iov[i].iov_base), \
1837 i++)
1838 #else
1839 #define IOADD(void)write(2, s, strlen(s))
1840 #endif
1841
1842 IOADD(progname);
1843 IOADD(": ");
1844 IOADD(af);
1845 IOADD("(");
1846 IOADD(av);
1847 IOADD(") failed (");
1848 IOADD(strerror(errno));
1849 IOADD(")\n");
1850
1851 #ifdef USE_IOVEC
1852 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1853 continue;
1854 #endif
1855 }
1856
1857 /*
1858 * usage --
1859 * exit with usage message
1860 */
1861 static void
1862 usage(void)
1863 {
1864 char *p;
1865 if ((p = strchr(progname, '[')) != NULL)
1866 *p = '\0';
1867
1868 (void)fprintf(stderr,
1869 "usage: %s [-BeikNnqrstWwX] \n\
1870 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1871 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1872 [-V variable] [variable=value] [target ...]\n", progname);
1873 exit(2);
1874 }
1875
1876
1877 /*
1878 * realpath(3) can get expensive, cache results...
1879 */
1880 char *
1881 cached_realpath(const char *pathname, char *resolved)
1882 {
1883 static GNode *cache;
1884 char *rp, *cp;
1885
1886 if (!pathname || !pathname[0])
1887 return NULL;
1888
1889 if (!cache) {
1890 cache = Targ_NewGN("Realpath");
1891 #ifndef DEBUG_REALPATH_CACHE
1892 cache->flags = INTERNAL;
1893 #endif
1894 }
1895 if (resolved == NULL && strcmp(pathname, ".OBJDIR") == 0) {
1896 /* purge any relative paths */
1897 Hash_Entry *he, *nhe;
1898 Hash_Search hs;
1899
1900 he = Hash_EnumFirst(&cache->context, &hs);
1901 while (he) {
1902 nhe = Hash_EnumNext(&hs);
1903 if (he->name[0] != '/') {
1904 if (DEBUG(DIR))
1905 fprintf(stderr, "cached_realpath: purging %s\n", he->name);
1906 Hash_DeleteEntry(&cache->context, he);
1907 }
1908 he = nhe;
1909 }
1910 return NULL;
1911 }
1912 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
1913 /* a hit */
1914 strncpy(resolved, rp, MAXPATHLEN);
1915 resolved[MAXPATHLEN - 1] = '\0';
1916 } else if ((rp = realpath(pathname, resolved)) != NULL) {
1917 Var_Set(pathname, rp, cache, 0);
1918 } /* else should we negative-cache? */
1919
1920 free(cp);
1921 return rp ? resolved : NULL;
1922 }
1923
1924 int
1925 PrintAddr(void *a, void *b)
1926 {
1927 printf("%lx ", (unsigned long) a);
1928 return b ? 0 : 0;
1929 }
1930
1931
1932 static int
1933 addErrorCMD(void *cmdp, void *gnp)
1934 {
1935 if (cmdp == NULL)
1936 return 1; /* stop */
1937 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
1938 return 0;
1939 }
1940
1941 void
1942 PrintOnError(GNode *gn, const char *s)
1943 {
1944 static GNode *en = NULL;
1945 char tmp[64];
1946 char *cp;
1947
1948 if (s)
1949 printf("%s", s);
1950
1951 printf("\n%s: stopped in %s\n", progname, curdir);
1952
1953 if (en)
1954 return; /* we've been here! */
1955 if (gn) {
1956 /*
1957 * We can print this even if there is no .ERROR target.
1958 */
1959 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1960 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
1961 Lst_ForEach(gn->commands, addErrorCMD, gn);
1962 }
1963 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1964 sizeof(tmp) - 1);
1965 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
1966 if (cp) {
1967 if (*cp)
1968 printf("%s", cp);
1969 free(cp);
1970 }
1971 fflush(stdout);
1972
1973 /*
1974 * Finally, see if there is a .ERROR target, and run it if so.
1975 */
1976 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1977 if (en) {
1978 en->type |= OP_SPECIAL;
1979 Compat_Make(en, en);
1980 }
1981 }
1982
1983 void
1984 Main_ExportMAKEFLAGS(Boolean first)
1985 {
1986 static int once = 1;
1987 char tmp[64];
1988 char *s;
1989
1990 if (once != first)
1991 return;
1992 once = 0;
1993
1994 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1995 sizeof(tmp));
1996 s = Var_Subst(NULL, tmp, VAR_CMD, VARF_WANTRES);
1997 if (s && *s) {
1998 #ifdef POSIX
1999 setenv("MAKEFLAGS", s, 1);
2000 #else
2001 setenv("MAKE", s, 1);
2002 #endif
2003 }
2004 }
2005
2006 char *
2007 getTmpdir(void)
2008 {
2009 static char *tmpdir = NULL;
2010
2011 if (!tmpdir) {
2012 struct stat st;
2013
2014 /*
2015 * Honor $TMPDIR but only if it is valid.
2016 * Ensure it ends with /.
2017 */
2018 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2019 VARF_WANTRES);
2020 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2021 free(tmpdir);
2022 tmpdir = bmake_strdup(_PATH_TMP);
2023 }
2024 }
2025 return tmpdir;
2026 }
2027
2028 /*
2029 * Create and open a temp file using "pattern".
2030 * If "fnamep" is provided set it to a copy of the filename created.
2031 * Otherwise unlink the file once open.
2032 */
2033 int
2034 mkTempFile(const char *pattern, char **fnamep)
2035 {
2036 static char *tmpdir = NULL;
2037 char tfile[MAXPATHLEN];
2038 int fd;
2039
2040 if (!pattern)
2041 pattern = TMPPAT;
2042 if (!tmpdir)
2043 tmpdir = getTmpdir();
2044 if (pattern[0] == '/') {
2045 snprintf(tfile, sizeof(tfile), "%s", pattern);
2046 } else {
2047 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2048 }
2049 if ((fd = mkstemp(tfile)) < 0)
2050 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2051 if (fnamep) {
2052 *fnamep = bmake_strdup(tfile);
2053 } else {
2054 unlink(tfile); /* we just want the descriptor */
2055 }
2056 return fd;
2057 }
2058
2059 /*
2060 * Convert a string representation of a boolean.
2061 * Anything that looks like "No", "False", "Off", "0" etc,
2062 * is FALSE, otherwise TRUE.
2063 */
2064 Boolean
2065 s2Boolean(const char *s, Boolean bf)
2066 {
2067 if (s) {
2068 switch(*s) {
2069 case '\0': /* not set - the default wins */
2070 break;
2071 case '0':
2072 case 'F':
2073 case 'f':
2074 case 'N':
2075 case 'n':
2076 bf = FALSE;
2077 break;
2078 case 'O':
2079 case 'o':
2080 switch (s[1]) {
2081 case 'F':
2082 case 'f':
2083 bf = FALSE;
2084 break;
2085 default:
2086 bf = TRUE;
2087 break;
2088 }
2089 break;
2090 default:
2091 bf = TRUE;
2092 break;
2093 }
2094 }
2095 return (bf);
2096 }
2097
2098 /*
2099 * Return a Boolean based on setting of a knob.
2100 *
2101 * If the knob is not set, the supplied default is the return value.
2102 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2103 * is FALSE, otherwise TRUE.
2104 */
2105 Boolean
2106 getBoolean(const char *name, Boolean bf)
2107 {
2108 char tmp[64];
2109 char *cp;
2110
2111 if (snprintf(tmp, sizeof(tmp), "${%s:U:tl}", name) < (int)(sizeof(tmp))) {
2112 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2113
2114 if (cp) {
2115 bf = s2Boolean(cp, bf);
2116 free(cp);
2117 }
2118 }
2119 return (bf);
2120 }
2121