main.c revision 1.170 1 /* $NetBSD: main.c,v 1.170 2009/03/24 13:53:21 perry 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.170 2009/03/24 13:53:21 perry 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.170 2009/03/24 13:53:21 perry 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", progname, dir);
680 if (len > 0)
681 (void)write(STDERR_FILENO, str, (size_t)len);
682 }
683 #endif
684
685 /*-
686 * main --
687 * The main function, for obvious reasons. Initializes variables
688 * and a few modules, then parses the arguments give it in the
689 * environment and on the command line. Reads the system makefile
690 * followed by either Makefile, makefile or the file given by the
691 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
692 * flags it has received by then uses either the Make or the Compat
693 * module to create the initial list of targets.
694 *
695 * Results:
696 * If -q was given, exits -1 if anything was out-of-date. Else it exits
697 * 0.
698 *
699 * Side Effects:
700 * The program exits when done. Targets are created. etc. etc. etc.
701 */
702 int
703 main(int argc, char **argv)
704 {
705 Lst targs; /* target nodes to create -- passed to Make_Init */
706 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
707 struct stat sb, sa;
708 char *p1, *path, *pwd;
709 char mdpath[MAXPATHLEN];
710 char *machine = getenv("MACHINE");
711 const char *machine_arch = getenv("MACHINE_ARCH");
712 char *syspath = getenv("MAKESYSPATH");
713 Lst sysMkPath; /* Path of sys.mk */
714 char *cp = NULL, *start;
715 /* avoid faults on read-only strings */
716 static char defsyspath[] = _PATH_DEFSYSPATH;
717 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
718 struct timeval rightnow; /* to initialize random seed */
719 #ifdef MAKE_NATIVE
720 struct utsname utsname;
721 #endif
722
723 /* default to writing debug to stderr */
724 debug_file = stderr;
725
726 #ifdef SIGINFO
727 (void)signal(SIGINFO, siginfo);
728 #endif
729 /*
730 * Set the seed to produce a different random sequence
731 * on each program execution.
732 */
733 gettimeofday(&rightnow, NULL);
734 srandom(rightnow.tv_sec + rightnow.tv_usec);
735
736 if ((progname = strrchr(argv[0], '/')) != NULL)
737 progname++;
738 else
739 progname = argv[0];
740 #ifdef RLIMIT_NOFILE
741 /*
742 * get rid of resource limit on file descriptors
743 */
744 {
745 struct rlimit rl;
746 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
747 rl.rlim_cur != rl.rlim_max) {
748 rl.rlim_cur = rl.rlim_max;
749 (void)setrlimit(RLIMIT_NOFILE, &rl);
750 }
751 }
752 #endif
753 /*
754 * Find where we are and take care of PWD for the automounter...
755 * All this code is so that we know where we are when we start up
756 * on a different machine with pmake.
757 */
758 if (getcwd(curdir, MAXPATHLEN) == NULL) {
759 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
760 exit(2);
761 }
762
763 if (stat(curdir, &sa) == -1) {
764 (void)fprintf(stderr, "%s: %s: %s.\n",
765 progname, curdir, strerror(errno));
766 exit(2);
767 }
768
769 /*
770 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
771 * since the value of curdir can very depending on how we got
772 * here. Ie sitting at a shell prompt (shell that provides $PWD)
773 * or via subdir.mk in which case its likely a shell which does
774 * not provide it.
775 * So, to stop it breaking this case only, we ignore PWD if
776 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
777 */
778 if ((pwd = getenv("PWD")) != NULL && getenv("MAKEOBJDIRPREFIX") == NULL) {
779 const char *makeobjdir = getenv("MAKEOBJDIR");
780
781 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
782 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
783 sa.st_dev == sb.st_dev)
784 (void)strncpy(curdir, pwd, MAXPATHLEN);
785 }
786 }
787
788 /*
789 * Get the name of this type of MACHINE from utsname
790 * so we can share an executable for similar machines.
791 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
792 *
793 * Note that both MACHINE and MACHINE_ARCH are decided at
794 * run-time.
795 */
796 if (!machine) {
797 #ifdef MAKE_NATIVE
798 if (uname(&utsname) == -1) {
799 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
800 strerror(errno));
801 exit(2);
802 }
803 machine = utsname.machine;
804 #else
805 #ifdef MAKE_MACHINE
806 machine = MAKE_MACHINE;
807 #else
808 machine = "unknown";
809 #endif
810 #endif
811 }
812
813 if (!machine_arch) {
814 #ifndef MACHINE_ARCH
815 #ifdef MAKE_MACHINE_ARCH
816 machine_arch = MAKE_MACHINE_ARCH;
817 #else
818 machine_arch = "unknown";
819 #endif
820 #else
821 machine_arch = MACHINE_ARCH;
822 #endif
823 }
824
825 /*
826 * Just in case MAKEOBJDIR wants us to do something tricky.
827 */
828 Var_Init(); /* Initialize the lists of variables for
829 * parsing arguments */
830 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
831 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
832 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
833 #ifdef MAKE_VERSION
834 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
835 #endif
836 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
837
838 /*
839 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
840 * MAKEOBJDIR is set in the environment, try only that value
841 * and fall back to .CURDIR if it does not exist.
842 *
843 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
844 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
845 * of these paths exist, just use .CURDIR.
846 */
847 Dir_Init(curdir);
848 (void)Main_SetObjdir(curdir);
849
850 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
851 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
852 (void)Main_SetObjdir(mdpath);
853 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
854 (void)Main_SetObjdir(path);
855 } else {
856 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
857 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
858 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
859 _PATH_OBJDIRPREFIX, curdir);
860 (void)Main_SetObjdir(mdpath);
861 }
862 }
863
864 create = Lst_Init(FALSE);
865 makefiles = Lst_Init(FALSE);
866 printVars = FALSE;
867 variables = Lst_Init(FALSE);
868 beSilent = FALSE; /* Print commands as executed */
869 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
870 noExecute = FALSE; /* Execute all commands */
871 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
872 keepgoing = FALSE; /* Stop on error */
873 allPrecious = FALSE; /* Remove targets when interrupted */
874 queryFlag = FALSE; /* This is not just a check-run */
875 noBuiltins = FALSE; /* Read the built-in rules */
876 touchFlag = FALSE; /* Actually update targets */
877 debug = 0; /* No debug verbosity, please. */
878 jobsRunning = FALSE;
879
880 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
881 maxJobTokens = maxJobs;
882 compatMake = FALSE; /* No compat mode */
883
884
885 /*
886 * Initialize the parsing, directory and variable modules to prepare
887 * for the reading of inclusion paths and variable settings on the
888 * command line
889 */
890
891 /*
892 * Initialize various variables.
893 * MAKE also gets this name, for compatibility
894 * .MAKEFLAGS gets set to the empty string just in case.
895 * MFLAGS also gets initialized empty, for compatibility.
896 */
897 Parse_Init();
898 Var_Set("MAKE", argv[0], VAR_GLOBAL, 0);
899 Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0);
900 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
901 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
902 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
903 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
904
905 /*
906 * Set some other useful macros
907 */
908 {
909 char tmp[64];
910
911 snprintf(tmp, sizeof(tmp), "%u", getpid());
912 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
913 snprintf(tmp, sizeof(tmp), "%u", getppid());
914 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
915 }
916 Job_SetPrefix();
917
918 /*
919 * First snag any flags out of the MAKE environment variable.
920 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
921 * in a different format).
922 */
923 #ifdef POSIX
924 Main_ParseArgLine(getenv("MAKEFLAGS"));
925 #else
926 Main_ParseArgLine(getenv("MAKE"));
927 #endif
928
929 MainParseArgs(argc, argv);
930
931 /*
932 * Be compatible if user did not specify -j and did not explicitly
933 * turned compatibility on
934 */
935 if (!compatMake && !forceJobs) {
936 compatMake = TRUE;
937 }
938
939 /*
940 * Initialize archive, target and suffix modules in preparation for
941 * parsing the makefile(s)
942 */
943 Arch_Init();
944 Targ_Init();
945 Suff_Init();
946 Trace_Init(tracefile);
947
948 DEFAULT = NULL;
949 (void)time(&now);
950
951 Trace_Log(MAKESTART, NULL);
952
953 /*
954 * Set up the .TARGETS variable to contain the list of targets to be
955 * created. If none specified, make the variable empty -- the parser
956 * will fill the thing in with the default or .MAIN target.
957 */
958 if (!Lst_IsEmpty(create)) {
959 LstNode ln;
960
961 for (ln = Lst_First(create); ln != NULL;
962 ln = Lst_Succ(ln)) {
963 char *name = (char *)Lst_Datum(ln);
964
965 Var_Append(".TARGETS", name, VAR_GLOBAL);
966 }
967 } else
968 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
969
970
971 /*
972 * If no user-supplied system path was given (through the -m option)
973 * add the directories from the DEFSYSPATH (more than one may be given
974 * as dir1:...:dirn) to the system include path.
975 */
976 if (syspath == NULL || *syspath == '\0')
977 syspath = defsyspath;
978 else
979 syspath = bmake_strdup(syspath);
980
981 for (start = syspath; *start != '\0'; start = cp) {
982 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
983 continue;
984 if (*cp == ':') {
985 *cp++ = '\0';
986 }
987 /* look for magic parent directory search string */
988 if (strncmp(".../", start, 4) != 0) {
989 (void)Dir_AddDir(defIncPath, start);
990 } else {
991 if (Dir_FindHereOrAbove(curdir, start+4,
992 found_path, sizeof(found_path))) {
993 (void)Dir_AddDir(defIncPath, found_path);
994 }
995 }
996 }
997 if (syspath != defsyspath)
998 free(syspath);
999
1000 /*
1001 * Read in the built-in rules first, followed by the specified
1002 * makefile, if it was (makefile != NULL), or the default
1003 * makefile and Makefile, in that order, if it wasn't.
1004 */
1005 if (!noBuiltins) {
1006 LstNode ln;
1007
1008 sysMkPath = Lst_Init(FALSE);
1009 Dir_Expand(_PATH_DEFSYSMK,
1010 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1011 sysMkPath);
1012 if (Lst_IsEmpty(sysMkPath))
1013 Fatal("%s: no system rules (%s).", progname,
1014 _PATH_DEFSYSMK);
1015 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1016 if (ln == NULL)
1017 Fatal("%s: cannot open %s.", progname,
1018 (char *)Lst_Datum(ln));
1019 }
1020
1021 if (!Lst_IsEmpty(makefiles)) {
1022 LstNode ln;
1023
1024 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1025 if (ln != NULL)
1026 Fatal("%s: cannot open %s.", progname,
1027 (char *)Lst_Datum(ln));
1028 } else if (ReadMakefile("makefile", NULL) != 0)
1029 (void)ReadMakefile("Makefile", NULL);
1030
1031 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1032 if (!noBuiltins || !printVars) {
1033 doing_depend = TRUE;
1034 (void)ReadMakefile(".depend", NULL);
1035 doing_depend = FALSE;
1036 }
1037
1038 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1039 if (p1)
1040 free(p1);
1041
1042 if (!compatMake)
1043 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1044 if (DEBUG(JOB))
1045 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1046 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1047
1048 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1049
1050 Check_Cwd_av(0, NULL, 0); /* initialize it */
1051
1052
1053 /*
1054 * For compatibility, look at the directories in the VPATH variable
1055 * and add them to the search path, if the variable is defined. The
1056 * variable's value is in the same format as the PATH envariable, i.e.
1057 * <directory>:<directory>:<directory>...
1058 */
1059 if (Var_Exists("VPATH", VAR_CMD)) {
1060 char *vpath, savec;
1061 /*
1062 * GCC stores string constants in read-only memory, but
1063 * Var_Subst will want to write this thing, so store it
1064 * in an array
1065 */
1066 static char VPATH[] = "${VPATH}";
1067
1068 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1069 path = vpath;
1070 do {
1071 /* skip to end of directory */
1072 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1073 continue;
1074 /* Save terminator character so know when to stop */
1075 savec = *cp;
1076 *cp = '\0';
1077 /* Add directory to search path */
1078 (void)Dir_AddDir(dirSearchPath, path);
1079 *cp = savec;
1080 path = cp + 1;
1081 } while (savec == ':');
1082 free(vpath);
1083 }
1084
1085 /*
1086 * Now that all search paths have been read for suffixes et al, it's
1087 * time to add the default search path to their lists...
1088 */
1089 Suff_DoPaths();
1090
1091 /*
1092 * Propagate attributes through :: dependency lists.
1093 */
1094 Targ_Propagate();
1095
1096 /* print the initial graph, if the user requested it */
1097 if (DEBUG(GRAPH1))
1098 Targ_PrintGraph(1);
1099
1100 /* print the values of any variables requested by the user */
1101 if (printVars) {
1102 LstNode ln;
1103
1104 for (ln = Lst_First(variables); ln != NULL;
1105 ln = Lst_Succ(ln)) {
1106 char *var = (char *)Lst_Datum(ln);
1107 char *value;
1108
1109 if (strchr(var, '$')) {
1110 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1111 } else {
1112 value = Var_Value(var, VAR_GLOBAL, &p1);
1113 }
1114 printf("%s\n", value ? value : "");
1115 if (p1)
1116 free(p1);
1117 }
1118 } else {
1119 /*
1120 * Have now read the entire graph and need to make a list of
1121 * targets to create. If none was given on the command line,
1122 * we consult the parsing module to find the main target(s)
1123 * to create.
1124 */
1125 if (Lst_IsEmpty(create))
1126 targs = Parse_MainName();
1127 else
1128 targs = Targ_FindList(create, TARG_CREATE);
1129
1130 if (!compatMake) {
1131 /*
1132 * Initialize job module before traversing the graph
1133 * now that any .BEGIN and .END targets have been read.
1134 * This is done only if the -q flag wasn't given
1135 * (to prevent the .BEGIN from being executed should
1136 * it exist).
1137 */
1138 if (!queryFlag) {
1139 Job_Init();
1140 jobsRunning = TRUE;
1141 }
1142
1143 /* Traverse the graph, checking on all the targets */
1144 outOfDate = Make_Run(targs);
1145 } else {
1146 /*
1147 * Compat_Init will take care of creating all the
1148 * targets as well as initializing the module.
1149 */
1150 Compat_Run(targs);
1151 }
1152 }
1153
1154 #ifdef CLEANUP
1155 Lst_Destroy(targs, NULL);
1156 Lst_Destroy(variables, NULL);
1157 Lst_Destroy(makefiles, NULL);
1158 Lst_Destroy(create, (FreeProc *)free);
1159 #endif
1160
1161 /* print the graph now it's been processed if the user requested it */
1162 if (DEBUG(GRAPH2))
1163 Targ_PrintGraph(2);
1164
1165 Trace_Log(MAKEEND, 0);
1166
1167 Suff_End();
1168 Targ_End();
1169 Arch_End();
1170 Var_End();
1171 Parse_End();
1172 Dir_End();
1173 Job_End();
1174 Trace_End();
1175
1176 return outOfDate ? 1 : 0;
1177 }
1178
1179 /*-
1180 * ReadMakefile --
1181 * Open and parse the given makefile.
1182 *
1183 * Results:
1184 * 0 if ok. -1 if couldn't open file.
1185 *
1186 * Side Effects:
1187 * lots
1188 */
1189 static int
1190 ReadMakefile(const void *p, const void *q __unused)
1191 {
1192 const char *fname = p; /* makefile to read */
1193 int fd;
1194 size_t len = MAXPATHLEN;
1195 char *name, *path = bmake_malloc(len);
1196 int setMAKEFILE;
1197
1198 if (!strcmp(fname, "-")) {
1199 Parse_File("(stdin)", dup(fileno(stdin)));
1200 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1201 } else {
1202 setMAKEFILE = strcmp(fname, ".depend");
1203
1204 /* if we've chdir'd, rebuild the path name */
1205 if (strcmp(curdir, objdir) && *fname != '/') {
1206 size_t plen = strlen(curdir) + strlen(fname) + 2;
1207 if (len < plen)
1208 path = bmake_realloc(path, len = 2 * plen);
1209
1210 (void)snprintf(path, len, "%s/%s", curdir, fname);
1211 fd = open(path, O_RDONLY);
1212 if (fd != -1) {
1213 fname = path;
1214 goto found;
1215 }
1216
1217 /* If curdir failed, try objdir (ala .depend) */
1218 plen = strlen(objdir) + strlen(fname) + 2;
1219 if (len < plen)
1220 path = bmake_realloc(path, len = 2 * plen);
1221 (void)snprintf(path, len, "%s/%s", objdir, fname);
1222 fd = open(path, O_RDONLY);
1223 if (fd != -1) {
1224 fname = path;
1225 goto found;
1226 }
1227 } else {
1228 fd = open(fname, O_RDONLY);
1229 if (fd != -1)
1230 goto found;
1231 }
1232 /* look in -I and system include directories. */
1233 name = Dir_FindFile(fname, parseIncPath);
1234 if (!name)
1235 name = Dir_FindFile(fname,
1236 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1237 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1238 if (name)
1239 free(name);
1240 free(path);
1241 return(-1);
1242 }
1243 fname = name;
1244 /*
1245 * set the MAKEFILE variable desired by System V fans -- the
1246 * placement of the setting here means it gets set to the last
1247 * makefile specified, as it is set by SysV make.
1248 */
1249 found:
1250 if (setMAKEFILE)
1251 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1252 Parse_File(fname, fd);
1253 }
1254 free(path);
1255 return(0);
1256 }
1257
1258
1259 /*
1260 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1261 * in situations that would not arrise with ./obj (links or not).
1262 * This tends to break things like:
1263 *
1264 * build:
1265 * ${MAKE} includes
1266 *
1267 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1268 * opposed to an argument) in a command line and if so returns
1269 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1270 * the Makefile hold true.
1271 *
1272 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1273 *
1274 * The chdir() only happens in the child process, and does nothing if
1275 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1276 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1277 * do nothing - to ensure historic semantics can be retained.
1278 */
1279 static int Check_Cwd_Off = 0;
1280
1281 static char *
1282 Check_Cwd_av(int ac, char **av, int copy)
1283 {
1284 static char *make[4];
1285 static char *cur_dir = NULL;
1286 char **mp;
1287 char *cp;
1288 int is_cmd, next_cmd;
1289 int i;
1290 int n;
1291
1292 if (Check_Cwd_Off) {
1293 if (DEBUG(CWD))
1294 fprintf(debug_file, "check_cwd: check is off.\n");
1295 return NULL;
1296 }
1297
1298 if (make[0] == NULL) {
1299 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1300 Check_Cwd_Off = 1;
1301 if (DEBUG(CWD))
1302 fprintf(debug_file, "check_cwd: turning check off.\n");
1303 return NULL;
1304 }
1305
1306 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1307 if ((make[0] = strrchr(make[1], '/')) == NULL) {
1308 make[0] = make[1];
1309 make[1] = NULL;
1310 } else
1311 ++make[0];
1312 make[2] = NULL;
1313 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1314 }
1315 if (ac == 0 || av == NULL) {
1316 if (DEBUG(CWD))
1317 fprintf(debug_file, "check_cwd: empty command.\n");
1318 return NULL; /* initialization only */
1319 }
1320
1321 if (getenv("MAKEOBJDIR") == NULL &&
1322 getenv("MAKEOBJDIRPREFIX") == NULL) {
1323 if (DEBUG(CWD))
1324 fprintf(debug_file, "check_cwd: no obj dirs.\n");
1325 return NULL;
1326 }
1327
1328
1329 next_cmd = 1;
1330 for (i = 0; i < ac; ++i) {
1331 is_cmd = next_cmd;
1332
1333 n = strlen(av[i]);
1334 cp = &(av[i])[n - 1];
1335 if (strspn(av[i], "|&;") == (size_t)n) {
1336 next_cmd = 1;
1337 continue;
1338 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1339 next_cmd = 1;
1340 if (copy) {
1341 do {
1342 *cp-- = '\0';
1343 } while (*cp == ';' || *cp == '&' || *cp == '|' ||
1344 *cp == ')' || *cp == '}') ;
1345 } else {
1346 /*
1347 * XXX this should not happen.
1348 */
1349 fprintf(stderr, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1350 progname, av[i]);
1351 }
1352 } else
1353 next_cmd = 0;
1354
1355 cp = av[i];
1356 if (*cp == ';' || *cp == '&' || *cp == '|')
1357 is_cmd = 1;
1358
1359 if (DEBUG(CWD))
1360 fprintf(debug_file, "av[%d] == %s '%s'",
1361 i, (is_cmd) ? "cmd" : "arg", av[i]);
1362 if (is_cmd != 0) {
1363 if (*cp == '(' || *cp == '{' ||
1364 *cp == ';' || *cp == '&' || *cp == '|') {
1365 do {
1366 ++cp;
1367 } while (*cp == '(' || *cp == '{' ||
1368 *cp == ';' || *cp == '&' || *cp == '|');
1369 if (*cp == '\0') {
1370 next_cmd = 1;
1371 continue;
1372 }
1373 }
1374 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1375 if (DEBUG(CWD))
1376 fprintf(debug_file, " == cd, done.\n");
1377 return NULL;
1378 }
1379 for (mp = make; *mp != NULL; ++mp) {
1380 n = strlen(*mp);
1381 if (strcmp(cp, *mp) == 0) {
1382 if (DEBUG(CWD))
1383 fprintf(debug_file, " %s == '%s', chdir(%s)\n",
1384 cp, *mp, cur_dir);
1385 return cur_dir;
1386 }
1387 }
1388 }
1389 if (DEBUG(CWD))
1390 fprintf(debug_file, "\n");
1391 }
1392 return NULL;
1393 }
1394
1395 char *
1396 Check_Cwd_Cmd(const char *cmd)
1397 {
1398 char *cp, *bp;
1399 char **av;
1400 int ac;
1401
1402 if (Check_Cwd_Off)
1403 return NULL;
1404
1405 if (cmd) {
1406 av = brk_string(cmd, &ac, TRUE, &bp);
1407 if (DEBUG(CWD))
1408 fprintf(debug_file, "splitting: '%s' -> %d words\n",
1409 cmd, ac);
1410 } else {
1411 ac = 0;
1412 av = NULL;
1413 bp = NULL;
1414 }
1415 cp = Check_Cwd_av(ac, av, 1);
1416 if (bp)
1417 free(bp);
1418 if (av)
1419 free(av);
1420 return cp;
1421 }
1422
1423 void
1424 Check_Cwd(const char **argv)
1425 {
1426 char *cp;
1427 int ac;
1428
1429 if (Check_Cwd_Off)
1430 return;
1431
1432 for (ac = 0; argv[ac] != NULL; ++ac)
1433 /* NOTHING */;
1434 if (ac == 3 && *argv[1] == '-') {
1435 cp = Check_Cwd_Cmd(argv[2]);
1436 } else {
1437 cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1438 }
1439 if (cp) {
1440 chdir(cp);
1441 }
1442 }
1443
1444 /*-
1445 * Cmd_Exec --
1446 * Execute the command in cmd, and return the output of that command
1447 * in a string.
1448 *
1449 * Results:
1450 * A string containing the output of the command, or the empty string
1451 * If errnum is not NULL, it contains the reason for the command failure
1452 *
1453 * Side Effects:
1454 * The string must be freed by the caller.
1455 */
1456 char *
1457 Cmd_Exec(const char *cmd, const char **errnum)
1458 {
1459 const char *args[4]; /* Args for invoking the shell */
1460 int fds[2]; /* Pipe streams */
1461 int cpid; /* Child PID */
1462 int pid; /* PID from wait() */
1463 char *res; /* result */
1464 int status; /* command exit status */
1465 Buffer buf; /* buffer to store the result */
1466 char *cp;
1467 int cc;
1468
1469
1470 *errnum = NULL;
1471
1472 if (!shellName)
1473 Shell_Init();
1474 /*
1475 * Set up arguments for shell
1476 */
1477 args[0] = shellName;
1478 args[1] = "-c";
1479 args[2] = cmd;
1480 args[3] = NULL;
1481
1482 /*
1483 * Open a pipe for fetching its output
1484 */
1485 if (pipe(fds) == -1) {
1486 *errnum = "Couldn't create pipe for \"%s\"";
1487 goto bad;
1488 }
1489
1490 /*
1491 * Fork
1492 */
1493 switch (cpid = vfork()) {
1494 case 0:
1495 /*
1496 * Close input side of pipe
1497 */
1498 (void)close(fds[0]);
1499
1500 /*
1501 * Duplicate the output stream to the shell's output, then
1502 * shut the extra thing down. Note we don't fetch the error
1503 * stream...why not? Why?
1504 */
1505 (void)dup2(fds[1], 1);
1506 (void)close(fds[1]);
1507
1508 Var_ExportVars();
1509
1510 (void)execv(shellPath, UNCONST(args));
1511 _exit(1);
1512 /*NOTREACHED*/
1513
1514 case -1:
1515 *errnum = "Couldn't exec \"%s\"";
1516 goto bad;
1517
1518 default:
1519 /*
1520 * No need for the writing half
1521 */
1522 (void)close(fds[1]);
1523
1524 Buf_Init(&buf, 0);
1525
1526 do {
1527 char result[BUFSIZ];
1528 cc = read(fds[0], result, sizeof(result));
1529 if (cc > 0)
1530 Buf_AddBytes(&buf, cc, result);
1531 }
1532 while (cc > 0 || (cc == -1 && errno == EINTR));
1533
1534 /*
1535 * Close the input side of the pipe.
1536 */
1537 (void)close(fds[0]);
1538
1539 /*
1540 * Wait for the process to exit.
1541 */
1542 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0))
1543 continue;
1544
1545 cc = Buf_Size(&buf);
1546 res = Buf_Destroy(&buf, FALSE);
1547
1548 if (cc == 0)
1549 *errnum = "Couldn't read shell's output for \"%s\"";
1550
1551 if (status)
1552 *errnum = "\"%s\" returned non-zero status";
1553
1554 /*
1555 * Null-terminate the result, convert newlines to spaces and
1556 * install it in the variable.
1557 */
1558 res[cc] = '\0';
1559 cp = &res[cc];
1560
1561 if (cc > 0 && *--cp == '\n') {
1562 /*
1563 * A final newline is just stripped
1564 */
1565 *cp-- = '\0';
1566 }
1567 while (cp >= res) {
1568 if (*cp == '\n') {
1569 *cp = ' ';
1570 }
1571 cp--;
1572 }
1573 break;
1574 }
1575 return res;
1576 bad:
1577 res = bmake_malloc(1);
1578 *res = '\0';
1579 return res;
1580 }
1581
1582 /*-
1583 * Error --
1584 * Print an error message given its format.
1585 *
1586 * Results:
1587 * None.
1588 *
1589 * Side Effects:
1590 * The message is printed.
1591 */
1592 /* VARARGS */
1593 void
1594 Error(const char *fmt, ...)
1595 {
1596 va_list ap;
1597 FILE *err_file;
1598
1599 err_file = debug_file;
1600 if (err_file == stdout)
1601 err_file = stderr;
1602 for (;;) {
1603 va_start(ap, fmt);
1604 fprintf(err_file, "%s: ", progname);
1605 (void)vfprintf(err_file, fmt, ap);
1606 va_end(ap);
1607 (void)fprintf(err_file, "\n");
1608 (void)fflush(err_file);
1609 if (err_file == stderr)
1610 break;
1611 err_file = stderr;
1612 }
1613 }
1614
1615 /*-
1616 * Fatal --
1617 * Produce a Fatal error message. If jobs are running, waits for them
1618 * to finish.
1619 *
1620 * Results:
1621 * None
1622 *
1623 * Side Effects:
1624 * The program exits
1625 */
1626 /* VARARGS */
1627 void
1628 Fatal(const char *fmt, ...)
1629 {
1630 va_list ap;
1631
1632 va_start(ap, fmt);
1633 if (jobsRunning)
1634 Job_Wait();
1635
1636 (void)vfprintf(stderr, fmt, ap);
1637 va_end(ap);
1638 (void)fprintf(stderr, "\n");
1639 (void)fflush(stderr);
1640
1641 PrintOnError(NULL);
1642
1643 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1644 Targ_PrintGraph(2);
1645 Trace_Log(MAKEERROR, 0);
1646 exit(2); /* Not 1 so -q can distinguish error */
1647 }
1648
1649 /*
1650 * Punt --
1651 * Major exception once jobs are being created. Kills all jobs, prints
1652 * a message and exits.
1653 *
1654 * Results:
1655 * None
1656 *
1657 * Side Effects:
1658 * All children are killed indiscriminately and the program Lib_Exits
1659 */
1660 /* VARARGS */
1661 void
1662 Punt(const char *fmt, ...)
1663 {
1664 va_list ap;
1665
1666 va_start(ap, fmt);
1667 (void)fprintf(stderr, "%s: ", progname);
1668 (void)vfprintf(stderr, fmt, ap);
1669 va_end(ap);
1670 (void)fprintf(stderr, "\n");
1671 (void)fflush(stderr);
1672
1673 PrintOnError(NULL);
1674
1675 DieHorribly();
1676 }
1677
1678 /*-
1679 * DieHorribly --
1680 * Exit without giving a message.
1681 *
1682 * Results:
1683 * None
1684 *
1685 * Side Effects:
1686 * A big one...
1687 */
1688 void
1689 DieHorribly(void)
1690 {
1691 if (jobsRunning)
1692 Job_AbortAll();
1693 if (DEBUG(GRAPH2))
1694 Targ_PrintGraph(2);
1695 Trace_Log(MAKEERROR, 0);
1696 exit(2); /* Not 1, so -q can distinguish error */
1697 }
1698
1699 /*
1700 * Finish --
1701 * Called when aborting due to errors in child shell to signal
1702 * abnormal exit.
1703 *
1704 * Results:
1705 * None
1706 *
1707 * Side Effects:
1708 * The program exits
1709 */
1710 void
1711 Finish(int errors)
1712 /* number of errors encountered in Make_Make */
1713 {
1714 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1715 }
1716
1717 /*
1718 * enunlink --
1719 * Remove a file carefully, avoiding directories.
1720 */
1721 int
1722 eunlink(const char *file)
1723 {
1724 struct stat st;
1725
1726 if (lstat(file, &st) == -1)
1727 return -1;
1728
1729 if (S_ISDIR(st.st_mode)) {
1730 errno = EISDIR;
1731 return -1;
1732 }
1733 return unlink(file);
1734 }
1735
1736 /*
1737 * execError --
1738 * Print why exec failed, avoiding stdio.
1739 */
1740 void
1741 execError(const char *af, const char *av)
1742 {
1743 #ifdef USE_IOVEC
1744 int i = 0;
1745 struct iovec iov[8];
1746 #define IOADD(s) \
1747 (void)(iov[i].iov_base = UNCONST(s), \
1748 iov[i].iov_len = strlen(iov[i].iov_base), \
1749 i++)
1750 #else
1751 #define IOADD(void)write(2, s, strlen(s))
1752 #endif
1753
1754 IOADD(progname);
1755 IOADD(": ");
1756 IOADD(af);
1757 IOADD("(");
1758 IOADD(av);
1759 IOADD(") failed (");
1760 IOADD(strerror(errno));
1761 IOADD(")\n");
1762
1763 #ifdef USE_IOVEC
1764 (void)writev(2, iov, 8);
1765 #endif
1766 }
1767
1768 /*
1769 * usage --
1770 * exit with usage message
1771 */
1772 static void
1773 usage(void)
1774 {
1775 (void)fprintf(stderr,
1776 "usage: %s [-BeikNnqrstWX] [-D variable] [-d flags] [-f makefile]\n\
1777 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1778 [-V variable] [variable=value] [target ...]\n", progname);
1779 exit(2);
1780 }
1781
1782
1783 int
1784 PrintAddr(void *a, void *b)
1785 {
1786 printf("%lx ", (unsigned long) a);
1787 return b ? 0 : 0;
1788 }
1789
1790
1791
1792 void
1793 PrintOnError(const char *s)
1794 {
1795 char tmp[64];
1796 char *cp;
1797
1798 if (s)
1799 printf("%s", s);
1800
1801 printf("\n%s: stopped in %s\n", progname, curdir);
1802 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1803 sizeof(tmp) - 1);
1804 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1805 if (cp) {
1806 if (*cp)
1807 printf("%s", cp);
1808 free(cp);
1809 }
1810 }
1811
1812 void
1813 Main_ExportMAKEFLAGS(Boolean first)
1814 {
1815 static int once = 1;
1816 char tmp[64];
1817 char *s;
1818
1819 if (once != first)
1820 return;
1821 once = 0;
1822
1823 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1824 sizeof(tmp));
1825 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1826 if (s && *s) {
1827 #ifdef POSIX
1828 setenv("MAKEFLAGS", s, 1);
1829 #else
1830 setenv("MAKE", s, 1);
1831 #endif
1832 }
1833 }
1834