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