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