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