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