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