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

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

No sys.mk in NMAKE.

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