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