main.c revision 1.186 1 /* $NetBSD: main.c,v 1.186 2010/05/10 15:54:21 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.186 2010/05/10 15:54:21 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.186 2010/05/10 15:54:21 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)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 p1 = argv[0];
904 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
905 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
906 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
907 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
908 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
909 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
910
911 /*
912 * Set some other useful macros
913 */
914 {
915 char tmp[64];
916 const char *ep;
917
918 if (!(ep = getenv(MAKE_LEVEL))) {
919 ep = "0";
920 }
921 Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
922 snprintf(tmp, sizeof(tmp), "%u", myPid);
923 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
924 snprintf(tmp, sizeof(tmp), "%u", getppid());
925 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
926 }
927 Job_SetPrefix();
928
929 /*
930 * First snag any flags out of the MAKE environment variable.
931 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
932 * in a different format).
933 */
934 #ifdef POSIX
935 Main_ParseArgLine(getenv("MAKEFLAGS"));
936 #else
937 Main_ParseArgLine(getenv("MAKE"));
938 #endif
939
940 /*
941 * Find where we are (now).
942 * We take care of PWD for the automounter below...
943 */
944 if (getcwd(curdir, MAXPATHLEN) == NULL) {
945 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
946 exit(2);
947 }
948
949 MainParseArgs(argc, argv);
950
951 /*
952 * Verify that cwd is sane.
953 */
954 if (stat(curdir, &sa) == -1) {
955 (void)fprintf(stderr, "%s: %s: %s.\n",
956 progname, curdir, strerror(errno));
957 exit(2);
958 }
959
960 /*
961 * All this code is so that we know where we are when we start up
962 * on a different machine with pmake.
963 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
964 * since the value of curdir can vary depending on how we got
965 * here. Ie sitting at a shell prompt (shell that provides $PWD)
966 * or via subdir.mk in which case its likely a shell which does
967 * not provide it.
968 * So, to stop it breaking this case only, we ignore PWD if
969 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
970 */
971 if (!ignorePWD &&
972 (pwd = getenv("PWD")) != NULL &&
973 getenv("MAKEOBJDIRPREFIX") == NULL) {
974 const char *makeobjdir = getenv("MAKEOBJDIR");
975
976 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
977 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
978 sa.st_dev == sb.st_dev)
979 (void)strncpy(curdir, pwd, MAXPATHLEN);
980 }
981 }
982 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
983
984 /*
985 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
986 * MAKEOBJDIR is set in the environment, try only that value
987 * and fall back to .CURDIR if it does not exist.
988 *
989 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
990 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
991 * of these paths exist, just use .CURDIR.
992 */
993 Dir_Init(curdir);
994 (void)Main_SetObjdir(curdir);
995
996 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
997 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
998 (void)Main_SetObjdir(mdpath);
999 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1000 (void)Main_SetObjdir(path);
1001 } else {
1002 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1003 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1004 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1005 _PATH_OBJDIRPREFIX, curdir);
1006 (void)Main_SetObjdir(mdpath);
1007 }
1008 }
1009
1010 /*
1011 * Be compatible if user did not specify -j and did not explicitly
1012 * turned compatibility on
1013 */
1014 if (!compatMake && !forceJobs) {
1015 compatMake = TRUE;
1016 }
1017
1018 /*
1019 * Initialize archive, target and suffix modules in preparation for
1020 * parsing the makefile(s)
1021 */
1022 Arch_Init();
1023 Targ_Init();
1024 Suff_Init();
1025 Trace_Init(tracefile);
1026
1027 DEFAULT = NULL;
1028 (void)time(&now);
1029
1030 Trace_Log(MAKESTART, NULL);
1031
1032 /*
1033 * Set up the .TARGETS variable to contain the list of targets to be
1034 * created. If none specified, make the variable empty -- the parser
1035 * will fill the thing in with the default or .MAIN target.
1036 */
1037 if (!Lst_IsEmpty(create)) {
1038 LstNode ln;
1039
1040 for (ln = Lst_First(create); ln != NULL;
1041 ln = Lst_Succ(ln)) {
1042 char *name = (char *)Lst_Datum(ln);
1043
1044 Var_Append(".TARGETS", name, VAR_GLOBAL);
1045 }
1046 } else
1047 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1048
1049
1050 /*
1051 * If no user-supplied system path was given (through the -m option)
1052 * add the directories from the DEFSYSPATH (more than one may be given
1053 * as dir1:...:dirn) to the system include path.
1054 */
1055 if (syspath == NULL || *syspath == '\0')
1056 syspath = defsyspath;
1057 else
1058 syspath = bmake_strdup(syspath);
1059
1060 for (start = syspath; *start != '\0'; start = cp) {
1061 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1062 continue;
1063 if (*cp == ':') {
1064 *cp++ = '\0';
1065 }
1066 /* look for magic parent directory search string */
1067 if (strncmp(".../", start, 4) != 0) {
1068 (void)Dir_AddDir(defIncPath, start);
1069 } else {
1070 if (Dir_FindHereOrAbove(curdir, start+4,
1071 found_path, sizeof(found_path))) {
1072 (void)Dir_AddDir(defIncPath, found_path);
1073 }
1074 }
1075 }
1076 if (syspath != defsyspath)
1077 free(syspath);
1078
1079 /*
1080 * Read in the built-in rules first, followed by the specified
1081 * makefile, if it was (makefile != NULL), or the default
1082 * makefile and Makefile, in that order, if it wasn't.
1083 */
1084 if (!noBuiltins) {
1085 LstNode ln;
1086
1087 sysMkPath = Lst_Init(FALSE);
1088 Dir_Expand(_PATH_DEFSYSMK,
1089 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1090 sysMkPath);
1091 if (Lst_IsEmpty(sysMkPath))
1092 Fatal("%s: no system rules (%s).", progname,
1093 _PATH_DEFSYSMK);
1094 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1095 if (ln == NULL)
1096 Fatal("%s: cannot open %s.", progname,
1097 (char *)Lst_Datum(ln));
1098 }
1099
1100 if (!Lst_IsEmpty(makefiles)) {
1101 LstNode ln;
1102
1103 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1104 if (ln != NULL)
1105 Fatal("%s: cannot open %s.", progname,
1106 (char *)Lst_Datum(ln));
1107 } else {
1108 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1109 VAR_CMD, 0);
1110 if (p1) {
1111 (void)str2Lst_Append(makefiles, p1, NULL);
1112 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1113 free(p1);
1114 }
1115 }
1116
1117 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1118 if (!noBuiltins || !printVars) {
1119 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1120 VAR_CMD, 0);
1121 doing_depend = TRUE;
1122 (void)ReadMakefile(makeDependfile, NULL);
1123 doing_depend = FALSE;
1124 }
1125
1126 MakeMode(NULL);
1127
1128 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1129 if (p1)
1130 free(p1);
1131
1132 if (!compatMake)
1133 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1134 if (DEBUG(JOB))
1135 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1136 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1137
1138 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1139
1140 Check_Cwd_av(0, NULL, 0); /* initialize it */
1141
1142
1143 /*
1144 * For compatibility, look at the directories in the VPATH variable
1145 * and add them to the search path, if the variable is defined. The
1146 * variable's value is in the same format as the PATH envariable, i.e.
1147 * <directory>:<directory>:<directory>...
1148 */
1149 if (Var_Exists("VPATH", VAR_CMD)) {
1150 char *vpath, savec;
1151 /*
1152 * GCC stores string constants in read-only memory, but
1153 * Var_Subst will want to write this thing, so store it
1154 * in an array
1155 */
1156 static char VPATH[] = "${VPATH}";
1157
1158 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1159 path = vpath;
1160 do {
1161 /* skip to end of directory */
1162 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1163 continue;
1164 /* Save terminator character so know when to stop */
1165 savec = *cp;
1166 *cp = '\0';
1167 /* Add directory to search path */
1168 (void)Dir_AddDir(dirSearchPath, path);
1169 *cp = savec;
1170 path = cp + 1;
1171 } while (savec == ':');
1172 free(vpath);
1173 }
1174
1175 /*
1176 * Now that all search paths have been read for suffixes et al, it's
1177 * time to add the default search path to their lists...
1178 */
1179 Suff_DoPaths();
1180
1181 /*
1182 * Propagate attributes through :: dependency lists.
1183 */
1184 Targ_Propagate();
1185
1186 /* print the initial graph, if the user requested it */
1187 if (DEBUG(GRAPH1))
1188 Targ_PrintGraph(1);
1189
1190 /* print the values of any variables requested by the user */
1191 if (printVars) {
1192 LstNode ln;
1193
1194 for (ln = Lst_First(variables); ln != NULL;
1195 ln = Lst_Succ(ln)) {
1196 char *var = (char *)Lst_Datum(ln);
1197 char *value;
1198
1199 if (strchr(var, '$')) {
1200 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1201 } else {
1202 value = Var_Value(var, VAR_GLOBAL, &p1);
1203 }
1204 printf("%s\n", value ? value : "");
1205 if (p1)
1206 free(p1);
1207 }
1208 } else {
1209 /*
1210 * Have now read the entire graph and need to make a list of
1211 * targets to create. If none was given on the command line,
1212 * we consult the parsing module to find the main target(s)
1213 * to create.
1214 */
1215 if (Lst_IsEmpty(create))
1216 targs = Parse_MainName();
1217 else
1218 targs = Targ_FindList(create, TARG_CREATE);
1219
1220 if (!compatMake) {
1221 /*
1222 * Initialize job module before traversing the graph
1223 * now that any .BEGIN and .END targets have been read.
1224 * This is done only if the -q flag wasn't given
1225 * (to prevent the .BEGIN from being executed should
1226 * it exist).
1227 */
1228 if (!queryFlag) {
1229 Job_Init();
1230 jobsRunning = TRUE;
1231 }
1232
1233 /* Traverse the graph, checking on all the targets */
1234 outOfDate = Make_Run(targs);
1235 } else {
1236 /*
1237 * Compat_Init will take care of creating all the
1238 * targets as well as initializing the module.
1239 */
1240 Compat_Run(targs);
1241 }
1242 }
1243
1244 #ifdef CLEANUP
1245 Lst_Destroy(targs, NULL);
1246 Lst_Destroy(variables, NULL);
1247 Lst_Destroy(makefiles, NULL);
1248 Lst_Destroy(create, (FreeProc *)free);
1249 #endif
1250
1251 /* print the graph now it's been processed if the user requested it */
1252 if (DEBUG(GRAPH2))
1253 Targ_PrintGraph(2);
1254
1255 Trace_Log(MAKEEND, 0);
1256
1257 Suff_End();
1258 Targ_End();
1259 Arch_End();
1260 Var_End();
1261 Parse_End();
1262 Dir_End();
1263 Job_End();
1264 Trace_End();
1265
1266 return outOfDate ? 1 : 0;
1267 }
1268
1269 /*-
1270 * ReadMakefile --
1271 * Open and parse the given makefile.
1272 *
1273 * Results:
1274 * 0 if ok. -1 if couldn't open file.
1275 *
1276 * Side Effects:
1277 * lots
1278 */
1279 static int
1280 ReadMakefile(const void *p, const void *q __unused)
1281 {
1282 const char *fname = p; /* makefile to read */
1283 int fd;
1284 size_t len = MAXPATHLEN;
1285 char *name, *path = bmake_malloc(len);
1286
1287 if (!strcmp(fname, "-")) {
1288 Parse_File("(stdin)", dup(fileno(stdin)));
1289 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1290 } else {
1291 /* if we've chdir'd, rebuild the path name */
1292 if (strcmp(curdir, objdir) && *fname != '/') {
1293 size_t plen = strlen(curdir) + strlen(fname) + 2;
1294 if (len < plen)
1295 path = bmake_realloc(path, len = 2 * plen);
1296
1297 (void)snprintf(path, len, "%s/%s", curdir, fname);
1298 fd = open(path, O_RDONLY);
1299 if (fd != -1) {
1300 fname = path;
1301 goto found;
1302 }
1303
1304 /* If curdir failed, try objdir (ala .depend) */
1305 plen = strlen(objdir) + strlen(fname) + 2;
1306 if (len < plen)
1307 path = bmake_realloc(path, len = 2 * plen);
1308 (void)snprintf(path, len, "%s/%s", objdir, fname);
1309 fd = open(path, O_RDONLY);
1310 if (fd != -1) {
1311 fname = path;
1312 goto found;
1313 }
1314 } else {
1315 fd = open(fname, O_RDONLY);
1316 if (fd != -1)
1317 goto found;
1318 }
1319 /* look in -I and system include directories. */
1320 name = Dir_FindFile(fname, parseIncPath);
1321 if (!name)
1322 name = Dir_FindFile(fname,
1323 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1324 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1325 if (name)
1326 free(name);
1327 free(path);
1328 return(-1);
1329 }
1330 fname = name;
1331 /*
1332 * set the MAKEFILE variable desired by System V fans -- the
1333 * placement of the setting here means it gets set to the last
1334 * makefile specified, as it is set by SysV make.
1335 */
1336 found:
1337 if (!doing_depend)
1338 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1339 Parse_File(fname, fd);
1340 }
1341 free(path);
1342 return(0);
1343 }
1344
1345
1346 /*
1347 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1348 * in situations that would not arrise with ./obj (links or not).
1349 * This tends to break things like:
1350 *
1351 * build:
1352 * ${MAKE} includes
1353 *
1354 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1355 * opposed to an argument) in a command line and if so returns
1356 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1357 * the Makefile hold true.
1358 *
1359 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1360 *
1361 * The chdir() only happens in the child process, and does nothing if
1362 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1363 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1364 * do nothing - to ensure historic semantics can be retained.
1365 */
1366 static int Check_Cwd_Off = 0;
1367
1368 static char *
1369 Check_Cwd_av(int ac, char **av, int copy)
1370 {
1371 static char *make[4];
1372 static char *cur_dir = NULL;
1373 char **mp;
1374 char *cp;
1375 int is_cmd, next_cmd;
1376 int i;
1377 int n;
1378
1379 if (Check_Cwd_Off) {
1380 if (DEBUG(CWD))
1381 fprintf(debug_file, "check_cwd: check is off.\n");
1382 return NULL;
1383 }
1384
1385 if (make[0] == NULL) {
1386 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1387 Check_Cwd_Off = 1;
1388 if (DEBUG(CWD))
1389 fprintf(debug_file, "check_cwd: turning check off.\n");
1390 return NULL;
1391 }
1392
1393 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1394 if ((make[0] = strrchr(make[1], '/')) == NULL) {
1395 make[0] = make[1];
1396 make[1] = NULL;
1397 } else
1398 ++make[0];
1399 make[2] = NULL;
1400 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1401 }
1402 if (ac == 0 || av == NULL) {
1403 if (DEBUG(CWD))
1404 fprintf(debug_file, "check_cwd: empty command.\n");
1405 return NULL; /* initialization only */
1406 }
1407
1408 if (getenv("MAKEOBJDIR") == NULL &&
1409 getenv("MAKEOBJDIRPREFIX") == NULL) {
1410 if (DEBUG(CWD))
1411 fprintf(debug_file, "check_cwd: no obj dirs.\n");
1412 return NULL;
1413 }
1414
1415
1416 next_cmd = 1;
1417 for (i = 0; i < ac; ++i) {
1418 is_cmd = next_cmd;
1419
1420 n = strlen(av[i]);
1421 cp = &(av[i])[n - 1];
1422 if (strspn(av[i], "|&;") == (size_t)n) {
1423 next_cmd = 1;
1424 continue;
1425 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1426 next_cmd = 1;
1427 if (copy) {
1428 do {
1429 *cp-- = '\0';
1430 } while (*cp == ';' || *cp == '&' || *cp == '|' ||
1431 *cp == ')' || *cp == '}') ;
1432 } else {
1433 /*
1434 * XXX this should not happen.
1435 */
1436 fprintf(stderr, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1437 progname, av[i]);
1438 }
1439 } else
1440 next_cmd = 0;
1441
1442 cp = av[i];
1443 if (*cp == ';' || *cp == '&' || *cp == '|')
1444 is_cmd = 1;
1445
1446 if (DEBUG(CWD))
1447 fprintf(debug_file, "av[%d] == %s '%s'",
1448 i, (is_cmd) ? "cmd" : "arg", av[i]);
1449 if (is_cmd != 0) {
1450 if (*cp == '(' || *cp == '{' ||
1451 *cp == ';' || *cp == '&' || *cp == '|') {
1452 do {
1453 ++cp;
1454 } while (*cp == '(' || *cp == '{' ||
1455 *cp == ';' || *cp == '&' || *cp == '|');
1456 if (*cp == '\0') {
1457 next_cmd = 1;
1458 continue;
1459 }
1460 }
1461 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1462 if (DEBUG(CWD))
1463 fprintf(debug_file, " == cd, done.\n");
1464 return NULL;
1465 }
1466 for (mp = make; *mp != NULL; ++mp) {
1467 n = strlen(*mp);
1468 if (strcmp(cp, *mp) == 0) {
1469 if (DEBUG(CWD))
1470 fprintf(debug_file, " %s == '%s', chdir(%s)\n",
1471 cp, *mp, cur_dir);
1472 return cur_dir;
1473 }
1474 }
1475 }
1476 if (DEBUG(CWD))
1477 fprintf(debug_file, "\n");
1478 }
1479 return NULL;
1480 }
1481
1482 char *
1483 Check_Cwd_Cmd(const char *cmd)
1484 {
1485 char *cp, *bp;
1486 char **av;
1487 int ac;
1488
1489 if (Check_Cwd_Off)
1490 return NULL;
1491
1492 if (cmd) {
1493 av = brk_string(cmd, &ac, TRUE, &bp);
1494 if (DEBUG(CWD))
1495 fprintf(debug_file, "splitting: '%s' -> %d words\n",
1496 cmd, ac);
1497 } else {
1498 ac = 0;
1499 av = NULL;
1500 bp = NULL;
1501 }
1502 cp = Check_Cwd_av(ac, av, 1);
1503 if (bp)
1504 free(bp);
1505 if (av)
1506 free(av);
1507 return cp;
1508 }
1509
1510 void
1511 Check_Cwd(const char **argv)
1512 {
1513 char *cp;
1514 int ac;
1515
1516 if (Check_Cwd_Off)
1517 return;
1518
1519 for (ac = 0; argv[ac] != NULL; ++ac)
1520 /* NOTHING */;
1521 if (ac == 3 && *argv[1] == '-') {
1522 cp = Check_Cwd_Cmd(argv[2]);
1523 } else {
1524 cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1525 }
1526 if (cp) {
1527 chdir(cp);
1528 }
1529 }
1530
1531 /*-
1532 * Cmd_Exec --
1533 * Execute the command in cmd, and return the output of that command
1534 * in a string.
1535 *
1536 * Results:
1537 * A string containing the output of the command, or the empty string
1538 * If errnum is not NULL, it contains the reason for the command failure
1539 *
1540 * Side Effects:
1541 * The string must be freed by the caller.
1542 */
1543 char *
1544 Cmd_Exec(const char *cmd, const char **errnum)
1545 {
1546 const char *args[4]; /* Args for invoking the shell */
1547 int fds[2]; /* Pipe streams */
1548 int cpid; /* Child PID */
1549 int pid; /* PID from wait() */
1550 char *res; /* result */
1551 int status; /* command exit status */
1552 Buffer buf; /* buffer to store the result */
1553 char *cp;
1554 int cc;
1555
1556
1557 *errnum = NULL;
1558
1559 if (!shellName)
1560 Shell_Init();
1561 /*
1562 * Set up arguments for shell
1563 */
1564 args[0] = shellName;
1565 args[1] = "-c";
1566 args[2] = cmd;
1567 args[3] = NULL;
1568
1569 /*
1570 * Open a pipe for fetching its output
1571 */
1572 if (pipe(fds) == -1) {
1573 *errnum = "Couldn't create pipe for \"%s\"";
1574 goto bad;
1575 }
1576
1577 /*
1578 * Fork
1579 */
1580 switch (cpid = vFork()) {
1581 case 0:
1582 /*
1583 * Close input side of pipe
1584 */
1585 (void)close(fds[0]);
1586
1587 /*
1588 * Duplicate the output stream to the shell's output, then
1589 * shut the extra thing down. Note we don't fetch the error
1590 * stream...why not? Why?
1591 */
1592 (void)dup2(fds[1], 1);
1593 (void)close(fds[1]);
1594
1595 Var_ExportVars();
1596
1597 (void)execv(shellPath, UNCONST(args));
1598 _exit(1);
1599 /*NOTREACHED*/
1600
1601 case -1:
1602 *errnum = "Couldn't exec \"%s\"";
1603 goto bad;
1604
1605 default:
1606 /*
1607 * No need for the writing half
1608 */
1609 (void)close(fds[1]);
1610
1611 Buf_Init(&buf, 0);
1612
1613 do {
1614 char result[BUFSIZ];
1615 cc = read(fds[0], result, sizeof(result));
1616 if (cc > 0)
1617 Buf_AddBytes(&buf, cc, result);
1618 }
1619 while (cc > 0 || (cc == -1 && errno == EINTR));
1620
1621 /*
1622 * Close the input side of the pipe.
1623 */
1624 (void)close(fds[0]);
1625
1626 /*
1627 * Wait for the process to exit.
1628 */
1629 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0))
1630 continue;
1631
1632 cc = Buf_Size(&buf);
1633 res = Buf_Destroy(&buf, FALSE);
1634
1635 if (cc == 0)
1636 *errnum = "Couldn't read shell's output for \"%s\"";
1637
1638 if (WIFSIGNALED(status))
1639 *errnum = "\"%s\" exited on a signal";
1640 else if (WEXITSTATUS(status) != 0)
1641 *errnum = "\"%s\" returned non-zero status";
1642
1643 /*
1644 * Null-terminate the result, convert newlines to spaces and
1645 * install it in the variable.
1646 */
1647 res[cc] = '\0';
1648 cp = &res[cc];
1649
1650 if (cc > 0 && *--cp == '\n') {
1651 /*
1652 * A final newline is just stripped
1653 */
1654 *cp-- = '\0';
1655 }
1656 while (cp >= res) {
1657 if (*cp == '\n') {
1658 *cp = ' ';
1659 }
1660 cp--;
1661 }
1662 break;
1663 }
1664 return res;
1665 bad:
1666 res = bmake_malloc(1);
1667 *res = '\0';
1668 return res;
1669 }
1670
1671 /*-
1672 * Error --
1673 * Print an error message given its format.
1674 *
1675 * Results:
1676 * None.
1677 *
1678 * Side Effects:
1679 * The message is printed.
1680 */
1681 /* VARARGS */
1682 void
1683 Error(const char *fmt, ...)
1684 {
1685 va_list ap;
1686 FILE *err_file;
1687
1688 err_file = debug_file;
1689 if (err_file == stdout)
1690 err_file = stderr;
1691 (void)fflush(stdout);
1692 for (;;) {
1693 va_start(ap, fmt);
1694 fprintf(err_file, "%s: ", progname);
1695 (void)vfprintf(err_file, fmt, ap);
1696 va_end(ap);
1697 (void)fprintf(err_file, "\n");
1698 (void)fflush(err_file);
1699 if (err_file == stderr)
1700 break;
1701 err_file = stderr;
1702 }
1703 }
1704
1705 /*-
1706 * Fatal --
1707 * Produce a Fatal error message. If jobs are running, waits for them
1708 * to finish.
1709 *
1710 * Results:
1711 * None
1712 *
1713 * Side Effects:
1714 * The program exits
1715 */
1716 /* VARARGS */
1717 void
1718 Fatal(const char *fmt, ...)
1719 {
1720 va_list ap;
1721
1722 va_start(ap, fmt);
1723 if (jobsRunning)
1724 Job_Wait();
1725
1726 (void)fflush(stdout);
1727 (void)vfprintf(stderr, fmt, ap);
1728 va_end(ap);
1729 (void)fprintf(stderr, "\n");
1730 (void)fflush(stderr);
1731
1732 PrintOnError(NULL, NULL);
1733
1734 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1735 Targ_PrintGraph(2);
1736 Trace_Log(MAKEERROR, 0);
1737 exit(2); /* Not 1 so -q can distinguish error */
1738 }
1739
1740 /*
1741 * Punt --
1742 * Major exception once jobs are being created. Kills all jobs, prints
1743 * a message and exits.
1744 *
1745 * Results:
1746 * None
1747 *
1748 * Side Effects:
1749 * All children are killed indiscriminately and the program Lib_Exits
1750 */
1751 /* VARARGS */
1752 void
1753 Punt(const char *fmt, ...)
1754 {
1755 va_list ap;
1756
1757 va_start(ap, fmt);
1758 (void)fflush(stdout);
1759 (void)fprintf(stderr, "%s: ", progname);
1760 (void)vfprintf(stderr, fmt, ap);
1761 va_end(ap);
1762 (void)fprintf(stderr, "\n");
1763 (void)fflush(stderr);
1764
1765 PrintOnError(NULL, NULL);
1766
1767 DieHorribly();
1768 }
1769
1770 /*-
1771 * DieHorribly --
1772 * Exit without giving a message.
1773 *
1774 * Results:
1775 * None
1776 *
1777 * Side Effects:
1778 * A big one...
1779 */
1780 void
1781 DieHorribly(void)
1782 {
1783 if (jobsRunning)
1784 Job_AbortAll();
1785 if (DEBUG(GRAPH2))
1786 Targ_PrintGraph(2);
1787 Trace_Log(MAKEERROR, 0);
1788 exit(2); /* Not 1, so -q can distinguish error */
1789 }
1790
1791 /*
1792 * Finish --
1793 * Called when aborting due to errors in child shell to signal
1794 * abnormal exit.
1795 *
1796 * Results:
1797 * None
1798 *
1799 * Side Effects:
1800 * The program exits
1801 */
1802 void
1803 Finish(int errors)
1804 /* number of errors encountered in Make_Make */
1805 {
1806 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1807 }
1808
1809 /*
1810 * enunlink --
1811 * Remove a file carefully, avoiding directories.
1812 */
1813 int
1814 eunlink(const char *file)
1815 {
1816 struct stat st;
1817
1818 if (lstat(file, &st) == -1)
1819 return -1;
1820
1821 if (S_ISDIR(st.st_mode)) {
1822 errno = EISDIR;
1823 return -1;
1824 }
1825 return unlink(file);
1826 }
1827
1828 /*
1829 * execError --
1830 * Print why exec failed, avoiding stdio.
1831 */
1832 void
1833 execError(const char *af, const char *av)
1834 {
1835 #ifdef USE_IOVEC
1836 int i = 0;
1837 struct iovec iov[8];
1838 #define IOADD(s) \
1839 (void)(iov[i].iov_base = UNCONST(s), \
1840 iov[i].iov_len = strlen(iov[i].iov_base), \
1841 i++)
1842 #else
1843 #define IOADD(void)write(2, s, strlen(s))
1844 #endif
1845
1846 IOADD(progname);
1847 IOADD(": ");
1848 IOADD(af);
1849 IOADD("(");
1850 IOADD(av);
1851 IOADD(") failed (");
1852 IOADD(strerror(errno));
1853 IOADD(")\n");
1854
1855 #ifdef USE_IOVEC
1856 (void)writev(2, iov, 8);
1857 #endif
1858 }
1859
1860 /*
1861 * usage --
1862 * exit with usage message
1863 */
1864 static void
1865 usage(void)
1866 {
1867 (void)fprintf(stderr,
1868 "usage: %s [-BeikNnqrstWX] \n\
1869 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1870 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1871 [-V variable] [variable=value] [target ...]\n", progname);
1872 exit(2);
1873 }
1874
1875
1876 int
1877 PrintAddr(void *a, void *b)
1878 {
1879 printf("%lx ", (unsigned long) a);
1880 return b ? 0 : 0;
1881 }
1882
1883
1884
1885 void
1886 PrintOnError(GNode *gn, const char *s)
1887 {
1888 static GNode *en = NULL;
1889 char tmp[64];
1890 char *cp;
1891
1892 if (s)
1893 printf("%s", s);
1894
1895 printf("\n%s: stopped in %s\n", progname, curdir);
1896
1897 if (en)
1898 return; /* we've been here! */
1899 if (gn) {
1900 /*
1901 * We can print this even if there is no .ERROR target.
1902 */
1903 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
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 * Finally, see if there is a .ERROR target, and run it if so.
1915 */
1916 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1917 if (en) {
1918 en->type |= OP_SPECIAL;
1919 Compat_Make(en, en);
1920 }
1921 }
1922
1923 void
1924 Main_ExportMAKEFLAGS(Boolean first)
1925 {
1926 static int once = 1;
1927 char tmp[64];
1928 char *s;
1929
1930 if (once != first)
1931 return;
1932 once = 0;
1933
1934 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1935 sizeof(tmp));
1936 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1937 if (s && *s) {
1938 #ifdef POSIX
1939 setenv("MAKEFLAGS", s, 1);
1940 #else
1941 setenv("MAKE", s, 1);
1942 #endif
1943 }
1944 }
1945
1946 /*
1947 * Create and open a temp file using "pattern".
1948 * If "fnamep" is provided set it to a copy of the filename created.
1949 * Otherwise unlink the file once open.
1950 */
1951 int
1952 mkTempFile(const char *pattern, char **fnamep)
1953 {
1954 static char *tmpdir = NULL;
1955 char tfile[MAXPATHLEN];
1956 int fd;
1957
1958 if (!pattern)
1959 pattern = TMPPAT;
1960
1961 if (!tmpdir) {
1962 struct stat st;
1963
1964 /*
1965 * Honor $TMPDIR but only if it is valid.
1966 * Ensure it ends with /.
1967 */
1968 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1969 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1970 free(tmpdir);
1971 tmpdir = bmake_strdup(_PATH_TMP);
1972 }
1973 }
1974 if (pattern[0] == '/') {
1975 snprintf(tfile, sizeof(tfile), "%s", pattern);
1976 } else {
1977 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1978 }
1979 if ((fd = mkstemp(tfile)) < 0)
1980 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1981 if (fnamep) {
1982 *fnamep = bmake_strdup(tfile);
1983 } else {
1984 unlink(tfile); /* we just want the descriptor */
1985 }
1986 return fd;
1987 }
1988