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