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