main.c revision 1.110 1 /* $NetBSD: main.c,v 1.110 2005/06/23 02:31:31 lukem 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.110 2005/06/23 02:31:31 lukem 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.110 2005/06/23 02:31:31 lukem Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
88
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
93 *
94 * Utility functions defined in this file:
95 * Main_ParseArgLine Takes a line of arguments, breaks them and
96 * treats them as if they were given when first
97 * invoked. Used by the parse module to implement
98 * the .MFLAGS target.
99 *
100 * Error Print a tagged error message. The global
101 * MAKE variable must have been defined. This
102 * takes a format string and two optional
103 * arguments for it.
104 *
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
107 *
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
110 *
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
114 */
115
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/signal.h>
121 #include <sys/stat.h>
122 #ifdef MAKE_NATIVE
123 #include <sys/utsname.h>
124 #endif
125 #include <sys/wait.h>
126
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
133
134 #include "make.h"
135 #include "hash.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "pathnames.h"
139 #include "trace.h"
140
141 #ifdef USE_IOVEC
142 #include <sys/uio.h>
143 #endif
144
145 #ifndef DEFMAXLOCAL
146 #define DEFMAXLOCAL DEFMAXJOBS
147 #endif /* DEFMAXLOCAL */
148
149 Lst create; /* Targets to be made */
150 time_t now; /* Time at start of make */
151 GNode *DEFAULT; /* .DEFAULT node */
152 Boolean allPrecious; /* .PRECIOUS given on line by itself */
153
154 static Boolean noBuiltins; /* -r flag */
155 static Lst makefiles; /* ordered list of makefiles to read */
156 static Boolean printVars; /* print value of one or more vars */
157 static Lst variables; /* list of variables to print */
158 int maxJobs; /* -j argument */
159 static int maxLocal; /* -L argument */
160 Boolean compatMake; /* -B argument */
161 Boolean debug; /* -d flag */
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;
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 #ifdef REMOTE
217 # define OPTFLAGS "BD:I:J:L:NPST:V:WXd:ef:ij:km:nqrst"
218 #else
219 # define OPTFLAGS "BD:I:J:NPST:V:WXd:ef:ij:km:nqrst"
220 #endif
221 #undef optarg
222 #define optarg argvalue
223 /* Can't actually use getopt(3) because rescanning is not portable */
224
225 getopt_def = OPTFLAGS;
226 rearg:
227 inOption = FALSE;
228 optscan = NULL;
229 while(argc > 1) {
230 char *getopt_spec;
231 if(!inOption)
232 optscan = argv[1];
233 c = *optscan++;
234 arginc = 0;
235 if(inOption) {
236 if(c == '\0') {
237 ++argv;
238 --argc;
239 inOption = FALSE;
240 continue;
241 }
242 } else {
243 if (c != '-' || dashDash)
244 break;
245 inOption = TRUE;
246 c = *optscan++;
247 }
248 /* '-' found at some earlier point */
249 getopt_spec = strchr(getopt_def, c);
250 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
251 /* -<something> found, and <something> should have an arg */
252 inOption = FALSE;
253 arginc = 1;
254 argvalue = optscan;
255 if(*argvalue == '\0') {
256 if (argc < 3) {
257 (void)fprintf(stderr,
258 "%s: option requires "
259 "an argument -- %c\n",
260 progname, c);
261 usage();
262 }
263 argvalue = argv[2];
264 arginc = 2;
265 }
266 } else {
267 argvalue = NULL;
268 }
269 switch(c) {
270 case '\0':
271 arginc = 1;
272 inOption = FALSE;
273 break;
274 case 'B':
275 compatMake = TRUE;
276 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
277 break;
278 case 'D':
279 Var_Set(optarg, "1", VAR_GLOBAL, 0);
280 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
281 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
282 break;
283 case 'I':
284 Parse_AddIncludeDir(optarg);
285 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
286 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
287 break;
288 case 'J':
289 if (sscanf(optarg, "%d,%d", &job_pipe[0], &job_pipe[1]) != 2) {
290 /* backslash to avoid trigraph ??) */
291 (void)fprintf(stderr,
292 "%s: internal error -- J option malformed (%s?\?)\n",
293 progname, optarg);
294 usage();
295 }
296 if ((fcntl(job_pipe[0], F_GETFD, 0) < 0) ||
297 (fcntl(job_pipe[1], F_GETFD, 0) < 0)) {
298 #if 0
299 (void)fprintf(stderr,
300 "%s: warning -- J descriptors were closed!\n",
301 progname);
302 #endif
303 job_pipe[0] = -1;
304 job_pipe[1] = -1;
305 compatMake = TRUE;
306 } else {
307 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
308 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
309 jobServer = TRUE;
310 }
311 break;
312 #ifdef REMOTE
313 case 'L':
314 maxLocal = strtol(optarg, &p, 0);
315 if (*p != '\0' || maxLocal < 1) {
316 (void) fprintf(stderr, "%s: illegal argument to -L -- must be positive integer!\n",
317 progname);
318 exit(1);
319 }
320 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
321 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
322 break;
323 #endif
324 case 'N':
325 noExecute = TRUE;
326 noRecursiveExecute = TRUE;
327 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
328 break;
329 case 'P':
330 usePipes = FALSE;
331 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
332 break;
333 case 'S':
334 keepgoing = FALSE;
335 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
336 break;
337 case 'T':
338 tracefile = estrdup(optarg);
339 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
340 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
341 break;
342 case 'V':
343 printVars = TRUE;
344 (void)Lst_AtEnd(variables, (ClientData)optarg);
345 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
346 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
347 break;
348 case 'W':
349 parseWarnFatal = TRUE;
350 break;
351 case 'X':
352 varNoExportEnv = TRUE;
353 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
354 break;
355 case 'd': {
356 char *modules = optarg;
357
358 for (; *modules; ++modules)
359 switch (*modules) {
360 case 'A':
361 debug = ~0;
362 break;
363 case 'a':
364 debug |= DEBUG_ARCH;
365 break;
366 case 'c':
367 debug |= DEBUG_COND;
368 break;
369 case 'd':
370 debug |= DEBUG_DIR;
371 break;
372 case 'e':
373 debug |= DEBUG_ERROR;
374 break;
375 case 'f':
376 debug |= DEBUG_FOR;
377 break;
378 case 'g':
379 if (modules[1] == '1') {
380 debug |= DEBUG_GRAPH1;
381 ++modules;
382 }
383 else if (modules[1] == '2') {
384 debug |= DEBUG_GRAPH2;
385 ++modules;
386 }
387 else if (modules[1] == '3') {
388 debug |= DEBUG_GRAPH3;
389 ++modules;
390 }
391 break;
392 case 'j':
393 debug |= DEBUG_JOB;
394 break;
395 case 'm':
396 debug |= DEBUG_MAKE;
397 break;
398 case 'n':
399 debug |= DEBUG_SCRIPT;
400 break;
401 case 's':
402 debug |= DEBUG_SUFF;
403 break;
404 case 't':
405 debug |= DEBUG_TARG;
406 break;
407 case 'v':
408 debug |= DEBUG_VAR;
409 break;
410 case 'x':
411 debug |= DEBUG_SHELL;
412 break;
413 default:
414 (void)fprintf(stderr,
415 "%s: illegal argument to d option -- %c\n",
416 progname, *modules);
417 usage();
418 }
419 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
420 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
421 break;
422 }
423 case 'e':
424 checkEnvFirst = TRUE;
425 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
426 break;
427 case 'f':
428 (void)Lst_AtEnd(makefiles, (ClientData)optarg);
429 break;
430 case 'i':
431 ignoreErrors = TRUE;
432 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
433 break;
434 case 'j':
435 forceJobs = TRUE;
436 maxJobs = strtol(optarg, &p, 0);
437 if (*p != '\0' || maxJobs < 1) {
438 (void) fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
439 progname);
440 exit(1);
441 }
442 #ifndef REMOTE
443 maxLocal = maxJobs;
444 #endif
445 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
446 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
447 break;
448 case 'k':
449 keepgoing = TRUE;
450 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
451 break;
452 case 'm':
453 /* look for magic parent directory search string */
454 if (strncmp(".../", optarg, 4) == 0) {
455 if (!Dir_FindHereOrAbove(curdir, optarg+4,
456 found_path, sizeof(found_path)))
457 break; /* nothing doing */
458 (void) Dir_AddDir(sysIncPath, found_path);
459
460 } else {
461 (void) Dir_AddDir(sysIncPath, optarg);
462 }
463 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
464 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
465 break;
466 case 'n':
467 noExecute = TRUE;
468 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
469 break;
470 case 'q':
471 queryFlag = TRUE;
472 /* Kind of nonsensical, wot? */
473 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
474 break;
475 case 'r':
476 noBuiltins = TRUE;
477 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
478 break;
479 case 's':
480 beSilent = TRUE;
481 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
482 break;
483 case 't':
484 touchFlag = TRUE;
485 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
486 break;
487 case '-':
488 dashDash = TRUE;
489 break;
490 default:
491 case '?':
492 usage();
493 }
494 argv += arginc;
495 argc -= arginc;
496 }
497
498 oldVars = TRUE;
499
500 /*
501 * See if the rest of the arguments are variable assignments and
502 * perform them if so. Else take them to be targets and stuff them
503 * on the end of the "create" list.
504 */
505 for (; argc > 1; ++argv, --argc)
506 if (Parse_IsVar(argv[1])) {
507 Parse_DoVar(argv[1], VAR_CMD);
508 } else {
509 if (!*argv[1])
510 Punt("illegal (null) argument.");
511 if (*argv[1] == '-' && !dashDash)
512 goto rearg;
513 (void)Lst_AtEnd(create, (ClientData)estrdup(argv[1]));
514 }
515 }
516
517 /*-
518 * Main_ParseArgLine --
519 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
520 * is encountered and by main() when reading the .MAKEFLAGS envariable.
521 * Takes a line of arguments and breaks it into its
522 * component words and passes those words and the number of them to the
523 * MainParseArgs function.
524 * The line should have all its leading whitespace removed.
525 *
526 * Input:
527 * line Line to fracture
528 *
529 * Results:
530 * None
531 *
532 * Side Effects:
533 * Only those that come from the various arguments.
534 */
535 void
536 Main_ParseArgLine(char *line)
537 {
538 char **argv; /* Manufactured argument vector */
539 int argc; /* Number of arguments in argv */
540 char *args; /* Space used by the args */
541 char *buf, *p1;
542 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
543 size_t len;
544
545 if (line == NULL)
546 return;
547 for (; *line == ' '; ++line)
548 continue;
549 if (!*line)
550 return;
551
552 buf = emalloc(len = strlen(line) + strlen(argv0) + 2);
553 (void)snprintf(buf, len, "%s %s", argv0, line);
554 if (p1)
555 free(p1);
556
557 argv = brk_string(buf, &argc, TRUE, &args);
558 free(buf);
559 MainParseArgs(argc, argv);
560
561 free(args);
562 free(argv);
563 }
564
565 Boolean
566 Main_SetObjdir(const char *path)
567 {
568 struct stat sb;
569 char *p = NULL;
570 char buf[MAXPATHLEN + 1];
571 Boolean rc = FALSE;
572
573 /* expand variable substitutions */
574 if (strchr(path, '$') != 0) {
575 snprintf(buf, MAXPATHLEN, "%s", path);
576 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
577 }
578
579 if (path[0] != '/') {
580 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
581 path = buf;
582 }
583
584 /* look for the directory and try to chdir there */
585 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
586 if (chdir(path)) {
587 (void)fprintf(stderr, "make warning: %s: %s.\n",
588 path, strerror(errno));
589 } else {
590 strncpy(objdir, path, MAXPATHLEN);
591 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
592 setenv("PWD", objdir, 1);
593 Dir_InitDot();
594 rc = TRUE;
595 }
596 }
597
598 if (p)
599 free(p);
600 return rc;
601 }
602
603
604 /*-
605 * main --
606 * The main function, for obvious reasons. Initializes variables
607 * and a few modules, then parses the arguments give it in the
608 * environment and on the command line. Reads the system makefile
609 * followed by either Makefile, makefile or the file given by the
610 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
611 * flags it has received by then uses either the Make or the Compat
612 * module to create the initial list of targets.
613 *
614 * Results:
615 * If -q was given, exits -1 if anything was out-of-date. Else it exits
616 * 0.
617 *
618 * Side Effects:
619 * The program exits when done. Targets are created. etc. etc. etc.
620 */
621 int
622 main(int argc, char **argv)
623 {
624 Lst targs; /* target nodes to create -- passed to Make_Init */
625 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
626 struct stat sb, sa;
627 char *p1, *path, *pwd;
628 char mdpath[MAXPATHLEN];
629 char *machine = getenv("MACHINE");
630 const char *machine_arch = getenv("MACHINE_ARCH");
631 char *syspath = getenv("MAKESYSPATH");
632 Lst sysMkPath; /* Path of sys.mk */
633 char *cp = NULL, *start;
634 /* avoid faults on read-only strings */
635 static char defsyspath[] = _PATH_DEFSYSPATH;
636 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
637 struct timeval rightnow; /* to initialize random seed */
638
639 /*
640 * Set the seed to produce a different random sequences
641 * on each program execution.
642 */
643 gettimeofday(&rightnow, NULL);
644 srandom(rightnow.tv_sec + rightnow.tv_usec);
645
646 if ((progname = strrchr(argv[0], '/')) != NULL)
647 progname++;
648 else
649 progname = argv[0];
650 #ifdef RLIMIT_NOFILE
651 /*
652 * get rid of resource limit on file descriptors
653 */
654 {
655 struct rlimit rl;
656 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
657 rl.rlim_cur != rl.rlim_max) {
658 rl.rlim_cur = rl.rlim_max;
659 (void) setrlimit(RLIMIT_NOFILE, &rl);
660 }
661 }
662 #endif
663 /*
664 * Find where we are and take care of PWD for the automounter...
665 * All this code is so that we know where we are when we start up
666 * on a different machine with pmake.
667 */
668 if (getcwd(curdir, MAXPATHLEN) == NULL) {
669 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
670 exit(2);
671 }
672
673 if (stat(curdir, &sa) == -1) {
674 (void)fprintf(stderr, "%s: %s: %s.\n",
675 progname, curdir, strerror(errno));
676 exit(2);
677 }
678
679 /*
680 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
681 * since the value of curdir can very depending on how we got
682 * here. Ie sitting at a shell prompt (shell that provides $PWD)
683 * or via subdir.mk in which case its likely a shell which does
684 * not provide it.
685 * So, to stop it breaking this case only, we ignore PWD if
686 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
687 */
688 if ((pwd = getenv("PWD")) != NULL && getenv("MAKEOBJDIRPREFIX") == NULL) {
689 const char *makeobjdir = getenv("MAKEOBJDIR");
690
691 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
692 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
693 sa.st_dev == sb.st_dev)
694 (void) strncpy(curdir, pwd, MAXPATHLEN);
695 }
696 }
697
698 /*
699 * Get the name of this type of MACHINE from utsname
700 * so we can share an executable for similar machines.
701 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
702 *
703 * Note that both MACHINE and MACHINE_ARCH are decided at
704 * run-time.
705 */
706 if (!machine) {
707 #ifdef MAKE_NATIVE
708 struct utsname utsname;
709
710 if (uname(&utsname) == -1) {
711 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
712 strerror(errno));
713 exit(2);
714 }
715 machine = utsname.machine;
716 #else
717 #ifdef MAKE_MACHINE
718 machine = MAKE_MACHINE;
719 #else
720 machine = "unknown";
721 #endif
722 #endif
723 }
724
725 if (!machine_arch) {
726 #ifndef MACHINE_ARCH
727 #ifdef MAKE_MACHINE_ARCH
728 machine_arch = MAKE_MACHINE_ARCH;
729 #else
730 machine_arch = "unknown";
731 #endif
732 #else
733 machine_arch = MACHINE_ARCH;
734 #endif
735 }
736
737 /*
738 * Just in case MAKEOBJDIR wants us to do something tricky.
739 */
740 Var_Init(); /* Initialize the lists of variables for
741 * parsing arguments */
742 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
743 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
744 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
745 #ifdef MAKE_VERSION
746 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
747 #endif
748 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
749
750 /*
751 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
752 * MAKEOBJDIR is set in the environment, try only that value
753 * and fall back to .CURDIR if it does not exist.
754 */
755 Dir_Init(curdir);
756 (void) Main_SetObjdir(curdir);
757
758 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
759 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
760 (void) Main_SetObjdir(mdpath);
761 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
762 (void) Main_SetObjdir(path);
763 }
764
765 create = Lst_Init(FALSE);
766 makefiles = Lst_Init(FALSE);
767 printVars = FALSE;
768 variables = Lst_Init(FALSE);
769 beSilent = FALSE; /* Print commands as executed */
770 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
771 noExecute = FALSE; /* Execute all commands */
772 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
773 keepgoing = FALSE; /* Stop on error */
774 allPrecious = FALSE; /* Remove targets when interrupted */
775 queryFlag = FALSE; /* This is not just a check-run */
776 noBuiltins = FALSE; /* Read the built-in rules */
777 touchFlag = FALSE; /* Actually update targets */
778 usePipes = TRUE; /* Catch child output in pipes */
779 debug = 0; /* No debug verbosity, please. */
780 jobsRunning = FALSE;
781
782 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
783 #ifdef REMOTE
784 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
785 #else
786 maxJobs = maxLocal;
787 #endif
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 != (char *) 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(maxJobs);
932 if (DEBUG(JOB))
933 printf("job_pipe %d %d, maxjobs %d maxlocal %d compat %d\n", job_pipe[0], job_pipe[1], maxJobs,
934 maxLocal, 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 (void)free((Address)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 Targ_Propagate();
983
984 /* print the initial graph, if the user requested it */
985 if (DEBUG(GRAPH1))
986 Targ_PrintGraph(1);
987
988 /* print the values of any variables requested by the user */
989 if (printVars) {
990 LstNode ln;
991
992 for (ln = Lst_First(variables); ln != NILLNODE;
993 ln = Lst_Succ(ln)) {
994 char *var = (char *)Lst_Datum(ln);
995 char *value;
996
997 if (strchr(var, '$')) {
998 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
999 } else {
1000 value = Var_Value(var, VAR_GLOBAL, &p1);
1001 }
1002 printf("%s\n", value ? value : "");
1003 if (p1)
1004 free(p1);
1005 }
1006 }
1007
1008 /*
1009 * Have now read the entire graph and need to make a list of targets
1010 * to create. If none was given on the command line, we consult the
1011 * parsing module to find the main target(s) to create.
1012 */
1013 if (Lst_IsEmpty(create))
1014 targs = Parse_MainName();
1015 else
1016 targs = Targ_FindList(create, TARG_CREATE);
1017
1018 if (!compatMake && !printVars) {
1019 /*
1020 * Initialize job module before traversing the graph, now that
1021 * any .BEGIN and .END targets have been read. This is done
1022 * only if the -q flag wasn't given (to prevent the .BEGIN from
1023 * being executed should it exist).
1024 */
1025 if (!queryFlag) {
1026 if (maxLocal == -1)
1027 maxLocal = maxJobs;
1028 Job_Init(maxJobs, maxLocal);
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, (void (*)(ClientData))) 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 Job_TokenFlush();
1504
1505 (void)vfprintf(stderr, fmt, ap);
1506 va_end(ap);
1507 (void)fprintf(stderr, "\n");
1508 (void)fflush(stderr);
1509
1510 PrintOnError(NULL);
1511
1512 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1513 Targ_PrintGraph(2);
1514 Trace_Log(MAKEERROR, 0);
1515 exit(2); /* Not 1 so -q can distinguish error */
1516 }
1517
1518 /*
1519 * Punt --
1520 * Major exception once jobs are being created. Kills all jobs, prints
1521 * a message and exits.
1522 *
1523 * Results:
1524 * None
1525 *
1526 * Side Effects:
1527 * All children are killed indiscriminately and the program Lib_Exits
1528 */
1529 /* VARARGS */
1530 void
1531 Punt(const char *fmt, ...)
1532 {
1533 va_list ap;
1534
1535 va_start(ap, fmt);
1536 (void)fprintf(stderr, "%s: ", progname);
1537 (void)vfprintf(stderr, fmt, ap);
1538 va_end(ap);
1539 (void)fprintf(stderr, "\n");
1540 (void)fflush(stderr);
1541
1542 PrintOnError(NULL);
1543
1544 DieHorribly();
1545 }
1546
1547 /*-
1548 * DieHorribly --
1549 * Exit without giving a message.
1550 *
1551 * Results:
1552 * None
1553 *
1554 * Side Effects:
1555 * A big one...
1556 */
1557 void
1558 DieHorribly(void)
1559 {
1560 if (jobsRunning)
1561 Job_AbortAll();
1562 if (DEBUG(GRAPH2))
1563 Targ_PrintGraph(2);
1564 Trace_Log(MAKEERROR, 0);
1565 exit(2); /* Not 1, so -q can distinguish error */
1566 }
1567
1568 /*
1569 * Finish --
1570 * Called when aborting due to errors in child shell to signal
1571 * abnormal exit.
1572 *
1573 * Results:
1574 * None
1575 *
1576 * Side Effects:
1577 * The program exits
1578 */
1579 void
1580 Finish(int errors)
1581 /* number of errors encountered in Make_Make */
1582 {
1583 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1584 }
1585
1586 /*
1587 * emalloc --
1588 * malloc, but die on error.
1589 */
1590 void *
1591 emalloc(size_t len)
1592 {
1593 void *p;
1594
1595 if ((p = malloc(len)) == NULL)
1596 enomem();
1597 return(p);
1598 }
1599
1600 /*
1601 * estrdup --
1602 * strdup, but die on error.
1603 */
1604 char *
1605 estrdup(const char *str)
1606 {
1607 char *p;
1608
1609 if ((p = strdup(str)) == NULL)
1610 enomem();
1611 return(p);
1612 }
1613
1614 /*
1615 * erealloc --
1616 * realloc, but die on error.
1617 */
1618 void *
1619 erealloc(void *ptr, size_t size)
1620 {
1621 if ((ptr = realloc(ptr, size)) == NULL)
1622 enomem();
1623 return(ptr);
1624 }
1625
1626 /*
1627 * enomem --
1628 * die when out of memory.
1629 */
1630 void
1631 enomem(void)
1632 {
1633 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
1634 exit(2);
1635 }
1636
1637 /*
1638 * enunlink --
1639 * Remove a file carefully, avoiding directories.
1640 */
1641 int
1642 eunlink(const char *file)
1643 {
1644 struct stat st;
1645
1646 if (lstat(file, &st) == -1)
1647 return -1;
1648
1649 if (S_ISDIR(st.st_mode)) {
1650 errno = EISDIR;
1651 return -1;
1652 }
1653 return unlink(file);
1654 }
1655
1656 /*
1657 * execError --
1658 * Print why exec failed, avoiding stdio.
1659 */
1660 void
1661 execError(const char *af, const char *av)
1662 {
1663 #ifdef USE_IOVEC
1664 int i = 0;
1665 struct iovec iov[8];
1666 #define IOADD(s) \
1667 (void)(iov[i].iov_base = UNCONST(s), \
1668 iov[i].iov_len = strlen(iov[i].iov_base), \
1669 i++)
1670 #else
1671 #define IOADD (void)write(2, s, strlen(s))
1672 #endif
1673
1674 IOADD(progname);
1675 IOADD(": ");
1676 IOADD(af);
1677 IOADD("(");
1678 IOADD(av);
1679 IOADD(") failed (");
1680 IOADD(strerror(errno));
1681 IOADD(")\n");
1682
1683 #ifdef USE_IOVEC
1684 (void)writev(2, iov, 8);
1685 #endif
1686 }
1687
1688 /*
1689 * usage --
1690 * exit with usage message
1691 */
1692 static void
1693 usage(void)
1694 {
1695 (void)fprintf(stderr,
1696 "usage: %s [-BeikNnqrstWX] [-D variable] [-d flags] [-f makefile]\n\
1697 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1698 [-V variable] [variable=value] [target ...]\n", progname);
1699 exit(2);
1700 }
1701
1702
1703 int
1704 PrintAddr(ClientData a, ClientData b)
1705 {
1706 printf("%lx ", (unsigned long) a);
1707 return b ? 0 : 0;
1708 }
1709
1710
1711
1712 void
1713 PrintOnError(const char *s)
1714 {
1715 char tmp[64];
1716
1717 if (s)
1718 printf("%s", s);
1719
1720 printf("\n%s: stopped in %s\n", progname, curdir);
1721 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1722 sizeof(tmp) - 1);
1723 s = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1724 if (s && *s)
1725 printf("%s", s);
1726 }
1727
1728 void
1729 Main_ExportMAKEFLAGS(Boolean first)
1730 {
1731 static int once = 1;
1732 char tmp[64];
1733 char *s;
1734
1735 if (once != first)
1736 return;
1737 once = 0;
1738
1739 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1740 sizeof(tmp));
1741 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1742 if (s && *s) {
1743 #ifdef POSIX
1744 setenv("MAKEFLAGS", s, 1);
1745 #else
1746 setenv("MAKE", s, 1);
1747 #endif
1748 }
1749 }
1750