main.c revision 1.119 1 /* $NetBSD: main.c,v 1.119 2006/02/18 04:10:05 tsutsui 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.119 2006/02/18 04:10:05 tsutsui 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.119 2006/02/18 04:10:05 tsutsui Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
88
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
93 *
94 * Utility functions defined in this file:
95 * Main_ParseArgLine Takes a line of arguments, breaks them and
96 * treats them as if they were given when first
97 * invoked. Used by the parse module to implement
98 * the .MFLAGS target.
99 *
100 * Error Print a tagged error message. The global
101 * MAKE variable must have been defined. This
102 * takes a format string and two optional
103 * arguments for it.
104 *
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
107 *
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
110 *
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
114 */
115
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/signal.h>
121 #include <sys/stat.h>
122 #ifdef MAKE_NATIVE
123 #include <sys/utsname.h>
124 #endif
125 #include <sys/wait.h>
126
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
133
134 #include "make.h"
135 #include "hash.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "pathnames.h"
139 #include "trace.h"
140
141 #ifdef USE_IOVEC
142 #include <sys/uio.h>
143 #endif
144
145 #ifndef DEFMAXLOCAL
146 #define DEFMAXLOCAL DEFMAXJOBS
147 #endif /* DEFMAXLOCAL */
148
149 Lst create; /* Targets to be made */
150 time_t now; /* Time at start of make */
151 GNode *DEFAULT; /* .DEFAULT node */
152 Boolean allPrecious; /* .PRECIOUS given on line by itself */
153
154 static Boolean noBuiltins; /* -r flag */
155 static Lst makefiles; /* ordered list of makefiles to read */
156 static Boolean printVars; /* print value of one or more vars */
157 static Lst variables; /* list of variables to print */
158 int maxJobs; /* -j argument */
159 static int maxLocal; /* -L argument */
160 Boolean compatMake; /* -B argument */
161 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;
211 const char *getopt_def;
212 char *optscan;
213 Boolean inOption, dashDash = FALSE;
214 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
215
216 #ifdef REMOTE
217 # define OPTFLAGS "BD:I:J:L:NPST:V:WXd:ef:ij:km:nqrst"
218 #else
219 # define OPTFLAGS "BD:I:J:NPST:V:WXd:ef:ij:km:nqrst"
220 #endif
221 #undef optarg
222 #define optarg argvalue
223 /* Can't actually use getopt(3) because rescanning is not portable */
224
225 getopt_def = OPTFLAGS;
226 rearg:
227 inOption = FALSE;
228 optscan = NULL;
229 while(argc > 1) {
230 char *getopt_spec;
231 if(!inOption)
232 optscan = argv[1];
233 c = *optscan++;
234 arginc = 0;
235 if(inOption) {
236 if(c == '\0') {
237 ++argv;
238 --argc;
239 inOption = FALSE;
240 continue;
241 }
242 } else {
243 if (c != '-' || dashDash)
244 break;
245 inOption = TRUE;
246 c = *optscan++;
247 }
248 /* '-' found at some earlier point */
249 getopt_spec = strchr(getopt_def, c);
250 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
251 /* -<something> found, and <something> should have an arg */
252 inOption = FALSE;
253 arginc = 1;
254 argvalue = optscan;
255 if(*argvalue == '\0') {
256 if (argc < 3) {
257 (void)fprintf(stderr,
258 "%s: option requires "
259 "an argument -- %c\n",
260 progname, c);
261 usage();
262 }
263 argvalue = argv[2];
264 arginc = 2;
265 }
266 } else {
267 argvalue = NULL;
268 }
269 switch(c) {
270 case '\0':
271 arginc = 1;
272 inOption = FALSE;
273 break;
274 case 'B':
275 compatMake = TRUE;
276 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
277 break;
278 case 'D':
279 Var_Set(optarg, "1", VAR_GLOBAL, 0);
280 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
281 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
282 break;
283 case 'I':
284 Parse_AddIncludeDir(optarg);
285 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
286 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
287 break;
288 case 'J':
289 if (sscanf(optarg, "%d,%d", &job_pipe[0], &job_pipe[1]) != 2) {
290 /* backslash to avoid trigraph ??) */
291 (void)fprintf(stderr,
292 "%s: internal error -- J option malformed (%s?\?)\n",
293 progname, optarg);
294 usage();
295 }
296 if ((fcntl(job_pipe[0], F_GETFD, 0) < 0) ||
297 (fcntl(job_pipe[1], F_GETFD, 0) < 0)) {
298 #if 0
299 (void)fprintf(stderr,
300 "%s: warning -- J descriptors were closed!\n",
301 progname);
302 exit(2);
303 #endif
304 job_pipe[0] = -1;
305 job_pipe[1] = -1;
306 compatMake = TRUE;
307 } else {
308 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
309 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
310 jobServer = TRUE;
311 }
312 break;
313 #ifdef REMOTE
314 case 'L':
315 maxLocal = strtol(optarg, &p, 0);
316 if (*p != '\0' || maxLocal < 1) {
317 (void)fprintf(stderr, "%s: illegal argument to -L -- must be positive integer!\n",
318 progname);
319 exit(1);
320 }
321 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
322 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
323 break;
324 #endif
325 case 'N':
326 noExecute = TRUE;
327 noRecursiveExecute = TRUE;
328 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
329 break;
330 case 'P':
331 usePipes = FALSE;
332 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
333 break;
334 case 'S':
335 keepgoing = FALSE;
336 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
337 break;
338 case 'T':
339 tracefile = estrdup(optarg);
340 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
341 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
342 break;
343 case 'V':
344 printVars = TRUE;
345 (void)Lst_AtEnd(variables, (ClientData)optarg);
346 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
347 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
348 break;
349 case 'W':
350 parseWarnFatal = TRUE;
351 break;
352 case 'X':
353 varNoExportEnv = TRUE;
354 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
355 break;
356 case 'd': {
357 char *modules = optarg;
358
359 for (; *modules; ++modules)
360 switch (*modules) {
361 case 'A':
362 debug = ~0;
363 break;
364 case 'a':
365 debug |= DEBUG_ARCH;
366 break;
367 case 'c':
368 debug |= DEBUG_COND;
369 break;
370 case 'd':
371 debug |= DEBUG_DIR;
372 break;
373 case 'e':
374 debug |= DEBUG_ERROR;
375 break;
376 case 'f':
377 debug |= DEBUG_FOR;
378 break;
379 case 'g':
380 if (modules[1] == '1') {
381 debug |= DEBUG_GRAPH1;
382 ++modules;
383 }
384 else if (modules[1] == '2') {
385 debug |= DEBUG_GRAPH2;
386 ++modules;
387 }
388 else if (modules[1] == '3') {
389 debug |= DEBUG_GRAPH3;
390 ++modules;
391 }
392 break;
393 case 'j':
394 debug |= DEBUG_JOB;
395 break;
396 case 'm':
397 debug |= DEBUG_MAKE;
398 break;
399 case 'n':
400 debug |= DEBUG_SCRIPT;
401 break;
402 case 'p':
403 debug |= DEBUG_PARSE;
404 break;
405 case 's':
406 debug |= DEBUG_SUFF;
407 break;
408 case 't':
409 debug |= DEBUG_TARG;
410 break;
411 case 'v':
412 debug |= DEBUG_VAR;
413 break;
414 case 'x':
415 debug |= DEBUG_SHELL;
416 break;
417 default:
418 (void)fprintf(stderr,
419 "%s: illegal argument to d option -- %c\n",
420 progname, *modules);
421 usage();
422 }
423 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
424 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
425 break;
426 }
427 case 'e':
428 checkEnvFirst = TRUE;
429 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
430 break;
431 case 'f':
432 (void)Lst_AtEnd(makefiles, (ClientData)optarg);
433 break;
434 case 'i':
435 ignoreErrors = TRUE;
436 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
437 break;
438 case 'j':
439 forceJobs = TRUE;
440 maxJobs = strtol(optarg, &p, 0);
441 if (*p != '\0' || maxJobs < 1) {
442 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
443 progname);
444 exit(1);
445 }
446 #ifndef REMOTE
447 maxLocal = maxJobs;
448 #endif
449 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
450 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
451 break;
452 case 'k':
453 keepgoing = TRUE;
454 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
455 break;
456 case 'm':
457 /* look for magic parent directory search string */
458 if (strncmp(".../", optarg, 4) == 0) {
459 if (!Dir_FindHereOrAbove(curdir, optarg+4,
460 found_path, sizeof(found_path)))
461 break; /* nothing doing */
462 (void)Dir_AddDir(sysIncPath, found_path);
463
464 } else {
465 (void)Dir_AddDir(sysIncPath, optarg);
466 }
467 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
468 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
469 break;
470 case 'n':
471 noExecute = TRUE;
472 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
473 break;
474 case 'q':
475 queryFlag = TRUE;
476 /* Kind of nonsensical, wot? */
477 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
478 break;
479 case 'r':
480 noBuiltins = TRUE;
481 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
482 break;
483 case 's':
484 beSilent = TRUE;
485 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
486 break;
487 case 't':
488 touchFlag = TRUE;
489 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
490 break;
491 case '-':
492 dashDash = TRUE;
493 break;
494 default:
495 case '?':
496 usage();
497 }
498 argv += arginc;
499 argc -= arginc;
500 }
501
502 oldVars = TRUE;
503
504 /*
505 * See if the rest of the arguments are variable assignments and
506 * perform them if so. Else take them to be targets and stuff them
507 * on the end of the "create" list.
508 */
509 for (; argc > 1; ++argv, --argc)
510 if (Parse_IsVar(argv[1])) {
511 Parse_DoVar(argv[1], VAR_CMD);
512 } else {
513 if (!*argv[1])
514 Punt("illegal (null) argument.");
515 if (*argv[1] == '-' && !dashDash)
516 goto rearg;
517 (void)Lst_AtEnd(create, (ClientData)estrdup(argv[1]));
518 }
519 }
520
521 /*-
522 * Main_ParseArgLine --
523 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
524 * is encountered and by main() when reading the .MAKEFLAGS envariable.
525 * Takes a line of arguments and breaks it into its
526 * component words and passes those words and the number of them to the
527 * MainParseArgs function.
528 * The line should have all its leading whitespace removed.
529 *
530 * Input:
531 * line Line to fracture
532 *
533 * Results:
534 * None
535 *
536 * Side Effects:
537 * Only those that come from the various arguments.
538 */
539 void
540 Main_ParseArgLine(char *line)
541 {
542 char **argv; /* Manufactured argument vector */
543 int argc; /* Number of arguments in argv */
544 char *args; /* Space used by the args */
545 char *buf, *p1;
546 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
547 size_t len;
548
549 if (line == NULL)
550 return;
551 for (; *line == ' '; ++line)
552 continue;
553 if (!*line)
554 return;
555
556 buf = emalloc(len = strlen(line) + strlen(argv0) + 2);
557 (void)snprintf(buf, len, "%s %s", argv0, line);
558 if (p1)
559 free(p1);
560
561 argv = brk_string(buf, &argc, TRUE, &args);
562 free(buf);
563 MainParseArgs(argc, argv);
564
565 free(args);
566 free(argv);
567 }
568
569 Boolean
570 Main_SetObjdir(const char *path)
571 {
572 struct stat sb;
573 char *p = NULL;
574 char buf[MAXPATHLEN + 1];
575 Boolean rc = FALSE;
576
577 /* expand variable substitutions */
578 if (strchr(path, '$') != 0) {
579 snprintf(buf, MAXPATHLEN, "%s", path);
580 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
581 }
582
583 if (path[0] != '/') {
584 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
585 path = buf;
586 }
587
588 /* look for the directory and try to chdir there */
589 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
590 if (chdir(path)) {
591 (void)fprintf(stderr, "make warning: %s: %s.\n",
592 path, strerror(errno));
593 } else {
594 strncpy(objdir, path, MAXPATHLEN);
595 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
596 setenv("PWD", objdir, 1);
597 Dir_InitDot();
598 rc = TRUE;
599 }
600 }
601
602 if (p)
603 free(p);
604 return rc;
605 }
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 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
799 #ifdef REMOTE
800 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
801 #else
802 maxJobs = maxLocal;
803 #endif
804 compatMake = FALSE; /* No compat mode */
805
806
807 /*
808 * Initialize the parsing, directory and variable modules to prepare
809 * for the reading of inclusion paths and variable settings on the
810 * command line
811 */
812
813 /*
814 * Initialize various variables.
815 * MAKE also gets this name, for compatibility
816 * .MAKEFLAGS gets set to the empty string just in case.
817 * MFLAGS also gets initialized empty, for compatibility.
818 */
819 Parse_Init();
820 Var_Set("MAKE", argv[0], VAR_GLOBAL, 0);
821 Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0);
822 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
823 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
824 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
825 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
826
827 /*
828 * First snag any flags out of the MAKE environment variable.
829 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
830 * in a different format).
831 */
832 #ifdef POSIX
833 Main_ParseArgLine(getenv("MAKEFLAGS"));
834 #else
835 Main_ParseArgLine(getenv("MAKE"));
836 #endif
837
838 MainParseArgs(argc, argv);
839
840 /*
841 * Be compatible if user did not specify -j and did not explicitly
842 * turned compatibility on
843 */
844 if (!compatMake && !forceJobs) {
845 compatMake = TRUE;
846 }
847
848 /*
849 * Initialize archive, target and suffix modules in preparation for
850 * parsing the makefile(s)
851 */
852 Arch_Init();
853 Targ_Init();
854 Suff_Init();
855 Trace_Init(tracefile);
856
857 DEFAULT = NILGNODE;
858 (void)time(&now);
859
860 Trace_Log(MAKESTART, NULL);
861
862 /*
863 * Set up the .TARGETS variable to contain the list of targets to be
864 * created. If none specified, make the variable empty -- the parser
865 * will fill the thing in with the default or .MAIN target.
866 */
867 if (!Lst_IsEmpty(create)) {
868 LstNode ln;
869
870 for (ln = Lst_First(create); ln != NILLNODE;
871 ln = Lst_Succ(ln)) {
872 char *name = (char *)Lst_Datum(ln);
873
874 Var_Append(".TARGETS", name, VAR_GLOBAL);
875 }
876 } else
877 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
878
879
880 /*
881 * If no user-supplied system path was given (through the -m option)
882 * add the directories from the DEFSYSPATH (more than one may be given
883 * as dir1:...:dirn) to the system include path.
884 */
885 if (syspath == NULL || *syspath == '\0')
886 syspath = defsyspath;
887 else
888 syspath = strdup(syspath);
889
890 for (start = syspath; *start != '\0'; start = cp) {
891 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
892 continue;
893 if (*cp == ':') {
894 *cp++ = '\0';
895 }
896 /* look for magic parent directory search string */
897 if (strncmp(".../", start, 4) != 0) {
898 (void)Dir_AddDir(defIncPath, start);
899 } else {
900 if (Dir_FindHereOrAbove(curdir, start+4,
901 found_path, sizeof(found_path))) {
902 (void)Dir_AddDir(defIncPath, found_path);
903 }
904 }
905 }
906 if (syspath != defsyspath)
907 free(syspath);
908
909 /*
910 * Read in the built-in rules first, followed by the specified
911 * makefile, if it was (makefile != NULL), or the default
912 * makefile and Makefile, in that order, if it wasn't.
913 */
914 if (!noBuiltins) {
915 LstNode ln;
916
917 sysMkPath = Lst_Init(FALSE);
918 Dir_Expand(_PATH_DEFSYSMK,
919 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
920 sysMkPath);
921 if (Lst_IsEmpty(sysMkPath))
922 Fatal("%s: no system rules (%s).", progname,
923 _PATH_DEFSYSMK);
924 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
925 if (ln != NILLNODE)
926 Fatal("%s: cannot open %s.", progname,
927 (char *)Lst_Datum(ln));
928 }
929
930 if (!Lst_IsEmpty(makefiles)) {
931 LstNode ln;
932
933 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
934 if (ln != NILLNODE)
935 Fatal("%s: cannot open %s.", progname,
936 (char *)Lst_Datum(ln));
937 } else if (!ReadMakefile(UNCONST("makefile"), NULL))
938 (void)ReadMakefile(UNCONST("Makefile"), NULL);
939
940 (void)ReadMakefile(UNCONST(".depend"), NULL);
941
942 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
943 if (p1)
944 free(p1);
945
946 if (!jobServer && !compatMake)
947 Job_ServerStart(maxJobs);
948 if (DEBUG(JOB))
949 printf("job_pipe %d %d, maxjobs %d maxlocal %d compat %d\n", job_pipe[0], job_pipe[1], maxJobs,
950 maxLocal, compatMake);
951
952 Main_ExportMAKEFLAGS(TRUE); /* initial export */
953
954 Check_Cwd_av(0, NULL, 0); /* initialize it */
955
956
957 /*
958 * For compatibility, look at the directories in the VPATH variable
959 * and add them to the search path, if the variable is defined. The
960 * variable's value is in the same format as the PATH envariable, i.e.
961 * <directory>:<directory>:<directory>...
962 */
963 if (Var_Exists("VPATH", VAR_CMD)) {
964 char *vpath, savec;
965 /*
966 * GCC stores string constants in read-only memory, but
967 * Var_Subst will want to write this thing, so store it
968 * in an array
969 */
970 static char VPATH[] = "${VPATH}";
971
972 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
973 path = vpath;
974 do {
975 /* skip to end of directory */
976 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
977 continue;
978 /* Save terminator character so know when to stop */
979 savec = *cp;
980 *cp = '\0';
981 /* Add directory to search path */
982 (void)Dir_AddDir(dirSearchPath, path);
983 *cp = savec;
984 path = cp + 1;
985 } while (savec == ':');
986 free(vpath);
987 }
988
989 /*
990 * Now that all search paths have been read for suffixes et al, it's
991 * time to add the default search path to their lists...
992 */
993 Suff_DoPaths();
994
995 /*
996 * Propagate attributes through :: dependency lists.
997 */
998 Targ_Propagate();
999
1000 /* print the initial graph, if the user requested it */
1001 if (DEBUG(GRAPH1))
1002 Targ_PrintGraph(1);
1003
1004 /* print the values of any variables requested by the user */
1005 if (printVars) {
1006 LstNode ln;
1007
1008 for (ln = Lst_First(variables); ln != NILLNODE;
1009 ln = Lst_Succ(ln)) {
1010 char *var = (char *)Lst_Datum(ln);
1011 char *value;
1012
1013 if (strchr(var, '$')) {
1014 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1015 } else {
1016 value = Var_Value(var, VAR_GLOBAL, &p1);
1017 }
1018 printf("%s\n", value ? value : "");
1019 if (p1)
1020 free(p1);
1021 }
1022 }
1023
1024 /*
1025 * Have now read the entire graph and need to make a list of targets
1026 * to create. If none was given on the command line, we consult the
1027 * parsing module to find the main target(s) to create.
1028 */
1029 if (Lst_IsEmpty(create))
1030 targs = Parse_MainName();
1031 else
1032 targs = Targ_FindList(create, TARG_CREATE);
1033
1034 if (!compatMake && !printVars) {
1035 /*
1036 * Initialize job module before traversing the graph, now that
1037 * any .BEGIN and .END targets have been read. This is done
1038 * only if the -q flag wasn't given (to prevent the .BEGIN from
1039 * being executed should it exist).
1040 */
1041 if (!queryFlag) {
1042 if (maxLocal == -1)
1043 maxLocal = maxJobs;
1044 Job_Init(maxJobs, maxLocal);
1045 jobsRunning = TRUE;
1046 }
1047
1048 /* Traverse the graph, checking on all the targets */
1049 outOfDate = Make_Run(targs);
1050 } else if (!printVars) {
1051 /*
1052 * Compat_Init will take care of creating all the targets as
1053 * well as initializing the module.
1054 */
1055 Compat_Run(targs);
1056 }
1057
1058 #ifdef CLEANUP
1059 Lst_Destroy(targs, NOFREE);
1060 Lst_Destroy(variables, NOFREE);
1061 Lst_Destroy(makefiles, NOFREE);
1062 Lst_Destroy(create, (FreeProc *)free);
1063 #endif
1064
1065 /* print the graph now it's been processed if the user requested it */
1066 if (DEBUG(GRAPH2))
1067 Targ_PrintGraph(2);
1068
1069 Trace_Log(MAKEEND, 0);
1070
1071 Suff_End();
1072 Targ_End();
1073 Arch_End();
1074 Var_End();
1075 Parse_End();
1076 Dir_End();
1077 Job_End();
1078 Trace_End();
1079
1080 if (queryFlag && outOfDate)
1081 return(1);
1082 else
1083 return(0);
1084 }
1085
1086 /*-
1087 * ReadMakefile --
1088 * Open and parse the given makefile.
1089 *
1090 * Results:
1091 * TRUE if ok. FALSE if couldn't open file.
1092 *
1093 * Side Effects:
1094 * lots
1095 */
1096 static Boolean
1097 ReadMakefile(ClientData p, ClientData q __unused)
1098 {
1099 char *fname = p; /* makefile to read */
1100 FILE *stream;
1101 size_t len = MAXPATHLEN;
1102 char *name, *path = emalloc(len);
1103 int setMAKEFILE;
1104
1105 if (!strcmp(fname, "-")) {
1106 Parse_File("(stdin)", stdin);
1107 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1108 } else {
1109 setMAKEFILE = strcmp(fname, ".depend");
1110
1111 /* if we've chdir'd, rebuild the path name */
1112 if (strcmp(curdir, objdir) && *fname != '/') {
1113 size_t plen = strlen(curdir) + strlen(fname) + 2;
1114 if (len < plen)
1115 path = erealloc(path, len = 2 * plen);
1116
1117 (void)snprintf(path, len, "%s/%s", curdir, fname);
1118 if ((stream = fopen(path, "r")) != NULL) {
1119 fname = path;
1120 goto found;
1121 }
1122
1123 /* If curdir failed, try objdir (ala .depend) */
1124 plen = strlen(objdir) + strlen(fname) + 2;
1125 if (len < plen)
1126 path = erealloc(path, len = 2 * plen);
1127 (void)snprintf(path, len, "%s/%s", objdir, fname);
1128 if ((stream = fopen(path, "r")) != NULL) {
1129 fname = path;
1130 goto found;
1131 }
1132 } else if ((stream = fopen(fname, "r")) != NULL)
1133 goto found;
1134 /* look in -I and system include directories. */
1135 name = Dir_FindFile(fname, parseIncPath);
1136 if (!name)
1137 name = Dir_FindFile(fname,
1138 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1139 if (!name || !(stream = fopen(name, "r"))) {
1140 free(path);
1141 return(FALSE);
1142 }
1143 fname = name;
1144 /*
1145 * set the MAKEFILE variable desired by System V fans -- the
1146 * placement of the setting here means it gets set to the last
1147 * makefile specified, as it is set by SysV make.
1148 */
1149 found:
1150 if (setMAKEFILE)
1151 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1152 Parse_File(fname, stream);
1153 (void)fclose(stream);
1154 }
1155 free(path);
1156 return(TRUE);
1157 }
1158
1159
1160 /*
1161 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1162 * in situations that would not arrise with ./obj (links or not).
1163 * This tends to break things like:
1164 *
1165 * build:
1166 * ${MAKE} includes
1167 *
1168 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1169 * opposed to an argument) in a command line and if so returns
1170 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1171 * the Makefile hold true.
1172 *
1173 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1174 *
1175 * The chdir() only happens in the child process, and does nothing if
1176 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1177 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1178 * do nothing - to ensure historic semantics can be retained.
1179 */
1180 static int Check_Cwd_Off = 0;
1181
1182 static char *
1183 Check_Cwd_av(int ac, char **av, int copy)
1184 {
1185 static char *make[4];
1186 static char *cur_dir = NULL;
1187 char **mp;
1188 char *cp;
1189 int is_cmd, next_cmd;
1190 int i;
1191 int n;
1192
1193 if (Check_Cwd_Off)
1194 return NULL;
1195
1196 if (make[0] == NULL) {
1197 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1198 Check_Cwd_Off = 1;
1199 return NULL;
1200 }
1201
1202 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1203 if ((make[0] = strrchr(make[1], '/')) == NULL) {
1204 make[0] = make[1];
1205 make[1] = NULL;
1206 } else
1207 ++make[0];
1208 make[2] = NULL;
1209 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1210 }
1211 if (ac == 0 || av == NULL)
1212 return NULL; /* initialization only */
1213
1214 if (getenv("MAKEOBJDIR") == NULL &&
1215 getenv("MAKEOBJDIRPREFIX") == NULL)
1216 return NULL;
1217
1218
1219 next_cmd = 1;
1220 for (i = 0; i < ac; ++i) {
1221 is_cmd = next_cmd;
1222
1223 n = strlen(av[i]);
1224 cp = &(av[i])[n - 1];
1225 if (strspn(av[i], "|&;") == n) {
1226 next_cmd = 1;
1227 continue;
1228 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1229 next_cmd = 1;
1230 if (copy) {
1231 do {
1232 *cp-- = '\0';
1233 } while (*cp == ';' || *cp == '&' || *cp == '|' ||
1234 *cp == ')' || *cp == '}') ;
1235 } else {
1236 /*
1237 * XXX this should not happen.
1238 */
1239 fprintf(stderr, "WARNING: raw arg ends in shell meta '%s'\n",
1240 av[i]);
1241 }
1242 } else
1243 next_cmd = 0;
1244
1245 cp = av[i];
1246 if (*cp == ';' || *cp == '&' || *cp == '|')
1247 is_cmd = 1;
1248
1249 #ifdef check_cwd_debug
1250 fprintf(stderr, "av[%d] == %s '%s'",
1251 i, (is_cmd) ? "cmd" : "arg", av[i]);
1252 #endif
1253 if (is_cmd != 0) {
1254 if (*cp == '(' || *cp == '{' ||
1255 *cp == ';' || *cp == '&' || *cp == '|') {
1256 do {
1257 ++cp;
1258 } while (*cp == '(' || *cp == '{' ||
1259 *cp == ';' || *cp == '&' || *cp == '|');
1260 if (*cp == '\0') {
1261 next_cmd = 1;
1262 continue;
1263 }
1264 }
1265 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1266 #ifdef check_cwd_debug
1267 fprintf(stderr, " == cd, done.\n");
1268 #endif
1269 return NULL;
1270 }
1271 for (mp = make; *mp != NULL; ++mp) {
1272 n = strlen(*mp);
1273 if (strcmp(cp, *mp) == 0) {
1274 #ifdef check_cwd_debug
1275 fprintf(stderr, " %s == '%s', chdir(%s)\n",
1276 cp, *mp, cur_dir);
1277 #endif
1278 return cur_dir;
1279 }
1280 }
1281 }
1282 #ifdef check_cwd_debug
1283 fprintf(stderr, "\n");
1284 #endif
1285 }
1286 return NULL;
1287 }
1288
1289 char *
1290 Check_Cwd_Cmd(const char *cmd)
1291 {
1292 char *cp, *bp;
1293 char **av;
1294 int ac;
1295
1296 if (Check_Cwd_Off)
1297 return NULL;
1298
1299 if (cmd) {
1300 av = brk_string(cmd, &ac, TRUE, &bp);
1301 #ifdef check_cwd_debug
1302 fprintf(stderr, "splitting: '%s' -> %d words\n",
1303 cmd, ac);
1304 #endif
1305 } else {
1306 ac = 0;
1307 av = NULL;
1308 bp = NULL;
1309 }
1310 cp = Check_Cwd_av(ac, av, 1);
1311 if (bp) {
1312 free(av);
1313 free(bp);
1314 }
1315 return cp;
1316 }
1317
1318 void
1319 Check_Cwd(const char **argv)
1320 {
1321 char *cp;
1322 int ac;
1323
1324 if (Check_Cwd_Off)
1325 return;
1326
1327 for (ac = 0; argv[ac] != NULL; ++ac)
1328 /* NOTHING */;
1329 if (ac == 3 && *argv[1] == '-') {
1330 cp = Check_Cwd_Cmd(argv[2]);
1331 } else {
1332 cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1333 }
1334 if (cp) {
1335 chdir(cp);
1336 }
1337 }
1338
1339 /*-
1340 * Cmd_Exec --
1341 * Execute the command in cmd, and return the output of that command
1342 * in a string.
1343 *
1344 * Results:
1345 * A string containing the output of the command, or the empty string
1346 * If err is not NULL, it contains the reason for the command failure
1347 *
1348 * Side Effects:
1349 * The string must be freed by the caller.
1350 */
1351 char *
1352 Cmd_Exec(const char *cmd, const char **err)
1353 {
1354 const char *args[4]; /* Args for invoking the shell */
1355 int fds[2]; /* Pipe streams */
1356 int cpid; /* Child PID */
1357 int pid; /* PID from wait() */
1358 char *res; /* result */
1359 int status; /* command exit status */
1360 Buffer buf; /* buffer to store the result */
1361 char *cp;
1362 int cc;
1363
1364
1365 *err = NULL;
1366
1367 if (!shellName)
1368 Shell_Init();
1369 /*
1370 * Set up arguments for shell
1371 */
1372 args[0] = shellName;
1373 args[1] = "-c";
1374 args[2] = cmd;
1375 args[3] = NULL;
1376
1377 /*
1378 * Open a pipe for fetching its output
1379 */
1380 if (pipe(fds) == -1) {
1381 *err = "Couldn't create pipe for \"%s\"";
1382 goto bad;
1383 }
1384
1385 /*
1386 * Fork
1387 */
1388 switch (cpid = vfork()) {
1389 case 0:
1390 /*
1391 * Close input side of pipe
1392 */
1393 (void)close(fds[0]);
1394
1395 /*
1396 * Duplicate the output stream to the shell's output, then
1397 * shut the extra thing down. Note we don't fetch the error
1398 * stream...why not? Why?
1399 */
1400 (void)dup2(fds[1], 1);
1401 (void)close(fds[1]);
1402
1403 (void)execv(shellPath, UNCONST(args));
1404 _exit(1);
1405 /*NOTREACHED*/
1406
1407 case -1:
1408 *err = "Couldn't exec \"%s\"";
1409 goto bad;
1410
1411 default:
1412 /*
1413 * No need for the writing half
1414 */
1415 (void)close(fds[1]);
1416
1417 buf = Buf_Init(MAKE_BSIZE);
1418
1419 do {
1420 char result[BUFSIZ];
1421 cc = read(fds[0], result, sizeof(result));
1422 if (cc > 0)
1423 Buf_AddBytes(buf, cc, (Byte *)result);
1424 }
1425 while (cc > 0 || (cc == -1 && errno == EINTR));
1426
1427 /*
1428 * Close the input side of the pipe.
1429 */
1430 (void)close(fds[0]);
1431
1432 /*
1433 * Wait for the process to exit.
1434 */
1435 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1436 continue;
1437
1438 res = (char *)Buf_GetAll(buf, &cc);
1439 Buf_Destroy(buf, FALSE);
1440
1441 if (cc == 0)
1442 *err = "Couldn't read shell's output for \"%s\"";
1443
1444 if (status)
1445 *err = "\"%s\" returned non-zero status";
1446
1447 /*
1448 * Null-terminate the result, convert newlines to spaces and
1449 * install it in the variable.
1450 */
1451 res[cc] = '\0';
1452 cp = &res[cc];
1453
1454 if (cc > 0 && *--cp == '\n') {
1455 /*
1456 * A final newline is just stripped
1457 */
1458 *cp-- = '\0';
1459 }
1460 while (cp >= res) {
1461 if (*cp == '\n') {
1462 *cp = ' ';
1463 }
1464 cp--;
1465 }
1466 break;
1467 }
1468 return res;
1469 bad:
1470 res = emalloc(1);
1471 *res = '\0';
1472 return res;
1473 }
1474
1475 /*-
1476 * Error --
1477 * Print an error message given its format.
1478 *
1479 * Results:
1480 * None.
1481 *
1482 * Side Effects:
1483 * The message is printed.
1484 */
1485 /* VARARGS */
1486 void
1487 Error(const char *fmt, ...)
1488 {
1489 va_list ap;
1490
1491 va_start(ap, fmt);
1492 fprintf(stderr, "%s: ", progname);
1493 (void)vfprintf(stderr, fmt, ap);
1494 va_end(ap);
1495 (void)fprintf(stderr, "\n");
1496 (void)fflush(stderr);
1497 }
1498
1499 /*-
1500 * Fatal --
1501 * Produce a Fatal error message. If jobs are running, waits for them
1502 * to finish.
1503 *
1504 * Results:
1505 * None
1506 *
1507 * Side Effects:
1508 * The program exits
1509 */
1510 /* VARARGS */
1511 void
1512 Fatal(const char *fmt, ...)
1513 {
1514 va_list ap;
1515
1516 va_start(ap, fmt);
1517 if (jobsRunning)
1518 Job_Wait();
1519
1520 (void)vfprintf(stderr, fmt, ap);
1521 va_end(ap);
1522 (void)fprintf(stderr, "\n");
1523 (void)fflush(stderr);
1524
1525 PrintOnError(NULL);
1526
1527 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1528 Targ_PrintGraph(2);
1529 Trace_Log(MAKEERROR, 0);
1530 exit(2); /* Not 1 so -q can distinguish error */
1531 }
1532
1533 /*
1534 * Punt --
1535 * Major exception once jobs are being created. Kills all jobs, prints
1536 * a message and exits.
1537 *
1538 * Results:
1539 * None
1540 *
1541 * Side Effects:
1542 * All children are killed indiscriminately and the program Lib_Exits
1543 */
1544 /* VARARGS */
1545 void
1546 Punt(const char *fmt, ...)
1547 {
1548 va_list ap;
1549
1550 va_start(ap, fmt);
1551 (void)fprintf(stderr, "%s: ", progname);
1552 (void)vfprintf(stderr, fmt, ap);
1553 va_end(ap);
1554 (void)fprintf(stderr, "\n");
1555 (void)fflush(stderr);
1556
1557 PrintOnError(NULL);
1558
1559 DieHorribly();
1560 }
1561
1562 /*-
1563 * DieHorribly --
1564 * Exit without giving a message.
1565 *
1566 * Results:
1567 * None
1568 *
1569 * Side Effects:
1570 * A big one...
1571 */
1572 void
1573 DieHorribly(void)
1574 {
1575 if (jobsRunning)
1576 Job_AbortAll();
1577 if (DEBUG(GRAPH2))
1578 Targ_PrintGraph(2);
1579 Trace_Log(MAKEERROR, 0);
1580 exit(2); /* Not 1, so -q can distinguish error */
1581 }
1582
1583 /*
1584 * Finish --
1585 * Called when aborting due to errors in child shell to signal
1586 * abnormal exit.
1587 *
1588 * Results:
1589 * None
1590 *
1591 * Side Effects:
1592 * The program exits
1593 */
1594 void
1595 Finish(int errors)
1596 /* number of errors encountered in Make_Make */
1597 {
1598 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1599 }
1600
1601 /*
1602 * emalloc --
1603 * malloc, but die on error.
1604 */
1605 void *
1606 emalloc(size_t len)
1607 {
1608 void *p;
1609
1610 if ((p = malloc(len)) == NULL)
1611 enomem();
1612 return(p);
1613 }
1614
1615 /*
1616 * estrdup --
1617 * strdup, but die on error.
1618 */
1619 char *
1620 estrdup(const char *str)
1621 {
1622 char *p;
1623
1624 if ((p = strdup(str)) == NULL)
1625 enomem();
1626 return(p);
1627 }
1628
1629 /*
1630 * erealloc --
1631 * realloc, but die on error.
1632 */
1633 void *
1634 erealloc(void *ptr, size_t size)
1635 {
1636 if ((ptr = realloc(ptr, size)) == NULL)
1637 enomem();
1638 return(ptr);
1639 }
1640
1641 /*
1642 * enomem --
1643 * die when out of memory.
1644 */
1645 void
1646 enomem(void)
1647 {
1648 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
1649 exit(2);
1650 }
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
1732 if (s)
1733 printf("%s", s);
1734
1735 printf("\n%s: stopped in %s\n", progname, curdir);
1736 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1737 sizeof(tmp) - 1);
1738 s = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1739 if (s && *s)
1740 printf("%s", s);
1741 }
1742
1743 void
1744 Main_ExportMAKEFLAGS(Boolean first)
1745 {
1746 static int once = 1;
1747 char tmp[64];
1748 char *s;
1749
1750 if (once != first)
1751 return;
1752 once = 0;
1753
1754 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1755 sizeof(tmp));
1756 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1757 if (s && *s) {
1758 #ifdef POSIX
1759 setenv("MAKEFLAGS", s, 1);
1760 #else
1761 setenv("MAKE", s, 1);
1762 #endif
1763 }
1764 }
1765