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