source: trunk/src/kmk/main.c@ 42

Last change on this file since 42 was 40, checked in by bird, 22 years ago

Inline files and such.

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