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