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

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

KMK changes..

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.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 #ifndef KMK
536 static char syspath[] = _PATH_DEFSYSPATH;
537 #endif
538
539#ifdef RLIMIT_NOFILE
540 /*
541 * get rid of resource limit on file descriptors
542 */
543 {
544 struct rlimit rl;
545 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
546 rl.rlim_cur != rl.rlim_max) {
547 rl.rlim_cur = rl.rlim_max;
548 (void) setrlimit(RLIMIT_NOFILE, &rl);
549 }
550 }
551#endif
552 /*
553 * Find where we are and take care of PWD for the automounter...
554 * All this code is so that we know where we are when we start up
555 * on a different machine with pmake.
556 */
557 curdir = cdpath;
558 if (getcwd(curdir, MAXPATHLEN) == NULL)
559 err(2, NULL);
560
561 if (stat(curdir, &sa) == -1)
562 err(2, "%s", curdir);
563
564#ifdef WANT_ENV_PWD
565 if ((pwd = getenv("PWD")) != NULL) {
566 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
567 sa.st_dev == sb.st_dev)
568 (void) strcpy(curdir, pwd);
569 }
570#endif
571
572#if defined(__i386__) && defined(__FreeBSD_version) && \
573 __FreeBSD_version > 300003
574 /*
575 * PC-98 kernel sets the `i386' string to the utsname.machine and
576 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
577 * we check machine.ispc98 and adjust the machine variable before
578 * using usname(3) below.
579 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
580 * __FreeBSD_version was defined as 300003. So, this check can
581 * safely be done with any kernel with version > 300003.
582 */
583 if (!machine) {
584 int ispc98;
585 size_t len;
586
587 len = sizeof(ispc98);
588 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
589 if (ispc98)
590 machine = "pc98";
591 }
592 }
593#endif
594
595 /*
596 * Get the name of this type of MACHINE from utsname
597 * so we can share an executable for similar machines.
598 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
599 *
600 * Note that while MACHINE is decided at run-time,
601 * MACHINE_ARCH is always known at compile time.
602 */
603 if (!machine) {
604#ifndef MACHINE
605 struct utsname utsname;
606
607 if (uname(&utsname) == -1) {
608 perror("make: uname");
609 exit(2);
610 }
611 machine = utsname.machine;
612#else
613 machine = MACHINE;
614#endif
615 }
616
617 if (!machine_arch) {
618#ifndef MACHINE_ARCH
619 machine_arch = "unknown";
620#else
621 machine_arch = MACHINE_ARCH;
622#endif
623 }
624
625 /*
626 * Set machine_cpu to the minumum supported CPU revision based
627 * on the target architecture, if not already set.
628 */
629 if (!machine_cpu) {
630 if (!strcmp(machine_arch, "i386"))
631 machine_cpu = "i386";
632 else if (!strcmp(machine_arch, "alpha"))
633 machine_cpu = "ev4";
634 else
635 machine_cpu = "unknown";
636 }
637
638 #ifdef KMK
639 /* @todo figure out how to set object directory! */
640 #else
641 /*
642 * The object directory location is determined using the
643 * following order of preference:
644 *
645 * 1. MAKEOBJDIRPREFIX`cwd`
646 * 2. MAKEOBJDIR
647 * 3. _PATH_OBJDIR.${MACHINE}
648 * 4. _PATH_OBJDIR
649 * 5. _PATH_OBJDIRPREFIX`cwd`
650 *
651 * If one of the first two fails, use the current directory.
652 * If the remaining three all fail, use the current directory.
653 *
654 * Once things are initted,
655 * have to add the original directory to the search path,
656 * and modify the paths for the Makefiles apropriately. The
657 * current directory is also placed as a variable for make scripts.
658 */
659 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
660 if (!(path = getenv("MAKEOBJDIR"))) {
661 path = _PATH_OBJDIR;
662 pathp = _PATH_OBJDIRPREFIX;
663 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
664 path, machine);
665 if (!(objdir = chdir_verify_path(mdpath, obpath)))
666 if (!(objdir=chdir_verify_path(path, obpath))) {
667 (void) snprintf(mdpath, MAXPATHLEN,
668 "%s%s", pathp, curdir);
669 if (!(objdir=chdir_verify_path(mdpath,
670 obpath)))
671 objdir = curdir;
672 }
673 }
674 else if (!(objdir = chdir_verify_path(path, obpath)))
675 objdir = curdir;
676 }
677 else {
678 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
679 if (!(objdir = chdir_verify_path(mdpath, obpath)))
680 objdir = curdir;
681 }
682 #endif
683
684#ifdef WANT_ENV_PWD
685 #ifdef USE_KLIB
686 kEnvSet("PWD", objdir);
687 #else
688 setenv("PWD", objdir, 1);
689 #endif
690#endif
691
692 create = Lst_Init(FALSE);
693 makefiles = Lst_Init(FALSE);
694 envFirstVars = Lst_Init(FALSE);
695 printVars = FALSE;
696 expandVars = TRUE;
697 variables = Lst_Init(FALSE);
698 beSilent = FALSE; /* Print commands as executed */
699 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
700 noExecute = FALSE; /* Execute all commands */
701 keepgoing = FALSE; /* Stop on error */
702 allPrecious = FALSE; /* Remove targets when interrupted */
703 queryFlag = FALSE; /* This is not just a check-run */
704 noBuiltins = FALSE; /* Read the built-in rules */
705 touchFlag = FALSE; /* Actually update targets */
706 usePipes = TRUE; /* Catch child output in pipes */
707 debug = 0; /* No debug verbosity, please. */
708 jobsRunning = FALSE;
709#ifdef NMAKE
710 go_to_objdir = FALSE;
711#endif
712
713 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
714#ifdef REMOTE
715 maxJobs = DEFMAXJOBS; /* Set default max concurrency */
716#else
717 maxJobs = maxLocal;
718#endif
719 forceJobs = FALSE; /* No -j flag */
720 compatMake = FALSE; /* No compat mode */
721
722
723 /*
724 * Initialize the parsing, directory and variable modules to prepare
725 * for the reading of inclusion paths and variable settings on the
726 * command line
727 */
728 Dir_Init(); /* Initialize directory structures so -I flags
729 * can be processed correctly */
730 Parse_Init(); /* Need to initialize the paths of #include
731 * directories */
732 Var_Init(); /* As well as the lists of variables for
733 * parsing arguments */
734 str_init();
735 if (objdir != curdir)
736 Dir_AddDir(dirSearchPath, curdir);
737 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
738 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
739
740 /*
741 * Initialize various variables.
742 * MAKE also gets this name, for compatibility
743 * .MAKEFLAGS gets set to the empty string just in case.
744 * MFLAGS also gets initialized empty, for compatibility.
745 */
746 Var_Set("MAKE", argv[0], VAR_GLOBAL);
747 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
748 Var_Set("MFLAGS", "", VAR_GLOBAL);
749 Var_Set("MACHINE", machine, VAR_GLOBAL);
750 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
751 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
752
753 /*
754 * First snag any flags out of the MAKE environment variable.
755 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
756 * in a different format).
757 */
758#ifdef POSIX
759 Main_ParseArgLine(getenv("MAKEFLAGS"));
760#else
761 Main_ParseArgLine(getenv("MAKE"));
762#endif
763
764 MainParseArgs(argc, argv);
765
766 /*
767 * Be compatible if user did not specify -j and did not explicitly
768 * turned compatibility on
769 */
770 if (!compatMake && !forceJobs)
771 compatMake = TRUE;
772
773 /*
774 * Initialize archive, target and suffix modules in preparation for
775 * parsing the makefile(s)
776 */
777 Arch_Init();
778 Targ_Init();
779 Suff_Init();
780
781 DEFAULT = NILGNODE;
782 (void)time(&now);
783
784 /*
785 * Set up the .TARGETS variable to contain the list of targets to be
786 * created. If none specified, make the variable empty -- the parser
787 * will fill the thing in with the default or .MAIN target.
788 */
789 if (!Lst_IsEmpty(create)) {
790 LstNode ln;
791
792 for (ln = Lst_First(create); ln != NILLNODE;
793 ln = Lst_Succ(ln)) {
794 char *name = (char *)Lst_Datum(ln);
795
796 Var_Append(".TARGETS", name, VAR_GLOBAL);
797 }
798 } else
799 Var_Set(".TARGETS", "", VAR_GLOBAL);
800
801
802 #ifdef KMK
803 /*
804 * Add current directory tree to system include path all levels up to the root.
805 * ASSUMES that curdir is absolute.
806 */
807 {
808 char * psz = estrdup(curdir);
809 char * pszEnd = psz + strlen(psz);
810 while (psz < pszEnd)
811 {
812 Dir_AddDir(sysIncPath, psz);
813
814 /* Trim of the last directory component. */
815 while (pszEnd-- > psz)
816 if (*pszEnd == '/' || *pszEnd == ':')
817 {
818 if (*pszEnd == ':') /*Drive letter means end of story */
819 pszEnd = psz;
820 *pszEnd = '\0';
821 break;
822 }
823 }
824 efree(psz);
825 }
826
827 #else
828 /*
829 * If no user-supplied system path was given (through the -m option)
830 * add the directories from the DEFSYSPATH (more than one may be given
831 * as dir1:...:dirn) to the system include path.
832 */
833 if (Lst_IsEmpty(sysIncPath)) {
834 for (start = syspath; *start != '\0'; start = cp) {
835 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
836 continue;
837 if (*cp == '\0') {
838 Dir_AddDir(sysIncPath, start);
839 } else {
840 *cp++ = '\0';
841 Dir_AddDir(sysIncPath, start);
842 }
843 }
844 }
845 #endif
846
847 /*
848 * Read in the built-in rules first, followed by the specified
849 * makefile, if it was (makefile != (char *) NULL), or the default
850 * Makefile and makefile, in that order, if it wasn't.
851 */
852 if (!noBuiltins) {
853 LstNode ln;
854
855 sysMkPath = Lst_Init (FALSE);
856 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
857 #ifdef NMAKE
858 if (!Lst_IsEmpty(sysMkPath))
859 {
860 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
861 if (ln != NILLNODE)
862 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
863 }
864 /* Fatal("make: no system rules (%s).", _PATH_DEFSYSMK); */
865 #else
866 if (Lst_IsEmpty(sysMkPath))
867 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
868 ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
869 if (ln != NILLNODE)
870 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
871 #endif
872 }
873
874 if (!Lst_IsEmpty(makefiles)) {
875 LstNode ln;
876
877 ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
878 if (ln != NILLNODE)
879 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
880 } else
881 #ifdef KMK
882 if ( !ReadMakefile("Makefile.kMk", NULL)
883 #if KFILE_CASE
884 || !ReadMakefile("makefile.kMk", NULL)
885 || !ReadMakefile("Makefile.kmk", NULL)
886 || !ReadMakefile("makefile.kmk", NULL)
887 || !ReadMakefile("makefile", NULL)
888 #endif
889 )
890 (void)ReadMakefile("Makefile", NULL);
891 #else
892 if (!ReadMakefile("makefile", NULL))
893 (void)ReadMakefile("Makefile", NULL);
894 #endif
895
896 (void)ReadMakefile(".depend", NULL);
897
898 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
899 efree(p1);
900
901 /* Install all the flags into the MAKE envariable. */
902 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
903#ifdef POSIX
904 #ifdef USE_KLIB
905 kEnvSet("MAKEFLAGS", p, TRUE);
906 #else
907 setenv("MAKEFLAGS", p, 1);
908 #endif
909#else
910 #ifdef USE_KLIB
911 kEnvSet("MAKE", p, TRUE);
912 #else
913 setenv("MAKE", p, 1);
914 #endif
915#endif
916 efree(p1);
917
918 /*
919 * For compatibility, look at the directories in the VPATH variable
920 * and add them to the search path, if the variable is defined. The
921 * variable's value is in the same format as the PATH envariable, i.e.
922 * <directory>:<directory>:<directory>...
923 */
924 if (Var_Exists("VPATH", VAR_CMD)) {
925 char *vpath, *path, *cp, savec;
926 /*
927 * GCC stores string constants in read-only memory, but
928 * Var_Subst will want to write this thing, so store it
929 * in an array
930 */
931 static char VPATH[] = "${VPATH}";
932
933 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
934 path = vpath;
935 do {
936 /* skip to end of directory */
937 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
938 continue;
939 /* Save terminator character so know when to stop */
940 savec = *cp;
941 *cp = '\0';
942 /* Add directory to search path */
943 Dir_AddDir(dirSearchPath, path);
944 *cp = savec;
945 path = cp + 1;
946 } while (savec == ':');
947 (void)efree((Address)vpath);
948 }
949
950 /*
951 * Now that all search paths have been read for suffixes et al, it's
952 * time to add the default search path to their lists...
953 */
954 Suff_DoPaths();
955
956 /* print the initial graph, if the user requested it */
957 if (DEBUG(GRAPH1))
958 Targ_PrintGraph(1);
959
960 /* print the values of any variables requested by the user */
961 if (printVars) {
962 LstNode ln;
963
964 for (ln = Lst_First(variables); ln != NILLNODE;
965 ln = Lst_Succ(ln)) {
966 char *value;
967 if (expandVars) {
968 p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
969 /* This sprintf is safe, because of the malloc above */
970 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
971 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
972 } else {
973 value = Var_Value((char *)Lst_Datum(ln),
974 VAR_GLOBAL, &p1);
975 }
976 printf("%s\n", value ? value : "");
977 if (p1)
978 efree(p1);
979 }
980 }
981
982 /*
983 * Have now read the entire graph and need to make a list of targets
984 * to create. If none was given on the command line, we consult the
985 * parsing module to find the main target(s) to create.
986 */
987 if (Lst_IsEmpty(create))
988 targs = Parse_MainName();
989 else
990 targs = Targ_FindList(create, TARG_CREATE);
991
992 if (!compatMake && !printVars) {
993 /*
994 * Initialize job module before traversing the graph, now that
995 * any .BEGIN and .END targets have been read. This is done
996 * only if the -q flag wasn't given (to prevent the .BEGIN from
997 * being executed should it exist).
998 */
999 if (!queryFlag) {
1000 if (maxLocal == -1)
1001 maxLocal = maxJobs;
1002 Job_Init(maxJobs, maxLocal);
1003 jobsRunning = TRUE;
1004 }
1005
1006 /* Traverse the graph, checking on all the targets */
1007 outOfDate = Make_Run(targs);
1008 } else if (!printVars) {
1009 /*
1010 * Compat_Init will take care of creating all the targets as
1011 * well as initializing the module.
1012 */
1013 Compat_Run(targs);
1014 }
1015
1016 Lst_Destroy(targs, NOFREE);
1017 Lst_Destroy(variables, NOFREE);
1018 Lst_Destroy(makefiles, NOFREE);
1019 Lst_Destroy(create, (void (*) __P((ClientData))) efree);
1020
1021 /* print the graph now it's been processed if the user requested it */
1022 if (DEBUG(GRAPH2))
1023 Targ_PrintGraph(2);
1024
1025 Suff_End();
1026 Targ_End();
1027 Arch_End();
1028 str_end();
1029 Var_End();
1030 Parse_End();
1031 Dir_End();
1032
1033 if (queryFlag && outOfDate)
1034 return(1);
1035 else
1036 return(0);
1037}
1038
1039/*-
1040 * ReadMakefile --
1041 * Open and parse the given makefile.
1042 *
1043 * Results:
1044 * TRUE if ok. FALSE if couldn't open file.
1045 *
1046 * Side Effects:
1047 * lots
1048 */
1049static Boolean
1050ReadMakefile(p, q)
1051 ClientData p, q;
1052{
1053 char *fname = p; /* makefile to read */
1054 extern Lst parseIncPath;
1055 FILE *stream;
1056 char *name, path[MAXPATHLEN + 1];
1057 char *MAKEFILE;
1058 int setMAKEFILE;
1059
1060 if (!strcmp(fname, "-")) {
1061 Parse_File("(stdin)", stdin);
1062 Var_Set("MAKEFILE", "", VAR_GLOBAL);
1063 } else {
1064 setMAKEFILE = strcmp(fname, ".depend");
1065
1066 /* if we've chdir'd, rebuild the path name */
1067 if (curdir != objdir && *fname != '/') {
1068 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
1069 if (realpath(path, path) != NULL &&
1070 (stream = fopen(path, "r")) != NULL) {
1071 MAKEFILE = fname;
1072 fname = path;
1073 goto found;
1074 }
1075 } else if (realpath(fname, path) != NULL) {
1076 MAKEFILE = fname;
1077 fname = path;
1078 if ((stream = fopen(fname, "r")) != NULL)
1079 goto found;
1080 }
1081 /* look in -I and system include directories. */
1082 name = Dir_FindFile(fname, parseIncPath);
1083 if (!name)
1084 name = Dir_FindFile(fname, sysIncPath);
1085 if (!name || !(stream = fopen(name, "r")))
1086 return(FALSE);
1087 MAKEFILE = fname = name;
1088 /*
1089 * set the MAKEFILE variable desired by System V fans -- the
1090 * placement of the setting here means it gets set to the last
1091 * makefile specified, as it is set by SysV make.
1092 */
1093found:
1094 if (setMAKEFILE)
1095 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1096 Parse_File(fname, stream);
1097 (void)fclose(stream);
1098 }
1099 return(TRUE);
1100}
1101
1102/*-
1103 * Cmd_Exec --
1104 * Execute the command in cmd, and return the output of that command
1105 * in a string.
1106 *
1107 * Results:
1108 * A string containing the output of the command, or the empty string
1109 * If err is not NULL, it contains the reason for the command failure
1110 *
1111 * Side Effects:
1112 * The string must be freed by the caller.
1113 */
1114char *
1115Cmd_Exec(cmd, err)
1116 char *cmd;
1117 char **err;
1118{
1119 char *args[4]; /* Args for invoking the shell */
1120 int fds[2]; /* Pipe streams */
1121 int cpid; /* Child PID */
1122 int pid; /* PID from wait() */
1123 char *res; /* result */
1124 int status; /* command exit status */
1125 Buffer buf; /* buffer to store the result */
1126 char *cp;
1127 int cc;
1128
1129
1130 *err = NULL;
1131
1132 /*
1133 * Set up arguments for shell
1134 */
1135 args[0] = "sh";
1136 args[1] = "-c";
1137 args[2] = cmd;
1138 args[3] = NULL;
1139
1140 /*
1141 * Open a pipe for fetching its output
1142 */
1143 if (pipe(fds) == -1) {
1144 *err = "Couldn't create pipe for \"%s\"";
1145 goto bad;
1146 }
1147
1148 /*
1149 * Fork
1150 */
1151#ifdef __EMX__
1152 switch (cpid = fork()) {
1153#else
1154 switch (cpid = vfork()) {
1155#endif
1156 case 0:
1157 /*
1158 * Close input side of pipe
1159 */
1160 (void) close(fds[0]);
1161
1162 /*
1163 * Duplicate the output stream to the shell's output, then
1164 * shut the extra thing down. Note we don't fetch the error
1165 * stream...why not? Why?
1166 */
1167 (void) dup2(fds[1], 1);
1168 (void) close(fds[1]);
1169
1170 #ifdef OS2
1171 {
1172 const char *psz = getenv("COMSPEC");
1173 if (!psz)
1174 psz = getenv("OS2_SHELL");
1175 if (!psz)
1176 psz = "c:\\os2\\cmd.exe";
1177 (void) execv(psz, args);
1178 }
1179 #else
1180 (void) execv("/bin/sh", args);
1181 #endif
1182 _exit(1);
1183 /*NOTREACHED*/
1184
1185 case -1:
1186 *err = "Couldn't exec \"%s\"";
1187 goto bad;
1188
1189 default:
1190 /*
1191 * No need for the writing half
1192 */
1193 (void) close(fds[1]);
1194
1195 buf = Buf_Init (MAKE_BSIZE);
1196
1197 do {
1198 char result[BUFSIZ];
1199 cc = read(fds[0], result, sizeof(result));
1200 if (cc > 0)
1201 Buf_AddBytes(buf, cc, (Byte *) result);
1202 }
1203 while (cc > 0 || (cc == -1 && errno == EINTR));
1204
1205 /*
1206 * Close the input side of the pipe.
1207 */
1208 (void) close(fds[0]);
1209
1210 /*
1211 * Wait for the process to exit.
1212 */
1213 while(((pid = wait(&status)) != cpid) && (pid >= 0))
1214 continue;
1215
1216 if (cc == -1)
1217 *err = "Error reading shell's output for \"%s\"";
1218
1219 res = (char *)Buf_GetAll (buf, &cc);
1220 Buf_Destroy (buf, FALSE);
1221
1222 if (status)
1223 *err = "\"%s\" returned non-zero status";
1224
1225 /*
1226 * Null-terminate the result, convert newlines to spaces and
1227 * install it in the variable.
1228 */
1229 res[cc] = '\0';
1230 cp = &res[cc] - 1;
1231
1232 if (*cp == '\n') {
1233 /*
1234 * A final newline is just stripped
1235 */
1236 *cp-- = '\0';
1237 }
1238 while (cp >= res) {
1239 if (*cp == '\n') {
1240 *cp = ' ';
1241 }
1242 cp--;
1243 }
1244 break;
1245 }
1246 return res;
1247bad:
1248 res = emalloc(1);
1249 *res = '\0';
1250 return res;
1251}
1252
1253/*-
1254 * Error --
1255 * Print an error message given its format.
1256 *
1257 * Results:
1258 * None.
1259 *
1260 * Side Effects:
1261 * The message is printed.
1262 */
1263/* VARARGS */
1264void
1265#if defined(__STDC__) || defined(__IBMC__)
1266Error(char *fmt, ...)
1267#else
1268Error(va_alist)
1269 va_dcl
1270#endif
1271{
1272 va_list ap;
1273#if defined(__STDC__) || defined(__IBMC__)
1274 va_start(ap, fmt);
1275#else
1276 char *fmt;
1277
1278 va_start(ap);
1279 fmt = va_arg(ap, char *);
1280#endif
1281 (void)vfprintf(stderr, fmt, ap);
1282 va_end(ap);
1283 (void)fprintf(stderr, "\n");
1284 (void)fflush(stderr);
1285}
1286
1287/*-
1288 * Fatal --
1289 * Produce a Fatal error message. If jobs are running, waits for them
1290 * to finish.
1291 *
1292 * Results:
1293 * None
1294 *
1295 * Side Effects:
1296 * The program exits
1297 */
1298/* VARARGS */
1299void
1300#if defined(__STDC__) || defined(__IBMC__)
1301Fatal(char *fmt, ...)
1302#else
1303Fatal(va_alist)
1304 va_dcl
1305#endif
1306{
1307 va_list ap;
1308#if defined(__STDC__) || defined(__IBMC__)
1309 va_start(ap, fmt);
1310#else
1311 char *fmt;
1312
1313 va_start(ap);
1314 fmt = va_arg(ap, char *);
1315#endif
1316 if (jobsRunning)
1317 Job_Wait();
1318
1319 (void)vfprintf(stderr, fmt, ap);
1320 va_end(ap);
1321 (void)fprintf(stderr, "\n");
1322 (void)fflush(stderr);
1323
1324 if (DEBUG(GRAPH2))
1325 Targ_PrintGraph(2);
1326 exit(2); /* Not 1 so -q can distinguish error */
1327}
1328
1329/*
1330 * Punt --
1331 * Major exception once jobs are being created. Kills all jobs, prints
1332 * a message and exits.
1333 *
1334 * Results:
1335 * None
1336 *
1337 * Side Effects:
1338 * All children are killed indiscriminately and the program Lib_Exits
1339 */
1340/* VARARGS */
1341void
1342#if defined(__STDC__) || defined(__IBMC__)
1343Punt(char *fmt, ...)
1344#else
1345Punt(va_alist)
1346 va_dcl
1347#endif
1348{
1349 va_list ap;
1350#if defined(__STDC__) || defined(__IBMC__)
1351 va_start(ap, fmt);
1352#else
1353 char *fmt;
1354
1355 va_start(ap);
1356 fmt = va_arg(ap, char *);
1357#endif
1358
1359 (void)fprintf(stderr, "make: ");
1360 (void)vfprintf(stderr, fmt, ap);
1361 va_end(ap);
1362 (void)fprintf(stderr, "\n");
1363 (void)fflush(stderr);
1364
1365 DieHorribly();
1366}
1367
1368/*-
1369 * DieHorribly --
1370 * Exit without giving a message.
1371 *
1372 * Results:
1373 * None
1374 *
1375 * Side Effects:
1376 * A big one...
1377 */
1378void
1379DieHorribly()
1380{
1381 if (jobsRunning)
1382 Job_AbortAll();
1383 if (DEBUG(GRAPH2))
1384 Targ_PrintGraph(2);
1385 exit(2); /* Not 1, so -q can distinguish error */
1386}
1387
1388/*
1389 * Finish --
1390 * Called when aborting due to errors in child shell to signal
1391 * abnormal exit.
1392 *
1393 * Results:
1394 * None
1395 *
1396 * Side Effects:
1397 * The program exits
1398 */
1399void
1400Finish(errors)
1401 int errors; /* number of errors encountered in Make_Make */
1402{
1403 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1404}
1405
1406/*
1407 * emalloc --
1408 * malloc, but die on error.
1409 */
1410void *
1411emalloc(len)
1412 size_t len;
1413{
1414 void *p;
1415
1416 if ((p = malloc(len)) == NULL)
1417 enomem();
1418 return(p);
1419}
1420
1421/*
1422 * estrdup --
1423 * strdup, but die on error.
1424 */
1425char *
1426estrdup(str)
1427 const char *str;
1428{
1429 char *p;
1430
1431 if ((p = strdup(str)) == NULL)
1432 enomem();
1433 return(p);
1434}
1435
1436/*
1437 * erealloc --
1438 * realloc, but die on error.
1439 */
1440void *
1441erealloc(ptr, size)
1442 void *ptr;
1443 size_t size;
1444{
1445 if ((ptr = realloc(ptr, size)) == NULL)
1446 enomem();
1447 return(ptr);
1448}
1449
1450/*
1451 * efree --
1452 * efree, no change.
1453 */
1454void
1455efree(ptr)
1456 void *ptr;
1457{
1458 if (ptr)
1459 free(ptr);
1460}
1461
1462/*
1463 * enomem --
1464 * die when out of memory.
1465 */
1466void
1467enomem()
1468{
1469 err(2, NULL);
1470}
1471
1472/*
1473 * enunlink --
1474 * Remove a file carefully, avoiding directories.
1475 */
1476int
1477eunlink(file)
1478 const char *file;
1479{
1480 struct stat st;
1481
1482#ifdef __EMX__
1483 if (stat(file, &st) == -1)
1484#else
1485 if (lstat(file, &st) == -1)
1486#endif
1487 return -1;
1488
1489 if (S_ISDIR(st.st_mode)) {
1490 errno = EISDIR;
1491 return -1;
1492 }
1493 return unlink(file);
1494}
1495
1496/*
1497 * usage --
1498 * exit with usage message
1499 */
1500static void
1501usage()
1502{
1503 (void)fprintf(stderr, "%s\n%s\n%s\n"
1504#ifdef NMAKE
1505"%s\n"
1506#endif
1507 ,
1508"usage: kmk [-Beiknqrstv] [-D variable] [-d flags] [-E variable] [-f makefile]",
1509" [-I directory] [-j max_jobs] [-m directory] [-V variable]",
1510" [variable=value] [target ...]"
1511#ifdef NMAKE
1512,"NMAKE compatible mode enabled."
1513
1514#endif
1515);
1516 exit(2);
1517}
1518
1519
1520int
1521PrintAddr(a, b)
1522 ClientData a;
1523 ClientData b;
1524{
1525 printf("%lx ", (unsigned long) a);
1526 return b ? 0 : 0;
1527}
Note: See TracBrowser for help on using the repository browser.