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