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