main.c revision 1.55 1 /* $NetBSD: main.c,v 1.55 2000/04/29 12:15:16 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.55 2000/04/29 12:15:16 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.55 2000/04/29 12:15:16 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 Boolean mkIncPath; /* -m flag */
141 static Boolean jobsRunning; /* TRUE if the jobs might be running */
142
143 static char * Check_Cwd_av __P((int, char **, int));
144 static void MainParseArgs __P((int, char **));
145 char * chdir_verify_path __P((char *, char *));
146 static int ReadMakefile __P((ClientData, ClientData));
147 static void usage __P((void));
148
149 static char *curdir; /* startup directory */
150 static char *objdir; /* where we chdir'ed to */
151 static char *progname; /* the program name */
152
153 /*-
154 * MainParseArgs --
155 * Parse a given argument vector. Called from main() and from
156 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
157 *
158 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
159 *
160 * Results:
161 * None
162 *
163 * Side Effects:
164 * Various global and local flags will be set depending on the flags
165 * given
166 */
167 static void
168 MainParseArgs(argc, argv)
169 int argc;
170 char **argv;
171 {
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 size_t len;
394
395 if (line == NULL)
396 return;
397 for (; *line == ' '; ++line)
398 continue;
399 if (!*line)
400 return;
401
402 buf = emalloc(len = strlen(line) + strlen(argv0) + 2);
403 (void)snprintf(buf, len, "%s %s", argv0, line);
404 if (p1)
405 free(p1);
406
407 argv = brk_string(buf, &argc, TRUE, &args);
408 free(buf);
409 MainParseArgs(argc, argv);
410
411 free(args);
412 free(argv);
413 }
414
415 char *
416 chdir_verify_path(path, obpath)
417 char *path;
418 char *obpath;
419 {
420 struct stat sb;
421
422 if (strchr(path, '$') != 0) {
423 path = Var_Subst(NULL, path, VAR_GLOBAL, 0);
424 }
425 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
426 if (chdir(path)) {
427 (void)fprintf(stderr, "make warning: %s: %s.\n",
428 path, strerror(errno));
429 return 0;
430 }
431 else {
432 if (path[0] != '/') {
433 (void) snprintf(obpath, MAXPATHLEN, "%s/%s",
434 curdir, path);
435 return obpath;
436 }
437 else
438 return path;
439 }
440 }
441
442 return 0;
443 }
444
445
446 /*-
447 * main --
448 * The main function, for obvious reasons. Initializes variables
449 * and a few modules, then parses the arguments give it in the
450 * environment and on the command line. Reads the system makefile
451 * followed by either Makefile, makefile or the file given by the
452 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
453 * flags it has received by then uses either the Make or the Compat
454 * module to create the initial list of targets.
455 *
456 * Results:
457 * If -q was given, exits -1 if anything was out-of-date. Else it exits
458 * 0.
459 *
460 * Side Effects:
461 * The program exits when done. Targets are created. etc. etc. etc.
462 */
463 int
464 main(argc, argv)
465 int argc;
466 char **argv;
467 {
468 Lst targs; /* target nodes to create -- passed to Make_Init */
469 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
470 struct stat sb, sa;
471 char *p, *p1, *path, *pathp, *pwd;
472 char mdpath[MAXPATHLEN + 1];
473 char obpath[MAXPATHLEN + 1];
474 char cdpath[MAXPATHLEN + 1];
475 char *machine = getenv("MACHINE");
476 char *machine_arch = getenv("MACHINE_ARCH");
477 char *syspath = getenv("MAKESYSPATH");
478 Lst sysMkPath; /* Path of sys.mk */
479 char *cp = NULL, *start;
480 /* avoid faults on read-only strings */
481 static char defsyspath[] = _PATH_DEFSYSPATH;
482
483 if ((progname = strrchr(argv[0], '/')) != NULL)
484 progname++;
485 else
486 progname = argv[0];
487 #ifdef RLIMIT_NOFILE
488 /*
489 * get rid of resource limit on file descriptors
490 */
491 {
492 struct rlimit rl;
493 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
494 rl.rlim_cur != rl.rlim_max) {
495 rl.rlim_cur = rl.rlim_max;
496 (void) setrlimit(RLIMIT_NOFILE, &rl);
497 }
498 }
499 #endif
500 /*
501 * Find where we are and take care of PWD for the automounter...
502 * All this code is so that we know where we are when we start up
503 * on a different machine with pmake.
504 */
505 curdir = cdpath;
506 if (getcwd(curdir, MAXPATHLEN) == NULL) {
507 (void)fprintf(stderr, "make: %s.\n", strerror(errno));
508 exit(2);
509 }
510
511 if (stat(curdir, &sa) == -1) {
512 (void)fprintf(stderr, "make: %s: %s.\n",
513 curdir, strerror(errno));
514 exit(2);
515 }
516
517 /*
518 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
519 * since the value of curdir can very depending on how we got
520 * here. Ie sitting at a shell prompt (shell that provides $PWD)
521 * or via subdir.mk in which case its likely a shell which does
522 * not provide it.
523 * So, to stop it breaking this case only, we ignore PWD if
524 * MAKEOBJDIRPREFIX is set.
525 */
526 if ((pwd = getenv("PWD")) != NULL &&
527 getenv("MAKEOBJDIRPREFIX") == NULL) {
528 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
529 sa.st_dev == sb.st_dev)
530 (void) strcpy(curdir, pwd);
531 }
532
533 /*
534 * Get the name of this type of MACHINE from utsname
535 * so we can share an executable for similar machines.
536 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
537 *
538 * Note that both MACHINE and MACHINE_ARCH are decided at
539 * run-time.
540 */
541 if (!machine) {
542 #ifndef MAKE_BOOTSTRAP
543 struct utsname utsname;
544
545 if (uname(&utsname) == -1) {
546 perror("make: uname");
547 exit(2);
548 }
549 machine = utsname.machine;
550 #else
551 machine = MACHINE;
552 #endif
553 }
554
555 if (!machine_arch) {
556 #ifndef MACHINE_ARCH
557 #ifdef __ARCHITECTURE__
558 machine_arch = __ARCHITECTURE__;
559 #else
560 machine_arch = "unknown"; /* XXX: no uname -p yet */
561 #endif
562 #else
563 machine_arch = MACHINE_ARCH;
564 #endif
565 }
566
567 /*
568 * Just in case MAKEOBJDIR wants us to do something tricky.
569 */
570 Var_Init(); /* Initialize the lists of variables for
571 * parsing arguments */
572 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
573 Var_Set("MACHINE", machine, VAR_GLOBAL);
574 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
575
576 /*
577 * If the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
578 * exists, change into it and build there. (If a .${MACHINE} suffix
579 * exists, use that directory instead).
580 * Otherwise check MAKEOBJDIRPREFIX`cwd` (or by default,
581 * _PATH_OBJDIRPREFIX`cwd`) and build there if it exists.
582 * If all fails, use the current directory to build.
583 *
584 * Once things are initted,
585 * have to add the original directory to the search path,
586 * and modify the paths for the Makefiles apropriately. The
587 * current directory is also placed as a variable for make scripts.
588 */
589 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
590 if (!(path = getenv("MAKEOBJDIR"))) {
591 path = _PATH_OBJDIR;
592 pathp = _PATH_OBJDIRPREFIX;
593 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
594 path, machine);
595 if (!(objdir = chdir_verify_path(mdpath, obpath)))
596 if (!(objdir=chdir_verify_path(path, obpath))) {
597 (void) snprintf(mdpath, MAXPATHLEN,
598 "%s%s", pathp, curdir);
599 if (!(objdir=chdir_verify_path(mdpath,
600 obpath)))
601 objdir = curdir;
602 }
603 }
604 else if (!(objdir = chdir_verify_path(path, obpath)))
605 objdir = curdir;
606 }
607 else {
608 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
609 if (!(objdir = chdir_verify_path(mdpath, obpath)))
610 objdir = curdir;
611 }
612
613 setenv("PWD", objdir, 1);
614
615 create = Lst_Init(FALSE);
616 makefiles = Lst_Init(FALSE);
617 printVars = FALSE;
618 variables = Lst_Init(FALSE);
619 beSilent = FALSE; /* Print commands as executed */
620 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
621 noExecute = FALSE; /* Execute all commands */
622 keepgoing = FALSE; /* Stop on error */
623 allPrecious = FALSE; /* Remove targets when interrupted */
624 queryFlag = FALSE; /* This is not just a check-run */
625 noBuiltins = FALSE; /* Read the built-in rules */
626 touchFlag = FALSE; /* Actually update targets */
627 usePipes = TRUE; /* Catch child output in pipes */
628 debug = 0; /* No debug verbosity, please. */
629 jobsRunning = FALSE;
630
631 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
632 #ifdef REMOTE
633 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
634 #else
635 maxJobs = maxLocal;
636 #endif
637 compatMake = FALSE; /* No compat mode */
638
639
640 /*
641 * Initialize the parsing, directory and variable modules to prepare
642 * for the reading of inclusion paths and variable settings on the
643 * command line
644 */
645
646 /*
647 * Initialize directory structures so -I flags can be processed
648 * correctly, if we have a different objdir, then let the directory
649 * know our curdir.
650 */
651 Dir_Init(curdir != objdir ? curdir : NULL);
652 Parse_Init(); /* Need to initialize the paths of #include
653 * directories */
654 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
655
656 /*
657 * Initialize various variables.
658 * MAKE also gets this name, for compatibility
659 * .MAKEFLAGS gets set to the empty string just in case.
660 * MFLAGS also gets initialized empty, for compatibility.
661 */
662 Var_Set("MAKE", argv[0], VAR_GLOBAL);
663 Var_Set(".MAKE", argv[0], VAR_GLOBAL);
664 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
665 Var_Set("MFLAGS", "", VAR_GLOBAL);
666
667 /*
668 * First snag any flags out of the MAKE environment variable.
669 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
670 * in a different format).
671 */
672 #ifdef POSIX
673 Main_ParseArgLine(getenv("MAKEFLAGS"));
674 #else
675 Main_ParseArgLine(getenv("MAKE"));
676 #endif
677
678 MainParseArgs(argc, argv);
679
680 /*
681 * Initialize archive, target and suffix modules in preparation for
682 * parsing the makefile(s)
683 */
684 Arch_Init();
685 Targ_Init();
686 Suff_Init();
687
688 DEFAULT = NILGNODE;
689 (void)time(&now);
690
691 /*
692 * Set up the .TARGETS variable to contain the list of targets to be
693 * created. If none specified, make the variable empty -- the parser
694 * will fill the thing in with the default or .MAIN target.
695 */
696 if (!Lst_IsEmpty(create)) {
697 LstNode ln;
698
699 for (ln = Lst_First(create); ln != NILLNODE;
700 ln = Lst_Succ(ln)) {
701 char *name = (char *)Lst_Datum(ln);
702
703 Var_Append(".TARGETS", name, VAR_GLOBAL);
704 }
705 } else
706 Var_Set(".TARGETS", "", VAR_GLOBAL);
707
708
709 /*
710 * If no user-supplied system path was given (through the -m option)
711 * add the directories from the DEFSYSPATH (more than one may be given
712 * as dir1:...:dirn) to the system include path.
713 */
714 if (!mkIncPath) {
715 if (syspath == NULL || *syspath == '\0')
716 syspath = defsyspath;
717 else
718 syspath = strdup(syspath);
719
720 for (start = syspath; *start != '\0'; start = cp) {
721 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
722 continue;
723 if (*cp == '\0') {
724 (void) Dir_AddDir(sysIncPath, start);
725 } else {
726 *cp++ = '\0';
727 (void) Dir_AddDir(sysIncPath, start);
728 }
729 }
730 if (syspath != defsyspath)
731 free(syspath);
732 }
733
734 /*
735 * Read in the built-in rules first, followed by the specified
736 * makefile, if it was (makefile != (char *) NULL), or the default
737 * Makefile and makefile, in that order, if it wasn't.
738 */
739 if (!noBuiltins) {
740 LstNode ln;
741
742 sysMkPath = Lst_Init (FALSE);
743 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
744 if (Lst_IsEmpty(sysMkPath))
745 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
746 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
747 if (ln != NILLNODE)
748 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
749 }
750
751 if (!Lst_IsEmpty(makefiles)) {
752 LstNode ln;
753
754 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
755 if (ln != NILLNODE)
756 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
757 } else if (!ReadMakefile("makefile", NULL))
758 (void)ReadMakefile("Makefile", NULL);
759
760 (void)ReadMakefile(".depend", NULL);
761
762 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
763 if (p1)
764 free(p1);
765
766 /* Install all the flags into the MAKE envariable. */
767 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
768 #ifdef POSIX
769 setenv("MAKEFLAGS", p, 1);
770 #else
771 setenv("MAKE", p, 1);
772 #endif
773 if (p1)
774 free(p1);
775
776 Check_Cwd_av(0, NULL, 0); /* initialize it */
777
778
779 /*
780 * For compatibility, look at the directories in the VPATH variable
781 * and add them to the search path, if the variable is defined. The
782 * variable's value is in the same format as the PATH envariable, i.e.
783 * <directory>:<directory>:<directory>...
784 */
785 if (Var_Exists("VPATH", VAR_CMD)) {
786 char *vpath, *path, *cp, savec;
787 /*
788 * GCC stores string constants in read-only memory, but
789 * Var_Subst will want to write this thing, so store it
790 * in an array
791 */
792 static char VPATH[] = "${VPATH}";
793
794 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
795 path = vpath;
796 do {
797 /* skip to end of directory */
798 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
799 continue;
800 /* Save terminator character so know when to stop */
801 savec = *cp;
802 *cp = '\0';
803 /* Add directory to search path */
804 (void) Dir_AddDir(dirSearchPath, path);
805 *cp = savec;
806 path = cp + 1;
807 } while (savec == ':');
808 (void)free((Address)vpath);
809 }
810
811 /*
812 * Now that all search paths have been read for suffixes et al, it's
813 * time to add the default search path to their lists...
814 */
815 Suff_DoPaths();
816
817 /*
818 * Propagate attributes through :: dependency lists.
819 */
820 Targ_Propagate();
821
822 /* print the initial graph, if the user requested it */
823 if (DEBUG(GRAPH1))
824 Targ_PrintGraph(1);
825
826 /* print the values of any variables requested by the user */
827 if (printVars) {
828 LstNode ln;
829
830 for (ln = Lst_First(variables); ln != NILLNODE;
831 ln = Lst_Succ(ln)) {
832 char *value = Var_Value((char *)Lst_Datum(ln),
833 VAR_GLOBAL, &p1);
834
835 printf("%s\n", value ? value : "");
836 if (p1)
837 free(p1);
838 }
839 }
840
841 /*
842 * Have now read the entire graph and need to make a list of targets
843 * to create. If none was given on the command line, we consult the
844 * parsing module to find the main target(s) to create.
845 */
846 if (Lst_IsEmpty(create))
847 targs = Parse_MainName();
848 else
849 targs = Targ_FindList(create, TARG_CREATE);
850
851 if (!compatMake && !printVars) {
852 /*
853 * Initialize job module before traversing the graph, now that
854 * any .BEGIN and .END targets have been read. This is done
855 * only if the -q flag wasn't given (to prevent the .BEGIN from
856 * being executed should it exist).
857 */
858 if (!queryFlag) {
859 if (maxLocal == -1)
860 maxLocal = maxJobs;
861 Job_Init(maxJobs, maxLocal);
862 jobsRunning = TRUE;
863 }
864
865 /* Traverse the graph, checking on all the targets */
866 outOfDate = Make_Run(targs);
867 } else if (!printVars) {
868 /*
869 * Compat_Init will take care of creating all the targets as
870 * well as initializing the module.
871 */
872 Compat_Run(targs);
873 }
874
875 #ifdef CLEANUP
876 Lst_Destroy(targs, NOFREE);
877 Lst_Destroy(variables, NOFREE);
878 Lst_Destroy(makefiles, NOFREE);
879 Lst_Destroy(create, (void (*) __P((ClientData))) free);
880 #endif
881
882 /* print the graph now it's been processed if the user requested it */
883 if (DEBUG(GRAPH2))
884 Targ_PrintGraph(2);
885
886 Suff_End();
887 Targ_End();
888 Arch_End();
889 Var_End();
890 Parse_End();
891 Dir_End();
892 Job_End();
893
894 if (queryFlag && outOfDate)
895 return(1);
896 else
897 return(0);
898 }
899
900 /*-
901 * ReadMakefile --
902 * Open and parse the given makefile.
903 *
904 * Results:
905 * TRUE if ok. FALSE if couldn't open file.
906 *
907 * Side Effects:
908 * lots
909 */
910 static Boolean
911 ReadMakefile(p, q)
912 ClientData p, q;
913 {
914 char *fname = p; /* makefile to read */
915 extern Lst parseIncPath;
916 FILE *stream;
917 size_t len = MAXPATHLEN;
918 char *name, *path = emalloc(len);
919
920 if (!strcmp(fname, "-")) {
921 Parse_File("(stdin)", stdin);
922 Var_Set("MAKEFILE", "", VAR_GLOBAL);
923 } else {
924 if ((stream = fopen(fname, "r")) != NULL)
925 goto found;
926 /* if we've chdir'd, rebuild the path name */
927 if (curdir != objdir && *fname != '/') {
928 size_t plen = strlen(curdir) + strlen(fname) + 2;
929 if (len < plen)
930 path = erealloc(path, len = 2 * plen);
931
932 (void)snprintf(path, len, "%s/%s", curdir, fname);
933 if ((stream = fopen(path, "r")) != NULL) {
934 fname = path;
935 goto found;
936 }
937 }
938 /* look in -I and system include directories. */
939 name = Dir_FindFile(fname, parseIncPath);
940 if (!name)
941 name = Dir_FindFile(fname, sysIncPath);
942 if (!name || !(stream = fopen(name, "r"))) {
943 free(path);
944 return(FALSE);
945 }
946 fname = name;
947 /*
948 * set the MAKEFILE variable desired by System V fans -- the
949 * placement of the setting here means it gets set to the last
950 * makefile specified, as it is set by SysV make.
951 */
952 found: Var_Set("MAKEFILE", fname, VAR_GLOBAL);
953 Parse_File(fname, stream);
954 (void)fclose(stream);
955 }
956 free(path);
957 return(TRUE);
958 }
959
960
961 /*
962 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
963 * in situations that would not arrise with ./obj (links or not).
964 * This tends to break things like:
965 *
966 * build:
967 * ${MAKE} includes
968 *
969 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
970 * opposed to an argument) in a command line and if so returns
971 * ${.CURDIR} so caller can chdir() so that the assumptions made by
972 * the Makefile hold true.
973 *
974 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
975 *
976 * The chdir() only happens in the child process, and does nothing if
977 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
978 * should not break anything. Also if NOCHECKMAKECHDIR is set we
979 * do nothing - to ensure historic semantics can be retained.
980 */
981 static int Check_Cwd_Off = 0;
982
983 static char *
984 Check_Cwd_av(ac, av, copy)
985 int ac;
986 char **av;
987 int copy;
988 {
989 static char *make[4];
990 static char *curdir = NULL;
991 char *cp, **mp;
992 int is_cmd, next_cmd;
993 int i;
994 int n;
995
996 if (Check_Cwd_Off)
997 return NULL;
998
999 if (make[0] == NULL) {
1000 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1001 Check_Cwd_Off = 1;
1002 return NULL;
1003 }
1004
1005 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1006 if ((make[0] = strrchr(make[1], '/')) == NULL) {
1007 make[0] = make[1];
1008 make[1] = NULL;
1009 } else
1010 ++make[0];
1011 make[2] = NULL;
1012 curdir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1013 }
1014 if (ac == 0 || av == NULL)
1015 return NULL; /* initialization only */
1016
1017 if (getenv("MAKEOBJDIR") == NULL &&
1018 getenv("MAKEOBJDIRPREFIX") == NULL)
1019 return NULL;
1020
1021
1022 next_cmd = 1;
1023 for (i = 0; i < ac; ++i) {
1024 is_cmd = next_cmd;
1025
1026 n = strlen(av[i]);
1027 cp = &(av[i])[n - 1];
1028 if (strspn(av[i], "|&;") == n) {
1029 next_cmd = 1;
1030 continue;
1031 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1032 next_cmd = 1;
1033 if (copy) {
1034 do {
1035 *cp-- = '\0';
1036 } while (*cp == ';' || *cp == '&' || *cp == '|' ||
1037 *cp == ')' || *cp == '}') ;
1038 } else {
1039 /*
1040 * XXX this should not happen.
1041 */
1042 fprintf(stderr, "WARNING: raw arg ends in shell meta '%s'\n",
1043 av[i]);
1044 }
1045 } else
1046 next_cmd = 0;
1047
1048 cp = av[i];
1049 if (*cp == ';' || *cp == '&' || *cp == '|')
1050 is_cmd = 1;
1051
1052 #ifdef check_cwd_debug
1053 fprintf(stderr, "av[%d] == %s '%s'",
1054 i, (is_cmd) ? "cmd" : "arg", av[i]);
1055 #endif
1056 if (is_cmd != 0) {
1057 while (*cp == '(' || *cp == '{' ||
1058 *cp == ';' || *cp == '&' || *cp == '|')
1059 ++cp;
1060 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1061 #ifdef check_cwd_debug
1062 fprintf(stderr, " == cd, done.\n");
1063 #endif
1064 return NULL;
1065 }
1066 for (mp = make; *mp != NULL; ++mp) {
1067 n = strlen(*mp);
1068 if (strcmp(cp, *mp) == 0) {
1069 #ifdef check_cwd_debug
1070 fprintf(stderr, " %s == '%s', chdir(%s)\n",
1071 cp, *mp, curdir);
1072 #endif
1073 return curdir;
1074 }
1075 }
1076 }
1077 #ifdef check_cwd_debug
1078 fprintf(stderr, "\n");
1079 #endif
1080 }
1081 return NULL;
1082 }
1083
1084 char *
1085 Check_Cwd_Cmd(cmd)
1086 char *cmd;
1087 {
1088 char *cp, *bp, **av;
1089 int ac;
1090
1091 if (Check_Cwd_Off)
1092 return NULL;
1093
1094 if (cmd) {
1095 av = brk_string(cmd, &ac, TRUE, &bp);
1096 #ifdef check_cwd_debug
1097 fprintf(stderr, "splitting: '%s' -> %d words\n",
1098 cmd, ac);
1099 #endif
1100 } else {
1101 ac = 0;
1102 av = NULL;
1103 bp = NULL;
1104 }
1105 cp = Check_Cwd_av(ac, av, 1);
1106 if (bp) {
1107 free(av);
1108 free(bp);
1109 }
1110 return cp;
1111 }
1112
1113 void
1114 Check_Cwd(argv)
1115 char **argv;
1116 {
1117 char *cp;
1118 int ac;
1119
1120 if (Check_Cwd_Off)
1121 return;
1122
1123 for (ac = 0; argv[ac] != NULL; ++ac)
1124 /* NOTHING */;
1125 if (ac == 3 && *argv[1] == '-') {
1126 cp = Check_Cwd_Cmd(argv[2]);
1127 } else {
1128 cp = Check_Cwd_av(ac, argv, 0);
1129 }
1130 if (cp) {
1131 chdir(cp);
1132 }
1133 }
1134
1135 /*-
1136 * Cmd_Exec --
1137 * Execute the command in cmd, and return the output of that command
1138 * in a string.
1139 *
1140 * Results:
1141 * A string containing the output of the command, or the empty string
1142 * If err is not NULL, it contains the reason for the command failure
1143 *
1144 * Side Effects:
1145 * The string must be freed by the caller.
1146 */
1147 char *
1148 Cmd_Exec(cmd, err)
1149 char *cmd;
1150 char **err;
1151 {
1152 char *args[4]; /* Args for invoking the shell */
1153 int fds[2]; /* Pipe streams */
1154 int cpid; /* Child PID */
1155 int pid; /* PID from wait() */
1156 char *res; /* result */
1157 int status; /* command exit status */
1158 Buffer buf; /* buffer to store the result */
1159 char *cp;
1160 int cc;
1161
1162
1163 *err = NULL;
1164
1165 /*
1166 * Set up arguments for shell
1167 */
1168 args[0] = "sh";
1169 args[1] = "-c";
1170 args[2] = cmd;
1171 args[3] = NULL;
1172
1173 /*
1174 * Open a pipe for fetching its output
1175 */
1176 if (pipe(fds) == -1) {
1177 *err = "Couldn't create pipe for \"%s\"";
1178 goto bad;
1179 }
1180
1181 /*
1182 * Fork
1183 */
1184 switch (cpid = vfork()) {
1185 case 0:
1186 /*
1187 * Close input side of pipe
1188 */
1189 (void) close(fds[0]);
1190
1191 /*
1192 * Duplicate the output stream to the shell's output, then
1193 * shut the extra thing down. Note we don't fetch the error
1194 * stream...why not? Why?
1195 */
1196 (void) dup2(fds[1], 1);
1197 (void) close(fds[1]);
1198
1199 (void) execv("/bin/sh", args);
1200 _exit(1);
1201 /*NOTREACHED*/
1202
1203 case -1:
1204 *err = "Couldn't exec \"%s\"";
1205 goto bad;
1206
1207 default:
1208 /*
1209 * No need for the writing half
1210 */
1211 (void) close(fds[1]);
1212
1213 buf = Buf_Init (MAKE_BSIZE);
1214
1215 do {
1216 char result[BUFSIZ];
1217 cc = read(fds[0], result, sizeof(result));
1218 if (cc > 0)
1219 Buf_AddBytes(buf, cc, (Byte *) result);
1220 }
1221 while (cc > 0 || (cc == -1 && errno == EINTR));
1222
1223 /*
1224 * Close the input side of the pipe.
1225 */
1226 (void) close(fds[0]);
1227
1228 /*
1229 * Wait for the process to exit.
1230 */
1231 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1232 continue;
1233
1234 res = (char *)Buf_GetAll (buf, &cc);
1235 Buf_Destroy (buf, FALSE);
1236
1237 if (cc == 0)
1238 *err = "Couldn't read shell's output for \"%s\"";
1239
1240 if (status)
1241 *err = "\"%s\" returned non-zero status";
1242
1243 /*
1244 * Null-terminate the result, convert newlines to spaces and
1245 * install it in the variable.
1246 */
1247 res[cc] = '\0';
1248 cp = &res[cc];
1249
1250 if (cc > 0 && *--cp == '\n') {
1251 /*
1252 * A final newline is just stripped
1253 */
1254 *cp-- = '\0';
1255 }
1256 while (cp >= res) {
1257 if (*cp == '\n') {
1258 *cp = ' ';
1259 }
1260 cp--;
1261 }
1262 break;
1263 }
1264 return res;
1265 bad:
1266 res = emalloc(1);
1267 *res = '\0';
1268 return res;
1269 }
1270
1271 /*-
1272 * Error --
1273 * Print an error message given its format.
1274 *
1275 * Results:
1276 * None.
1277 *
1278 * Side Effects:
1279 * The message is printed.
1280 */
1281 /* VARARGS */
1282 void
1283 #ifdef __STDC__
1284 Error(char *fmt, ...)
1285 #else
1286 Error(va_alist)
1287 va_dcl
1288 #endif
1289 {
1290 va_list ap;
1291 #ifdef __STDC__
1292 va_start(ap, fmt);
1293 #else
1294 char *fmt;
1295
1296 va_start(ap);
1297 fmt = va_arg(ap, char *);
1298 #endif
1299 fprintf(stderr, "%s: ", progname);
1300 (void)vfprintf(stderr, fmt, ap);
1301 va_end(ap);
1302 (void)fprintf(stderr, "\n");
1303 (void)fflush(stderr);
1304 }
1305
1306 /*-
1307 * Fatal --
1308 * Produce a Fatal error message. If jobs are running, waits for them
1309 * to finish.
1310 *
1311 * Results:
1312 * None
1313 *
1314 * Side Effects:
1315 * The program exits
1316 */
1317 /* VARARGS */
1318 void
1319 #ifdef __STDC__
1320 Fatal(char *fmt, ...)
1321 #else
1322 Fatal(va_alist)
1323 va_dcl
1324 #endif
1325 {
1326 va_list ap;
1327 #ifdef __STDC__
1328 va_start(ap, fmt);
1329 #else
1330 char *fmt;
1331
1332 va_start(ap);
1333 fmt = va_arg(ap, char *);
1334 #endif
1335 if (jobsRunning)
1336 Job_Wait();
1337
1338 (void)vfprintf(stderr, fmt, ap);
1339 va_end(ap);
1340 (void)fprintf(stderr, "\n");
1341 (void)fflush(stderr);
1342
1343 if (DEBUG(GRAPH2))
1344 Targ_PrintGraph(2);
1345 exit(2); /* Not 1 so -q can distinguish error */
1346 }
1347
1348 /*
1349 * Punt --
1350 * Major exception once jobs are being created. Kills all jobs, prints
1351 * a message and exits.
1352 *
1353 * Results:
1354 * None
1355 *
1356 * Side Effects:
1357 * All children are killed indiscriminately and the program Lib_Exits
1358 */
1359 /* VARARGS */
1360 void
1361 #ifdef __STDC__
1362 Punt(char *fmt, ...)
1363 #else
1364 Punt(va_alist)
1365 va_dcl
1366 #endif
1367 {
1368 va_list ap;
1369 #ifdef __STDC__
1370 va_start(ap, fmt);
1371 #else
1372 char *fmt;
1373
1374 va_start(ap);
1375 fmt = va_arg(ap, char *);
1376 #endif
1377
1378 (void)fprintf(stderr, "make: ");
1379 (void)vfprintf(stderr, fmt, ap);
1380 va_end(ap);
1381 (void)fprintf(stderr, "\n");
1382 (void)fflush(stderr);
1383
1384 DieHorribly();
1385 }
1386
1387 /*-
1388 * DieHorribly --
1389 * Exit without giving a message.
1390 *
1391 * Results:
1392 * None
1393 *
1394 * Side Effects:
1395 * A big one...
1396 */
1397 void
1398 DieHorribly()
1399 {
1400 if (jobsRunning)
1401 Job_AbortAll();
1402 if (DEBUG(GRAPH2))
1403 Targ_PrintGraph(2);
1404 exit(2); /* Not 1, so -q can distinguish error */
1405 }
1406
1407 /*
1408 * Finish --
1409 * Called when aborting due to errors in child shell to signal
1410 * abnormal exit.
1411 *
1412 * Results:
1413 * None
1414 *
1415 * Side Effects:
1416 * The program exits
1417 */
1418 void
1419 Finish(errors)
1420 int errors; /* number of errors encountered in Make_Make */
1421 {
1422 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1423 }
1424
1425 /*
1426 * emalloc --
1427 * malloc, but die on error.
1428 */
1429 void *
1430 emalloc(len)
1431 size_t len;
1432 {
1433 void *p;
1434
1435 if ((p = malloc(len)) == NULL)
1436 enomem();
1437 return(p);
1438 }
1439
1440 /*
1441 * estrdup --
1442 * strdup, but die on error.
1443 */
1444 char *
1445 estrdup(str)
1446 const char *str;
1447 {
1448 char *p;
1449
1450 if ((p = strdup(str)) == NULL)
1451 enomem();
1452 return(p);
1453 }
1454
1455 /*
1456 * erealloc --
1457 * realloc, but die on error.
1458 */
1459 void *
1460 erealloc(ptr, size)
1461 void *ptr;
1462 size_t size;
1463 {
1464 if ((ptr = realloc(ptr, size)) == NULL)
1465 enomem();
1466 return(ptr);
1467 }
1468
1469 /*
1470 * enomem --
1471 * die when out of memory.
1472 */
1473 void
1474 enomem()
1475 {
1476 (void)fprintf(stderr, "make: %s.\n", strerror(errno));
1477 exit(2);
1478 }
1479
1480 /*
1481 * enunlink --
1482 * Remove a file carefully, avoiding directories.
1483 */
1484 int
1485 eunlink(file)
1486 const char *file;
1487 {
1488 struct stat st;
1489
1490 if (lstat(file, &st) == -1)
1491 return -1;
1492
1493 if (S_ISDIR(st.st_mode)) {
1494 errno = EISDIR;
1495 return -1;
1496 }
1497 return unlink(file);
1498 }
1499
1500 /*
1501 * usage --
1502 * exit with usage message
1503 */
1504 static void
1505 usage()
1506 {
1507 (void)fprintf(stderr,
1508 "usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
1509 [-I directory] [-j max_jobs] [-m directory] [-V variable]\n\
1510 [variable=value] [target ...]\n");
1511 exit(2);
1512 }
1513
1514
1515 int
1516 PrintAddr(a, b)
1517 ClientData a;
1518 ClientData b;
1519 {
1520 printf("%lx ", (unsigned long) a);
1521 return b ? 0 : 0;
1522 }
1523