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