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