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

Last change on this file since 29 was 27, checked in by bird, 23 years ago

OS2 / VAC308

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