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