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