main.c revision 1.47 1 /* $NetBSD: main.c,v 1.47 1999/08/02 17:23:58 hubertf 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.47 1999/08/02 17:23:58 hubertf 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.47 1999/08/02 17:23:58 hubertf 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 Boolean mkIncPath; /* -m flag */
141 static Boolean jobsRunning; /* TRUE if the jobs might be running */
142
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
151 /*-
152 * MainParseArgs --
153 * Parse a given argument vector. Called from main() and from
154 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
155 *
156 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
157 *
158 * Results:
159 * None
160 *
161 * Side Effects:
162 * Various global and local flags will be set depending on the flags
163 * given
164 */
165 static void
166 MainParseArgs(argc, argv)
167 int argc;
168 char **argv;
169 {
170 extern int optind;
171 extern char *optarg;
172 char *p;
173 int c;
174 int forceJobs = 0;
175
176 optind = 1; /* since we're called more than once */
177 #ifdef REMOTE
178 # define OPTFLAGS "BD:I:L:PSV:d:ef:ij:km:nqrst"
179 #else
180 # define OPTFLAGS "BD:I:PSV:d:ef:ij:km:nqrst"
181 #endif
182 rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
183 switch(c) {
184 case 'D':
185 Var_Set(optarg, "1", VAR_GLOBAL);
186 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
187 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
188 break;
189 case 'I':
190 Parse_AddIncludeDir(optarg);
191 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
192 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
193 break;
194 case 'V':
195 printVars = TRUE;
196 (void)Lst_AtEnd(variables, (ClientData)optarg);
197 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
198 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
199 break;
200 case 'B':
201 compatMake = TRUE;
202 break;
203 #ifdef REMOTE
204 case 'L':
205 maxLocal = strtol(optarg, &p, 0);
206 if (*p != '\0' || maxLocal < 1) {
207 (void) fprintf(stderr, "make: illegal argument to -L -- must be positive integer!\n");
208 exit(1);
209 }
210 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
211 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
212 break;
213 #endif
214 case 'P':
215 usePipes = FALSE;
216 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
217 break;
218 case 'S':
219 keepgoing = FALSE;
220 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
221 break;
222 case 'd': {
223 char *modules = optarg;
224
225 for (; *modules; ++modules)
226 switch (*modules) {
227 case 'A':
228 debug = ~0;
229 break;
230 case 'a':
231 debug |= DEBUG_ARCH;
232 break;
233 case 'c':
234 debug |= DEBUG_COND;
235 break;
236 case 'd':
237 debug |= DEBUG_DIR;
238 break;
239 case 'f':
240 debug |= DEBUG_FOR;
241 break;
242 case 'g':
243 if (modules[1] == '1') {
244 debug |= DEBUG_GRAPH1;
245 ++modules;
246 }
247 else if (modules[1] == '2') {
248 debug |= DEBUG_GRAPH2;
249 ++modules;
250 }
251 break;
252 case 'j':
253 debug |= DEBUG_JOB;
254 break;
255 case 'm':
256 debug |= DEBUG_MAKE;
257 break;
258 case 's':
259 debug |= DEBUG_SUFF;
260 break;
261 case 't':
262 debug |= DEBUG_TARG;
263 break;
264 case 'v':
265 debug |= DEBUG_VAR;
266 break;
267 default:
268 (void)fprintf(stderr,
269 "make: illegal argument to d option -- %c\n",
270 *modules);
271 usage();
272 }
273 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
274 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
275 break;
276 }
277 case 'e':
278 checkEnvFirst = TRUE;
279 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
280 break;
281 case 'f':
282 (void)Lst_AtEnd(makefiles, (ClientData)optarg);
283 break;
284 case 'i':
285 ignoreErrors = TRUE;
286 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
287 break;
288 case 'j':
289 forceJobs = TRUE;
290 maxJobs = strtol(optarg, &p, 0);
291 if (*p != '\0' || maxJobs < 1) {
292 (void) fprintf(stderr, "make: illegal argument to -j -- must be positive integer!\n");
293 exit(1);
294 }
295 #ifndef REMOTE
296 maxLocal = maxJobs;
297 #endif
298 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
299 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
300 break;
301 case 'k':
302 keepgoing = TRUE;
303 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
304 break;
305 case 'm':
306 mkIncPath = TRUE;
307 (void) Dir_AddDir(sysIncPath, optarg);
308 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
309 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
310 break;
311 case 'n':
312 noExecute = TRUE;
313 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
314 break;
315 case 'q':
316 queryFlag = TRUE;
317 /* Kind of nonsensical, wot? */
318 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
319 break;
320 case 'r':
321 noBuiltins = TRUE;
322 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
323 break;
324 case 's':
325 beSilent = TRUE;
326 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
327 break;
328 case 't':
329 touchFlag = TRUE;
330 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
331 break;
332 default:
333 case '?':
334 usage();
335 }
336 }
337
338 /*
339 * Be compatible if user did not specify -j and did not explicitly
340 * turned compatibility on
341 */
342 if (!compatMake && !forceJobs)
343 compatMake = TRUE;
344
345 oldVars = TRUE;
346
347 /*
348 * See if the rest of the arguments are variable assignments and
349 * perform them if so. Else take them to be targets and stuff them
350 * on the end of the "create" list.
351 */
352 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
353 if (Parse_IsVar(*argv))
354 Parse_DoVar(*argv, VAR_CMD);
355 else {
356 if (!**argv)
357 Punt("illegal (null) argument.");
358 if (**argv == '-') {
359 if ((*argv)[1])
360 optind = 0; /* -flag... */
361 else
362 optind = 1; /* - */
363 goto rearg;
364 }
365 (void)Lst_AtEnd(create, (ClientData)estrdup(*argv));
366 }
367 }
368
369 /*-
370 * Main_ParseArgLine --
371 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
372 * is encountered and by main() when reading the .MAKEFLAGS envariable.
373 * Takes a line of arguments and breaks it into its
374 * component words and passes those words and the number of them to the
375 * MainParseArgs function.
376 * The line should have all its leading whitespace removed.
377 *
378 * Results:
379 * None
380 *
381 * Side Effects:
382 * Only those that come from the various arguments.
383 */
384 void
385 Main_ParseArgLine(line)
386 char *line; /* Line to fracture */
387 {
388 char **argv; /* Manufactured argument vector */
389 int argc; /* Number of arguments in argv */
390 char *args; /* Space used by the args */
391 char *buf, *p1;
392 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
393
394 if (line == NULL)
395 return;
396 for (; *line == ' '; ++line)
397 continue;
398 if (!*line)
399 return;
400
401 buf = emalloc(strlen(line) + strlen(argv0) + 2);
402 (void)sprintf(buf, "%s %s", argv0, line);
403 if (p1)
404 free(p1);
405
406 argv = brk_string(buf, &argc, TRUE, &args);
407 free(buf);
408 MainParseArgs(argc, argv);
409
410 free(args);
411 free(argv);
412 }
413
414 char *
415 chdir_verify_path(path, obpath)
416 char *path;
417 char *obpath;
418 {
419 struct stat sb;
420
421 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
422 if (chdir(path)) {
423 (void)fprintf(stderr, "make warning: %s: %s.\n",
424 path, strerror(errno));
425 return 0;
426 }
427 else {
428 if (path[0] != '/') {
429 (void) snprintf(obpath, MAXPATHLEN, "%s/%s",
430 curdir, path);
431 return obpath;
432 }
433 else
434 return path;
435 }
436 }
437
438 return 0;
439 }
440
441
442 /*-
443 * main --
444 * The main function, for obvious reasons. Initializes variables
445 * and a few modules, then parses the arguments give it in the
446 * environment and on the command line. Reads the system makefile
447 * followed by either Makefile, makefile or the file given by the
448 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
449 * flags it has received by then uses either the Make or the Compat
450 * module to create the initial list of targets.
451 *
452 * Results:
453 * If -q was given, exits -1 if anything was out-of-date. Else it exits
454 * 0.
455 *
456 * Side Effects:
457 * The program exits when done. Targets are created. etc. etc. etc.
458 */
459 int
460 main(argc, argv)
461 int argc;
462 char **argv;
463 {
464 Lst targs; /* target nodes to create -- passed to Make_Init */
465 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
466 struct stat sb, sa;
467 char *p, *p1, *path, *pathp, *pwd;
468 char mdpath[MAXPATHLEN + 1];
469 char obpath[MAXPATHLEN + 1];
470 char cdpath[MAXPATHLEN + 1];
471 char *machine = getenv("MACHINE");
472 char *machine_arch = getenv("MACHINE_ARCH");
473 Lst sysMkPath; /* Path of sys.mk */
474 char *cp = NULL, *start;
475 /* avoid faults on read-only strings */
476 static char syspath[] = _PATH_DEFSYSPATH;
477
478 #ifdef RLIMIT_NOFILE
479 /*
480 * get rid of resource limit on file descriptors
481 */
482 {
483 struct rlimit rl;
484 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
485 rl.rlim_cur != rl.rlim_max) {
486 rl.rlim_cur = rl.rlim_max;
487 (void) setrlimit(RLIMIT_NOFILE, &rl);
488 }
489 }
490 #endif
491 /*
492 * Find where we are and take care of PWD for the automounter...
493 * All this code is so that we know where we are when we start up
494 * on a different machine with pmake.
495 */
496 curdir = cdpath;
497 if (getcwd(curdir, MAXPATHLEN) == NULL) {
498 (void)fprintf(stderr, "make: %s.\n", strerror(errno));
499 exit(2);
500 }
501
502 if (stat(curdir, &sa) == -1) {
503 (void)fprintf(stderr, "make: %s: %s.\n",
504 curdir, strerror(errno));
505 exit(2);
506 }
507
508 if ((pwd = getenv("PWD")) != NULL) {
509 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
510 sa.st_dev == sb.st_dev)
511 (void) strcpy(curdir, pwd);
512 }
513
514 /*
515 * Get the name of this type of MACHINE from utsname
516 * so we can share an executable for similar machines.
517 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
518 *
519 * Note that both MACHINE and MACHINE_ARCH are decided at
520 * run-time.
521 */
522 if (!machine) {
523 #ifndef MAKE_BOOTSTRAP
524 struct utsname utsname;
525
526 if (uname(&utsname) == -1) {
527 perror("make: uname");
528 exit(2);
529 }
530 machine = utsname.machine;
531 #else
532 machine = MACHINE;
533 #endif
534 }
535
536 if (!machine_arch) {
537 #ifndef MACHINE_ARCH
538 #ifdef __ARCHITECTURE__
539 machine_arch = __ARCHITECTURE__;
540 #else
541 machine_arch = "unknown"; /* XXX: no uname -p yet */
542 #endif
543 #else
544 machine_arch = MACHINE_ARCH;
545 #endif
546 }
547
548 /*
549 * If the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
550 * exists, change into it and build there. (If a .${MACHINE} suffix
551 * exists, use that directory instead).
552 * Otherwise check MAKEOBJDIRPREFIX`cwd` (or by default,
553 * _PATH_OBJDIRPREFIX`cwd`) and build there if it exists.
554 * If all fails, use the current directory to build.
555 *
556 * Once things are initted,
557 * have to add the original directory to the search path,
558 * and modify the paths for the Makefiles apropriately. The
559 * current directory is also placed as a variable for make scripts.
560 */
561 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
562 if (!(path = getenv("MAKEOBJDIR"))) {
563 path = _PATH_OBJDIR;
564 pathp = _PATH_OBJDIRPREFIX;
565 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
566 path, machine);
567 if (!(objdir = chdir_verify_path(mdpath, obpath)))
568 if (!(objdir=chdir_verify_path(path, obpath))) {
569 (void) snprintf(mdpath, MAXPATHLEN,
570 "%s%s", pathp, curdir);
571 if (!(objdir=chdir_verify_path(mdpath,
572 obpath)))
573 objdir = curdir;
574 }
575 }
576 else if (!(objdir = chdir_verify_path(path, obpath)))
577 objdir = curdir;
578 }
579 else {
580 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
581 if (!(objdir = chdir_verify_path(mdpath, obpath)))
582 objdir = curdir;
583 }
584
585 setenv("PWD", objdir, 1);
586
587 create = Lst_Init(FALSE);
588 makefiles = Lst_Init(FALSE);
589 printVars = FALSE;
590 variables = Lst_Init(FALSE);
591 beSilent = FALSE; /* Print commands as executed */
592 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
593 noExecute = FALSE; /* Execute all commands */
594 keepgoing = FALSE; /* Stop on error */
595 allPrecious = FALSE; /* Remove targets when interrupted */
596 queryFlag = FALSE; /* This is not just a check-run */
597 noBuiltins = FALSE; /* Read the built-in rules */
598 touchFlag = FALSE; /* Actually update targets */
599 usePipes = TRUE; /* Catch child output in pipes */
600 debug = 0; /* No debug verbosity, please. */
601 jobsRunning = FALSE;
602
603 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
604 #ifdef REMOTE
605 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
606 #else
607 maxJobs = maxLocal;
608 #endif
609 compatMake = FALSE; /* No compat mode */
610
611
612 /*
613 * Initialize the parsing, directory and variable modules to prepare
614 * for the reading of inclusion paths and variable settings on the
615 * command line
616 */
617
618 /*
619 * Initialize directory structures so -I flags can be processed
620 * correctly, if we have a different objdir, then let the directory
621 * know our curdir.
622 */
623 Dir_Init(curdir != objdir ? curdir : NULL);
624 Parse_Init(); /* Need to initialize the paths of #include
625 * directories */
626 Var_Init(); /* As well as the lists of variables for
627 * parsing arguments */
628 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
629 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
630
631 /*
632 * Initialize various variables.
633 * MAKE also gets this name, for compatibility
634 * .MAKEFLAGS gets set to the empty string just in case.
635 * MFLAGS also gets initialized empty, for compatibility.
636 */
637 Var_Set("MAKE", argv[0], VAR_GLOBAL);
638 Var_Set(".MAKE", argv[0], VAR_GLOBAL);
639 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
640 Var_Set("MFLAGS", "", VAR_GLOBAL);
641 Var_Set("MACHINE", machine, VAR_GLOBAL);
642 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
643
644 /*
645 * First snag any flags out of the MAKE environment variable.
646 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
647 * in a different format).
648 */
649 #ifdef POSIX
650 Main_ParseArgLine(getenv("MAKEFLAGS"));
651 #else
652 Main_ParseArgLine(getenv("MAKE"));
653 #endif
654
655 MainParseArgs(argc, argv);
656
657 /*
658 * Initialize archive, target and suffix modules in preparation for
659 * parsing the makefile(s)
660 */
661 Arch_Init();
662 Targ_Init();
663 Suff_Init();
664
665 DEFAULT = NILGNODE;
666 (void)time(&now);
667
668 /*
669 * Set up the .TARGETS variable to contain the list of targets to be
670 * created. If none specified, make the variable empty -- the parser
671 * will fill the thing in with the default or .MAIN target.
672 */
673 if (!Lst_IsEmpty(create)) {
674 LstNode ln;
675
676 for (ln = Lst_First(create); ln != NILLNODE;
677 ln = Lst_Succ(ln)) {
678 char *name = (char *)Lst_Datum(ln);
679
680 Var_Append(".TARGETS", name, VAR_GLOBAL);
681 }
682 } else
683 Var_Set(".TARGETS", "", VAR_GLOBAL);
684
685
686 /*
687 * If no user-supplied system path was given (through the -m option)
688 * add the directories from the DEFSYSPATH (more than one may be given
689 * as dir1:...:dirn) to the system include path.
690 */
691 if (!mkIncPath) {
692 for (start = syspath; *start != '\0'; start = cp) {
693 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
694 continue;
695 if (*cp == '\0') {
696 (void) Dir_AddDir(sysIncPath, start);
697 } else {
698 *cp++ = '\0';
699 (void) Dir_AddDir(sysIncPath, start);
700 }
701 }
702 }
703
704 /*
705 * Read in the built-in rules first, followed by the specified
706 * makefile, if it was (makefile != (char *) NULL), or the default
707 * Makefile and makefile, in that order, if it wasn't.
708 */
709 if (!noBuiltins) {
710 LstNode ln;
711
712 sysMkPath = Lst_Init (FALSE);
713 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
714 if (Lst_IsEmpty(sysMkPath))
715 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
716 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
717 if (ln != NILLNODE)
718 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
719 }
720
721 if (!Lst_IsEmpty(makefiles)) {
722 LstNode ln;
723
724 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
725 if (ln != NILLNODE)
726 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
727 } else if (!ReadMakefile("makefile", NULL))
728 (void)ReadMakefile("Makefile", NULL);
729
730 (void)ReadMakefile(".depend", NULL);
731
732 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
733 if (p1)
734 free(p1);
735
736 /* Install all the flags into the MAKE envariable. */
737 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
738 #ifdef POSIX
739 setenv("MAKEFLAGS", p, 1);
740 #else
741 setenv("MAKE", p, 1);
742 #endif
743 if (p1)
744 free(p1);
745
746 /*
747 * For compatibility, look at the directories in the VPATH variable
748 * and add them to the search path, if the variable is defined. The
749 * variable's value is in the same format as the PATH envariable, i.e.
750 * <directory>:<directory>:<directory>...
751 */
752 if (Var_Exists("VPATH", VAR_CMD)) {
753 char *vpath, *path, *cp, savec;
754 /*
755 * GCC stores string constants in read-only memory, but
756 * Var_Subst will want to write this thing, so store it
757 * in an array
758 */
759 static char VPATH[] = "${VPATH}";
760
761 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
762 path = vpath;
763 do {
764 /* skip to end of directory */
765 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
766 continue;
767 /* Save terminator character so know when to stop */
768 savec = *cp;
769 *cp = '\0';
770 /* Add directory to search path */
771 (void) Dir_AddDir(dirSearchPath, path);
772 *cp = savec;
773 path = cp + 1;
774 } while (savec == ':');
775 (void)free((Address)vpath);
776 }
777
778 /*
779 * Now that all search paths have been read for suffixes et al, it's
780 * time to add the default search path to their lists...
781 */
782 Suff_DoPaths();
783
784 /* print the initial graph, if the user requested it */
785 if (DEBUG(GRAPH1))
786 Targ_PrintGraph(1);
787
788 /* print the values of any variables requested by the user */
789 if (printVars) {
790 LstNode ln;
791
792 for (ln = Lst_First(variables); ln != NILLNODE;
793 ln = Lst_Succ(ln)) {
794 char *value = Var_Value((char *)Lst_Datum(ln),
795 VAR_GLOBAL, &p1);
796
797 printf("%s\n", value ? value : "");
798 if (p1)
799 free(p1);
800 }
801 }
802
803 /*
804 * Have now read the entire graph and need to make a list of targets
805 * to create. If none was given on the command line, we consult the
806 * parsing module to find the main target(s) to create.
807 */
808 if (Lst_IsEmpty(create))
809 targs = Parse_MainName();
810 else
811 targs = Targ_FindList(create, TARG_CREATE);
812
813 if (!compatMake && !printVars) {
814 /*
815 * Initialize job module before traversing the graph, now that
816 * any .BEGIN and .END targets have been read. This is done
817 * only if the -q flag wasn't given (to prevent the .BEGIN from
818 * being executed should it exist).
819 */
820 if (!queryFlag) {
821 if (maxLocal == -1)
822 maxLocal = maxJobs;
823 Job_Init(maxJobs, maxLocal);
824 jobsRunning = TRUE;
825 }
826
827 /* Traverse the graph, checking on all the targets */
828 outOfDate = Make_Run(targs);
829 } else if (!printVars) {
830 /*
831 * Compat_Init will take care of creating all the targets as
832 * well as initializing the module.
833 */
834 Compat_Run(targs);
835 }
836
837 Lst_Destroy(targs, NOFREE);
838 Lst_Destroy(variables, NOFREE);
839 Lst_Destroy(makefiles, NOFREE);
840 Lst_Destroy(create, (void (*) __P((ClientData))) free);
841
842 /* print the graph now it's been processed if the user requested it */
843 if (DEBUG(GRAPH2))
844 Targ_PrintGraph(2);
845
846 Suff_End();
847 Targ_End();
848 Arch_End();
849 Var_End();
850 Parse_End();
851 Dir_End();
852 Job_End();
853
854 if (queryFlag && outOfDate)
855 return(1);
856 else
857 return(0);
858 }
859
860 /*-
861 * ReadMakefile --
862 * Open and parse the given makefile.
863 *
864 * Results:
865 * TRUE if ok. FALSE if couldn't open file.
866 *
867 * Side Effects:
868 * lots
869 */
870 static Boolean
871 ReadMakefile(p, q)
872 ClientData p, q;
873 {
874 char *fname = p; /* makefile to read */
875 extern Lst parseIncPath;
876 FILE *stream;
877 char *name, path[MAXPATHLEN + 1];
878
879 if (!strcmp(fname, "-")) {
880 Parse_File("(stdin)", stdin);
881 Var_Set("MAKEFILE", "", VAR_GLOBAL);
882 } else {
883 if ((stream = fopen(fname, "r")) != NULL)
884 goto found;
885 /* if we've chdir'd, rebuild the path name */
886 if (curdir != objdir && *fname != '/') {
887 (void)sprintf(path, "%s/%s", curdir, fname);
888 if ((stream = fopen(path, "r")) != NULL) {
889 fname = path;
890 goto found;
891 }
892 }
893 /* look in -I and system include directories. */
894 name = Dir_FindFile(fname, parseIncPath);
895 if (!name)
896 name = Dir_FindFile(fname, sysIncPath);
897 if (!name || !(stream = fopen(name, "r")))
898 return(FALSE);
899 fname = name;
900 /*
901 * set the MAKEFILE variable desired by System V fans -- the
902 * placement of the setting here means it gets set to the last
903 * makefile specified, as it is set by SysV make.
904 */
905 found: Var_Set("MAKEFILE", fname, VAR_GLOBAL);
906 Parse_File(fname, stream);
907 (void)fclose(stream);
908 }
909 return(TRUE);
910 }
911
912 /*-
913 * Cmd_Exec --
914 * Execute the command in cmd, and return the output of that command
915 * in a string.
916 *
917 * Results:
918 * A string containing the output of the command, or the empty string
919 * If err is not NULL, it contains the reason for the command failure
920 *
921 * Side Effects:
922 * The string must be freed by the caller.
923 */
924 char *
925 Cmd_Exec(cmd, err)
926 char *cmd;
927 char **err;
928 {
929 char *args[4]; /* Args for invoking the shell */
930 int fds[2]; /* Pipe streams */
931 int cpid; /* Child PID */
932 int pid; /* PID from wait() */
933 char *res; /* result */
934 int status; /* command exit status */
935 Buffer buf; /* buffer to store the result */
936 char *cp;
937 int cc;
938
939
940 *err = NULL;
941
942 /*
943 * Set up arguments for shell
944 */
945 args[0] = "sh";
946 args[1] = "-c";
947 args[2] = cmd;
948 args[3] = NULL;
949
950 /*
951 * Open a pipe for fetching its output
952 */
953 if (pipe(fds) == -1) {
954 *err = "Couldn't create pipe for \"%s\"";
955 goto bad;
956 }
957
958 /*
959 * Fork
960 */
961 switch (cpid = vfork()) {
962 case 0:
963 /*
964 * Close input side of pipe
965 */
966 (void) close(fds[0]);
967
968 /*
969 * Duplicate the output stream to the shell's output, then
970 * shut the extra thing down. Note we don't fetch the error
971 * stream...why not? Why?
972 */
973 (void) dup2(fds[1], 1);
974 (void) close(fds[1]);
975
976 (void) execv("/bin/sh", args);
977 _exit(1);
978 /*NOTREACHED*/
979
980 case -1:
981 *err = "Couldn't exec \"%s\"";
982 goto bad;
983
984 default:
985 /*
986 * No need for the writing half
987 */
988 (void) close(fds[1]);
989
990 buf = Buf_Init (MAKE_BSIZE);
991
992 do {
993 char result[BUFSIZ];
994 cc = read(fds[0], result, sizeof(result));
995 if (cc > 0)
996 Buf_AddBytes(buf, cc, (Byte *) result);
997 }
998 while (cc > 0 || (cc == -1 && errno == EINTR));
999
1000 /*
1001 * Close the input side of the pipe.
1002 */
1003 (void) close(fds[0]);
1004
1005 /*
1006 * Wait for the process to exit.
1007 */
1008 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1009 continue;
1010
1011 res = (char *)Buf_GetAll (buf, &cc);
1012 Buf_Destroy (buf, FALSE);
1013
1014 if (cc == 0)
1015 *err = "Couldn't read shell's output for \"%s\"";
1016
1017 if (status)
1018 *err = "\"%s\" returned non-zero status";
1019
1020 /*
1021 * Null-terminate the result, convert newlines to spaces and
1022 * install it in the variable.
1023 */
1024 res[cc] = '\0';
1025 cp = &res[cc];
1026
1027 if (cc > 0 && *--cp == '\n') {
1028 /*
1029 * A final newline is just stripped
1030 */
1031 *cp-- = '\0';
1032 }
1033 while (cp >= res) {
1034 if (*cp == '\n') {
1035 *cp = ' ';
1036 }
1037 cp--;
1038 }
1039 break;
1040 }
1041 return res;
1042 bad:
1043 res = emalloc(1);
1044 *res = '\0';
1045 return res;
1046 }
1047
1048 /*-
1049 * Error --
1050 * Print an error message given its format.
1051 *
1052 * Results:
1053 * None.
1054 *
1055 * Side Effects:
1056 * The message is printed.
1057 */
1058 /* VARARGS */
1059 void
1060 #ifdef __STDC__
1061 Error(char *fmt, ...)
1062 #else
1063 Error(va_alist)
1064 va_dcl
1065 #endif
1066 {
1067 va_list ap;
1068 #ifdef __STDC__
1069 va_start(ap, fmt);
1070 #else
1071 char *fmt;
1072
1073 va_start(ap);
1074 fmt = va_arg(ap, char *);
1075 #endif
1076 (void)vfprintf(stderr, fmt, ap);
1077 va_end(ap);
1078 (void)fprintf(stderr, "\n");
1079 (void)fflush(stderr);
1080 }
1081
1082 /*-
1083 * Fatal --
1084 * Produce a Fatal error message. If jobs are running, waits for them
1085 * to finish.
1086 *
1087 * Results:
1088 * None
1089 *
1090 * Side Effects:
1091 * The program exits
1092 */
1093 /* VARARGS */
1094 void
1095 #ifdef __STDC__
1096 Fatal(char *fmt, ...)
1097 #else
1098 Fatal(va_alist)
1099 va_dcl
1100 #endif
1101 {
1102 va_list ap;
1103 #ifdef __STDC__
1104 va_start(ap, fmt);
1105 #else
1106 char *fmt;
1107
1108 va_start(ap);
1109 fmt = va_arg(ap, char *);
1110 #endif
1111 if (jobsRunning)
1112 Job_Wait();
1113
1114 (void)vfprintf(stderr, fmt, ap);
1115 va_end(ap);
1116 (void)fprintf(stderr, "\n");
1117 (void)fflush(stderr);
1118
1119 if (DEBUG(GRAPH2))
1120 Targ_PrintGraph(2);
1121 exit(2); /* Not 1 so -q can distinguish error */
1122 }
1123
1124 /*
1125 * Punt --
1126 * Major exception once jobs are being created. Kills all jobs, prints
1127 * a message and exits.
1128 *
1129 * Results:
1130 * None
1131 *
1132 * Side Effects:
1133 * All children are killed indiscriminately and the program Lib_Exits
1134 */
1135 /* VARARGS */
1136 void
1137 #ifdef __STDC__
1138 Punt(char *fmt, ...)
1139 #else
1140 Punt(va_alist)
1141 va_dcl
1142 #endif
1143 {
1144 va_list ap;
1145 #ifdef __STDC__
1146 va_start(ap, fmt);
1147 #else
1148 char *fmt;
1149
1150 va_start(ap);
1151 fmt = va_arg(ap, char *);
1152 #endif
1153
1154 (void)fprintf(stderr, "make: ");
1155 (void)vfprintf(stderr, fmt, ap);
1156 va_end(ap);
1157 (void)fprintf(stderr, "\n");
1158 (void)fflush(stderr);
1159
1160 DieHorribly();
1161 }
1162
1163 /*-
1164 * DieHorribly --
1165 * Exit without giving a message.
1166 *
1167 * Results:
1168 * None
1169 *
1170 * Side Effects:
1171 * A big one...
1172 */
1173 void
1174 DieHorribly()
1175 {
1176 if (jobsRunning)
1177 Job_AbortAll();
1178 if (DEBUG(GRAPH2))
1179 Targ_PrintGraph(2);
1180 exit(2); /* Not 1, so -q can distinguish error */
1181 }
1182
1183 /*
1184 * Finish --
1185 * Called when aborting due to errors in child shell to signal
1186 * abnormal exit.
1187 *
1188 * Results:
1189 * None
1190 *
1191 * Side Effects:
1192 * The program exits
1193 */
1194 void
1195 Finish(errors)
1196 int errors; /* number of errors encountered in Make_Make */
1197 {
1198 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1199 }
1200
1201 /*
1202 * emalloc --
1203 * malloc, but die on error.
1204 */
1205 void *
1206 emalloc(len)
1207 size_t len;
1208 {
1209 void *p;
1210
1211 if ((p = malloc(len)) == NULL)
1212 enomem();
1213 return(p);
1214 }
1215
1216 /*
1217 * estrdup --
1218 * strdup, but die on error.
1219 */
1220 char *
1221 estrdup(str)
1222 const char *str;
1223 {
1224 char *p;
1225
1226 if ((p = strdup(str)) == NULL)
1227 enomem();
1228 return(p);
1229 }
1230
1231 /*
1232 * erealloc --
1233 * realloc, but die on error.
1234 */
1235 void *
1236 erealloc(ptr, size)
1237 void *ptr;
1238 size_t size;
1239 {
1240 if ((ptr = realloc(ptr, size)) == NULL)
1241 enomem();
1242 return(ptr);
1243 }
1244
1245 /*
1246 * enomem --
1247 * die when out of memory.
1248 */
1249 void
1250 enomem()
1251 {
1252 (void)fprintf(stderr, "make: %s.\n", strerror(errno));
1253 exit(2);
1254 }
1255
1256 /*
1257 * enunlink --
1258 * Remove a file carefully, avoiding directories.
1259 */
1260 int
1261 eunlink(file)
1262 const char *file;
1263 {
1264 struct stat st;
1265
1266 if (lstat(file, &st) == -1)
1267 return -1;
1268
1269 if (S_ISDIR(st.st_mode)) {
1270 errno = EISDIR;
1271 return -1;
1272 }
1273 return unlink(file);
1274 }
1275
1276 /*
1277 * usage --
1278 * exit with usage message
1279 */
1280 static void
1281 usage()
1282 {
1283 (void)fprintf(stderr,
1284 "usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
1285 [-I directory] [-j max_jobs] [-m directory] [-V variable]\n\
1286 [variable=value] [target ...]\n");
1287 exit(2);
1288 }
1289
1290
1291 int
1292 PrintAddr(a, b)
1293 ClientData a;
1294 ClientData b;
1295 {
1296 printf("%lx ", (unsigned long) a);
1297 return b ? 0 : 0;
1298 }
1299