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