Back out part of rev 1.24. The intention the quoting backfires and bad
[dragonfly.git] / usr.bin / make / main.c
CommitLineData
984263bc
MD
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.
1de703da
MD
37 *
38 * @(#) Copyright (c) 1988, 1989, 1990, 1993 The Regents of the University of California. All rights reserved.
39 * @(#)main.c 8.3 (Berkeley) 3/19/94
27afa3b2 40 * $FreeBSD: src/usr.bin/make/main.c,v 1.35.2.10 2003/12/16 08:34:11 des Exp $
3c837662 41 * $DragonFly: src/usr.bin/make/main.c,v 1.47 2005/01/14 11:30:16 joerg Exp $
984263bc
MD
42 */
43
984263bc
MD
44/*-
45 * main.c --
46 * The main file for this entire program. Exit routines etc
47 * reside here.
48 *
49 * Utility functions defined in this file:
50 * Main_ParseArgLine Takes a line of arguments, breaks them and
51 * treats them as if they were given when first
52 * invoked. Used by the parse module to implement
53 * the .MFLAGS target.
984263bc
MD
54 */
55
984263bc
MD
56#ifndef MACHINE
57#include <sys/utsname.h>
58#endif
9863ce62
MO
59#include <sys/param.h>
60#include <sys/types.h>
61#include <sys/stat.h>
984263bc
MD
62#include <sys/wait.h>
63#include <err.h>
984263bc 64#include <errno.h>
2eae1d85 65#include <signal.h>
79ffa91f 66#include <stdlib.h>
9863ce62
MO
67#include <stdlib.h>
68#include <string.h>
d0f0ba15 69#include <unistd.h>
271e747f 70#include <sys/sysctl.h>
79ffa91f 71
9863ce62 72#include "arch.h"
6a3d9147 73#include "buf.h"
9863ce62
MO
74#include "compat.h"
75#include "config.h"
984263bc 76#include "dir.h"
9863ce62
MO
77#include "globals.h"
78#include "GNode.h"
984263bc 79#include "job.h"
9863ce62
MO
80#include "lst.h"
81#include "make.h"
89aa31f8 82#include "nonints.h"
9863ce62 83#include "parse.h"
984263bc 84#include "pathnames.h"
9863ce62
MO
85#include "str.h"
86#include "suff.h"
87#include "targ.h"
88#include "util.h"
89#include "var.h"
984263bc 90
454224cf 91#define WANT_ENV_MKLVL 1
89a1b397
JS
92#define MKLVL_MAXVAL 500
93#define MKLVL_ENVVAR "__MKLVL__"
454224cf 94
984263bc
MD
95#define MAKEFLAGS ".MAKEFLAGS"
96
0a7e0b85
MO
97/* Targets to be made */
98Lst create = Lst_Initializer(create);
99
984263bc
MD
100time_t now; /* Time at start of make */
101GNode *DEFAULT; /* .DEFAULT node */
102Boolean allPrecious; /* .PRECIOUS given on line by itself */
103
104static Boolean noBuiltins; /* -r flag */
0a7e0b85
MO
105
106/* ordered list of makefiles to read */
107static Lst makefiles = Lst_Initializer(makefiles);
108
984263bc 109static Boolean expandVars; /* fully expand printed variables */
0a7e0b85
MO
110
111/* list of variables to print */
112static Lst variables = Lst_Initializer(variables);
113
984263bc
MD
114int maxJobs; /* -j argument */
115static Boolean forceJobs; /* -j argument given */
984263bc
MD
116Boolean compatMake; /* -B argument */
117Boolean debug; /* -d flag */
118Boolean noExecute; /* -n flag */
119Boolean keepgoing; /* -k flag */
120Boolean queryFlag; /* -q flag */
121Boolean touchFlag; /* -t flag */
122Boolean usePipes; /* !-P flag */
123Boolean ignoreErrors; /* -i flag */
124Boolean beSilent; /* -s flag */
125Boolean beVerbose; /* -v flag */
126Boolean oldVars; /* variable substitution style */
127Boolean checkEnvFirst; /* -e flag */
0a7e0b85
MO
128
129/* (-E) vars to override from env */
130Lst envFirstVars = Lst_Initializer(envFirstVars);
131
84de9e23 132Boolean jobsRunning; /* TRUE if the jobs might be running */
984263bc 133
2d8a3be7 134static void MainParseArgs(int, char **);
271e747f 135char *chdir_verify_path(const char *, char *);
d98710ab 136static int ReadMakefile(const void *, const void *);
2d8a3be7 137static void usage(void);
984263bc
MD
138
139static char *curdir; /* startup directory */
140static char *objdir; /* where we chdir'ed to */
141
d2e0d34c
JS
142/*
143 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
144 */
145static void
271e747f 146MFLAGS_append(const char *flag, char *arg)
d2e0d34c 147{
fbfaa208 148
d2e0d34c
JS
149 Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
150 if (arg != NULL)
151 Var_Append(MAKEFLAGS, arg, VAR_GLOBAL);
152
153 Var_Append("MFLAGS", flag, VAR_GLOBAL);
154 if (arg != NULL)
155 Var_Append("MFLAGS", arg, VAR_GLOBAL);
156}
157
984263bc
MD
158/*-
159 * MainParseArgs --
160 * Parse a given argument vector. Called from main() and from
161 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
162 *
163 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
164 *
165 * Results:
166 * None
167 *
168 * Side Effects:
169 * Various global and local flags will be set depending on the flags
170 * given
171 */
172static void
84de9e23 173MainParseArgs(int argc, char **argv)
984263bc 174{
984263bc
MD
175 int c;
176
177 optind = 1; /* since we're called more than once */
a34ec481 178#define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
984263bc
MD
179rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
180 switch(c) {
181 case 'C':
182 if (chdir(optarg) == -1)
183 err(1, "chdir %s", optarg);
184 break;
185 case 'D':
186 Var_Set(optarg, "1", VAR_GLOBAL);
d2e0d34c 187 MFLAGS_append("-D", optarg);
984263bc
MD
188 break;
189 case 'I':
190 Parse_AddIncludeDir(optarg);
d2e0d34c 191 MFLAGS_append("-I", optarg);
984263bc
MD
192 break;
193 case 'V':
913d5730 194 Lst_AtEnd(&variables, estrdup(optarg));
d2e0d34c 195 MFLAGS_append("-V", optarg);
984263bc
MD
196 break;
197 case 'X':
198 expandVars = FALSE;
199 break;
200 case 'B':
201 compatMake = TRUE;
d2e0d34c 202 MFLAGS_append("-B", NULL);
aa582f64 203 unsetenv("MAKE_JOBS_FIFO");
984263bc 204 break;
984263bc
MD
205 case 'P':
206 usePipes = FALSE;
d2e0d34c 207 MFLAGS_append("-P", NULL);
984263bc
MD
208 break;
209 case 'S':
210 keepgoing = FALSE;
d2e0d34c 211 MFLAGS_append("-S", NULL);
984263bc
MD
212 break;
213 case 'd': {
214 char *modules = optarg;
215
216 for (; *modules; ++modules)
217 switch (*modules) {
218 case 'A':
219 debug = ~0;
220 break;
221 case 'a':
222 debug |= DEBUG_ARCH;
223 break;
224 case 'c':
225 debug |= DEBUG_COND;
226 break;
227 case 'd':
228 debug |= DEBUG_DIR;
229 break;
230 case 'f':
231 debug |= DEBUG_FOR;
232 break;
233 case 'g':
234 if (modules[1] == '1') {
235 debug |= DEBUG_GRAPH1;
236 ++modules;
237 }
238 else if (modules[1] == '2') {
239 debug |= DEBUG_GRAPH2;
240 ++modules;
241 }
242 break;
243 case 'j':
244 debug |= DEBUG_JOB;
245 break;
246 case 'l':
247 debug |= DEBUG_LOUD;
248 break;
249 case 'm':
250 debug |= DEBUG_MAKE;
251 break;
252 case 's':
253 debug |= DEBUG_SUFF;
254 break;
255 case 't':
256 debug |= DEBUG_TARG;
257 break;
258 case 'v':
259 debug |= DEBUG_VAR;
260 break;
261 default:
262 warnx("illegal argument to d option -- %c", *modules);
263 usage();
264 }
d2e0d34c 265 MFLAGS_append("-d", optarg);
984263bc
MD
266 break;
267 }
268 case 'E':
913d5730 269 Lst_AtEnd(&envFirstVars, estrdup(optarg));
d2e0d34c 270 MFLAGS_append("-E", optarg);
984263bc
MD
271 break;
272 case 'e':
273 checkEnvFirst = TRUE;
d2e0d34c 274 MFLAGS_append("-e", NULL);
984263bc
MD
275 break;
276 case 'f':
913d5730 277 Lst_AtEnd(&makefiles, estrdup(optarg));
984263bc
MD
278 break;
279 case 'i':
280 ignoreErrors = TRUE;
d2e0d34c 281 MFLAGS_append("-i", NULL);
984263bc
MD
282 break;
283 case 'j': {
284 char *endptr;
285
286 forceJobs = TRUE;
287 maxJobs = strtol(optarg, &endptr, 10);
288 if (maxJobs <= 0 || *endptr != '\0') {
289 warnx("illegal number, -j argument -- %s",
290 optarg);
291 usage();
292 }
d2e0d34c 293 MFLAGS_append("-j", optarg);
984263bc
MD
294 break;
295 }
296 case 'k':
297 keepgoing = TRUE;
d2e0d34c 298 MFLAGS_append("-k", NULL);
984263bc
MD
299 break;
300 case 'm':
0a7e0b85 301 Dir_AddDir(&sysIncPath, optarg);
d2e0d34c 302 MFLAGS_append("-m", optarg);
984263bc
MD
303 break;
304 case 'n':
305 noExecute = TRUE;
d2e0d34c 306 MFLAGS_append("-n", NULL);
984263bc
MD
307 break;
308 case 'q':
309 queryFlag = TRUE;
310 /* Kind of nonsensical, wot? */
d2e0d34c 311 MFLAGS_append("-q", NULL);
984263bc
MD
312 break;
313 case 'r':
314 noBuiltins = TRUE;
d2e0d34c 315 MFLAGS_append("-r", NULL);
984263bc
MD
316 break;
317 case 's':
318 beSilent = TRUE;
d2e0d34c 319 MFLAGS_append("-s", NULL);
984263bc
MD
320 break;
321 case 't':
322 touchFlag = TRUE;
d2e0d34c 323 MFLAGS_append("-t", NULL);
984263bc
MD
324 break;
325 case 'v':
326 beVerbose = TRUE;
d2e0d34c 327 MFLAGS_append("-v", NULL);
984263bc
MD
328 break;
329 default:
330 case '?':
331 usage();
332 }
333 }
334
335 oldVars = TRUE;
336
337 /*
338 * See if the rest of the arguments are variable assignments and
339 * perform them if so. Else take them to be targets and stuff them
340 * on the end of the "create" list.
341 */
342 for (argv += optind, argc -= optind; *argv; ++argv, --argc)
c382ef3f 343 if (Parse_IsVar(*argv)) {
984263bc 344 Parse_DoVar(*argv, VAR_CMD);
c382ef3f 345 } else {
984263bc
MD
346 if (!**argv)
347 Punt("illegal (null) argument.");
348 if (**argv == '-') {
349 if ((*argv)[1])
350 optind = 0; /* -flag... */
351 else
352 optind = 1; /* - */
353 goto rearg;
354 }
0a7e0b85 355 Lst_AtEnd(&create, estrdup(*argv));
984263bc
MD
356 }
357}
358
359/*-
360 * Main_ParseArgLine --
361 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
362 * is encountered and by main() when reading the .MAKEFLAGS envariable.
363 * Takes a line of arguments and breaks it into its
364 * component words and passes those words and the number of them to the
365 * MainParseArgs function.
366 * The line should have all its leading whitespace removed.
367 *
368 * Results:
369 * None
370 *
371 * Side Effects:
372 * Only those that come from the various arguments.
373 */
374void
84de9e23 375Main_ParseArgLine(char *line)
984263bc
MD
376{
377 char **argv; /* Manufactured argument vector */
378 int argc; /* Number of arguments in argv */
379
380 if (line == NULL)
381 return;
382 for (; *line == ' '; ++line)
383 continue;
384 if (!*line)
385 return;
386
387 argv = brk_string(line, &argc, TRUE);
388 MainParseArgs(argc, argv);
389}
390
391char *
271e747f 392chdir_verify_path(const char *path, char *obpath)
984263bc
MD
393{
394 struct stat sb;
395
396 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
ef1537e7 397 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
984263bc 398 warn("warning: %s", path);
fbfaa208 399 return (0);
984263bc 400 }
fbfaa208 401 return (obpath);
984263bc
MD
402 }
403
271e747f 404 return (NULL);
984263bc
MD
405}
406
e3273be1
MO
407static void
408catch_child(int sig __unused)
409{
410}
411
89a1b397
JS
412/*
413 * In lieu of a good way to prevent every possible looping in
414 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
415 * by make(1), to prevent a forkbomb from happening, in a dumb and
416 * mechanical way.
417 */
418static void
419check_make_level(void)
420{
421#ifdef WANT_ENV_MKLVL
422 char *value = getenv(MKLVL_ENVVAR);
423 int level = (value == NULL) ? 0 : atoi(value);
424
425 if (level < 0) {
426 errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
427 } else if (level > MKLVL_MAXVAL) {
428 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
429 } else {
430 char new_value[32];
431 sprintf(new_value, "%d", level + 1);
432 setenv(MKLVL_ENVVAR, new_value, 1);
433 }
434#endif /* WANT_ENV_MKLVL */
435}
984263bc
MD
436
437/*-
438 * main --
439 * The main function, for obvious reasons. Initializes variables
440 * and a few modules, then parses the arguments give it in the
441 * environment and on the command line. Reads the system makefile
442 * followed by either Makefile, makefile or the file given by the
443 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
444 * flags it has received by then uses either the Make or the Compat
445 * module to create the initial list of targets.
446 *
447 * Results:
448 * If -q was given, exits -1 if anything was out-of-date. Else it exits
449 * 0.
450 *
451 * Side Effects:
452 * The program exits when done. Targets are created. etc. etc. etc.
453 */
454int
84de9e23 455main(int argc, char **argv)
984263bc 456{
984263bc 457 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
b50e2d44
MO
458 char *p, *p1;
459 const char *pathp;
271e747f 460 const char *path;
ef1537e7
MD
461 char mdpath[MAXPATHLEN];
462 char obpath[MAXPATHLEN];
463 char cdpath[MAXPATHLEN];
271e747f
MO
464 const char *machine = getenv("MACHINE");
465 const char *machine_arch = getenv("MACHINE_ARCH");
466 const char *machine_cpu = getenv("MACHINE_CPU");
984263bc
MD
467 char *cp = NULL, *start;
468 /* avoid faults on read-only strings */
469 static char syspath[] = _PATH_DEFSYSPATH;
470
27afa3b2
MD
471 {
472 /*
473 * Catch SIGCHLD so that we get kicked out of select() when we
474 * need to look at a child. This is only known to matter for the
475 * -j case (perhaps without -P).
476 *
477 * XXX this is intentionally misplaced.
478 */
479 struct sigaction sa;
480
481 sigemptyset(&sa.sa_mask);
482 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
483 sa.sa_handler = catch_child;
484 sigaction(SIGCHLD, &sa, NULL);
485 }
486
89a1b397
JS
487 check_make_level();
488
899365c2
MO
489#if DEFSHELL == 2
490 /*
491 * Turn off ENV to make ksh happier.
492 */
493 unsetenv("ENV");
494#endif
89a1b397 495
984263bc
MD
496#ifdef RLIMIT_NOFILE
497 /*
498 * get rid of resource limit on file descriptors
499 */
500 {
501 struct rlimit rl;
502 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
503 rl.rlim_cur != rl.rlim_max) {
504 rl.rlim_cur = rl.rlim_max;
fbfaa208 505 setrlimit(RLIMIT_NOFILE, &rl);
984263bc
MD
506 }
507 }
508#endif
984263bc 509
984263bc
MD
510 /*
511 * PC-98 kernel sets the `i386' string to the utsname.machine and
512 * it cannot be distinguished from IBM-PC by uname(3). Therefore,
513 * we check machine.ispc98 and adjust the machine variable before
514 * using usname(3) below.
4bd279b8
JS
515 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
516 * __FreeBSD_version was defined as 300003. So, this check can
517 * safely be done with any kernel with version > 300003.
984263bc
MD
518 */
519 if (!machine) {
520 int ispc98;
521 size_t len;
522
523 len = sizeof(ispc98);
524 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
525 if (ispc98)
526 machine = "pc98";
527 }
528 }
984263bc
MD
529
530 /*
531 * Get the name of this type of MACHINE from utsname
532 * so we can share an executable for similar machines.
533 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
534 *
535 * Note that while MACHINE is decided at run-time,
536 * MACHINE_ARCH is always known at compile time.
537 */
538 if (!machine) {
539#ifndef MACHINE
540 struct utsname utsname;
541
611c334f
JR
542 if (uname(&utsname) == -1)
543 err(2, "uname");
984263bc
MD
544 machine = utsname.machine;
545#else
546 machine = MACHINE;
547#endif
548 }
549
550 if (!machine_arch) {
551#ifndef MACHINE_ARCH
552 machine_arch = "unknown";
553#else
554 machine_arch = MACHINE_ARCH;
555#endif
556 }
557
558 /*
559 * Set machine_cpu to the minumum supported CPU revision based
560 * on the target architecture, if not already set.
561 */
562 if (!machine_cpu) {
563 if (!strcmp(machine_arch, "i386"))
564 machine_cpu = "i386";
565 else if (!strcmp(machine_arch, "alpha"))
566 machine_cpu = "ev4";
567 else
568 machine_cpu = "unknown";
569 }
984263bc 570
984263bc 571 expandVars = TRUE;
984263bc
MD
572 beSilent = FALSE; /* Print commands as executed */
573 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
574 noExecute = FALSE; /* Execute all commands */
575 keepgoing = FALSE; /* Stop on error */
576 allPrecious = FALSE; /* Remove targets when interrupted */
577 queryFlag = FALSE; /* This is not just a check-run */
578 noBuiltins = FALSE; /* Read the built-in rules */
579 touchFlag = FALSE; /* Actually update targets */
580 usePipes = TRUE; /* Catch child output in pipes */
581 debug = 0; /* No debug verbosity, please. */
582 jobsRunning = FALSE;
583
a34ec481 584 maxJobs = DEFMAXJOBS;
984263bc
MD
585 forceJobs = FALSE; /* No -j flag */
586 compatMake = FALSE; /* No compat mode */
587
984263bc
MD
588 /*
589 * Initialize the parsing, directory and variable modules to prepare
590 * for the reading of inclusion paths and variable settings on the
591 * command line
592 */
593 Dir_Init(); /* Initialize directory structures so -I flags
594 * can be processed correctly */
595 Parse_Init(); /* Need to initialize the paths of #include
596 * directories */
597 Var_Init(); /* As well as the lists of variables for
598 * parsing arguments */
599 str_init();
984263bc
MD
600
601 /*
602 * Initialize various variables.
603 * MAKE also gets this name, for compatibility
604 * .MAKEFLAGS gets set to the empty string just in case.
605 * MFLAGS also gets initialized empty, for compatibility.
606 */
607 Var_Set("MAKE", argv[0], VAR_GLOBAL);
608 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
609 Var_Set("MFLAGS", "", VAR_GLOBAL);
610 Var_Set("MACHINE", machine, VAR_GLOBAL);
611 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
612 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
ef1537e7
MD
613#ifdef MAKE_VERSION
614 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
615#endif
984263bc
MD
616
617 /*
618 * First snag any flags out of the MAKE environment variable.
619 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
620 * in a different format).
621 */
984263bc 622 Main_ParseArgLine(getenv("MAKEFLAGS"));
984263bc
MD
623
624 MainParseArgs(argc, argv);
625
57c92c78
JS
626 /*
627 * Find where we are...
628 * All this code is so that we know where we are when we start up
629 * on a different machine with pmake.
630 */
631 curdir = cdpath;
632 if (getcwd(curdir, MAXPATHLEN) == NULL)
633 err(2, NULL);
634
271e747f
MO
635 {
636 struct stat sa;
57c92c78
JS
637 if (stat(curdir, &sa) == -1)
638 err(2, "%s", curdir);
271e747f 639 }
57c92c78
JS
640
641 /*
642 * The object directory location is determined using the
643 * following order of preference:
644 *
645 * 1. MAKEOBJDIRPREFIX`cwd`
646 * 2. MAKEOBJDIR
647 * 3. _PATH_OBJDIR.${MACHINE}
648 * 4. _PATH_OBJDIR
649 * 5. _PATH_OBJDIRPREFIX`cwd`
650 *
651 * If one of the first two fails, use the current directory.
652 * If the remaining three all fail, use the current directory.
653 *
654 * Once things are initted,
655 * have to add the original directory to the search path,
656 * and modify the paths for the Makefiles apropriately. The
657 * current directory is also placed as a variable for make scripts.
658 */
659 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
660 if (!(path = getenv("MAKEOBJDIR"))) {
661 path = _PATH_OBJDIR;
662 pathp = _PATH_OBJDIRPREFIX;
fbfaa208 663 snprintf(mdpath, MAXPATHLEN, "%s.%s",
57c92c78
JS
664 path, machine);
665 if (!(objdir = chdir_verify_path(mdpath, obpath)))
666 if (!(objdir=chdir_verify_path(path, obpath))) {
fbfaa208 667 snprintf(mdpath, MAXPATHLEN,
57c92c78
JS
668 "%s%s", pathp, curdir);
669 if (!(objdir=chdir_verify_path(mdpath,
670 obpath)))
671 objdir = curdir;
672 }
673 }
674 else if (!(objdir = chdir_verify_path(path, obpath)))
675 objdir = curdir;
676 }
677 else {
fbfaa208 678 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
57c92c78
JS
679 if (!(objdir = chdir_verify_path(mdpath, obpath)))
680 objdir = curdir;
681 }
682 Dir_InitDot(); /* Initialize the "." directory */
683 if (objdir != curdir)
0a7e0b85 684 Dir_AddDir(&dirSearchPath, curdir);
57c92c78
JS
685 Var_Set(".DIRECTIVE_MAKEENV", "YES", VAR_GLOBAL);
686 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
687 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
688
aa582f64
MO
689 if (getenv("MAKE_JOBS_FIFO") != NULL)
690 forceJobs = TRUE;
984263bc
MD
691 /*
692 * Be compatible if user did not specify -j and did not explicitly
693 * turned compatibility on
694 */
695 if (!compatMake && !forceJobs)
696 compatMake = TRUE;
697
698 /*
699 * Initialize archive, target and suffix modules in preparation for
700 * parsing the makefile(s)
701 */
702 Arch_Init();
703 Targ_Init();
704 Suff_Init();
705
9edd457e 706 DEFAULT = NULL;
fbfaa208 707 time(&now);
984263bc
MD
708
709 /*
710 * Set up the .TARGETS variable to contain the list of targets to be
711 * created. If none specified, make the variable empty -- the parser
712 * will fill the thing in with the default or .MAIN target.
713 */
0a7e0b85 714 if (!Lst_IsEmpty(&create)) {
e035e56b 715 LstNode *ln;
984263bc 716
0a7e0b85 717 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
9a4c88c2 718 char *name = Lst_Datum(ln);
984263bc
MD
719
720 Var_Append(".TARGETS", name, VAR_GLOBAL);
721 }
722 } else
723 Var_Set(".TARGETS", "", VAR_GLOBAL);
724
725
726 /*
727 * If no user-supplied system path was given (through the -m option)
728 * add the directories from the DEFSYSPATH (more than one may be given
729 * as dir1:...:dirn) to the system include path.
730 */
0a7e0b85 731 if (Lst_IsEmpty(&sysIncPath)) {
984263bc
MD
732 for (start = syspath; *start != '\0'; start = cp) {
733 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
734 continue;
735 if (*cp == '\0') {
0a7e0b85 736 Dir_AddDir(&sysIncPath, start);
984263bc
MD
737 } else {
738 *cp++ = '\0';
0a7e0b85 739 Dir_AddDir(&sysIncPath, start);
984263bc
MD
740 }
741 }
742 }
743
744 /*
745 * Read in the built-in rules first, followed by the specified
746 * makefile, if it was (makefile != (char *) NULL), or the default
747 * Makefile and makefile, in that order, if it wasn't.
748 */
749 if (!noBuiltins) {
0a7e0b85
MO
750 /* Path of sys.mk */
751 Lst sysMkPath = Lst_Initializer(sysMkPath);
e035e56b 752 LstNode *ln;
984263bc 753
0a7e0b85
MO
754 Dir_Expand(_PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
755 if (Lst_IsEmpty(&sysMkPath))
984263bc 756 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
0a7e0b85 757 ln = Lst_Find(&sysMkPath, NULL, ReadMakefile);
9edd457e 758 if (ln != NULL)
984263bc 759 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
0a7e0b85 760 Lst_Destroy(&sysMkPath, free);
984263bc
MD
761 }
762
0a7e0b85 763 if (!Lst_IsEmpty(&makefiles)) {
e035e56b 764 LstNode *ln;
984263bc 765
0a7e0b85 766 ln = Lst_Find(&makefiles, NULL, ReadMakefile);
9edd457e 767 if (ln != NULL)
984263bc 768 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
9a309bcc
MD
769 } else if (!ReadMakefile("BSDmakefile", NULL))
770 if (!ReadMakefile("makefile", NULL))
fbfaa208 771 ReadMakefile("Makefile", NULL);
984263bc 772
fbfaa208 773 ReadMakefile(".depend", NULL);
984263bc 774
984263bc
MD
775 /* Install all the flags into the MAKE envariable. */
776 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
984263bc 777 setenv("MAKEFLAGS", p, 1);
a4516861 778 free(p1);
984263bc
MD
779
780 /*
781 * For compatibility, look at the directories in the VPATH variable
782 * and add them to the search path, if the variable is defined. The
783 * variable's value is in the same format as the PATH envariable, i.e.
784 * <directory>:<directory>:<directory>...
785 */
786 if (Var_Exists("VPATH", VAR_CMD)) {
84de9e23 787 char *vpath, savec;
984263bc
MD
788 /*
789 * GCC stores string constants in read-only memory, but
790 * Var_Subst will want to write this thing, so store it
791 * in an array
792 */
793 static char VPATH[] = "${VPATH}";
794
795 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
796 path = vpath;
797 do {
798 /* skip to end of directory */
799 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
800 continue;
801 /* Save terminator character so know when to stop */
802 savec = *cp;
803 *cp = '\0';
804 /* Add directory to search path */
0a7e0b85 805 Dir_AddDir(&dirSearchPath, path);
984263bc
MD
806 *cp = savec;
807 path = cp + 1;
808 } while (savec == ':');
fbfaa208 809 free(vpath);
984263bc
MD
810 }
811
812 /*
813 * Now that all search paths have been read for suffixes et al, it's
814 * time to add the default search path to their lists...
815 */
816 Suff_DoPaths();
817
818 /* print the initial graph, if the user requested it */
819 if (DEBUG(GRAPH1))
820 Targ_PrintGraph(1);
821
822 /* print the values of any variables requested by the user */
0a7e0b85 823 if (!Lst_IsEmpty(&variables)) {
e035e56b 824 LstNode *ln;
984263bc 825
0a7e0b85 826 for (ln = Lst_First(&variables); ln != NULL;
984263bc
MD
827 ln = Lst_Succ(ln)) {
828 char *value;
829 if (expandVars) {
9a4c88c2 830 p1 = emalloc(strlen(Lst_Datum(ln)) + 1 + 3);
984263bc 831 /* This sprintf is safe, because of the malloc above */
fbfaa208 832 sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
984263bc
MD
833 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
834 } else {
9a4c88c2 835 value = Var_Value(Lst_Datum(ln),
984263bc
MD
836 VAR_GLOBAL, &p1);
837 }
838 printf("%s\n", value ? value : "");
839 if (p1)
840 free(p1);
841 }
454224cf 842 } else {
984263bc 843
984263bc 844 /*
454224cf
MD
845 * Have now read the entire graph and need to make a list of targets
846 * to create. If none was given on the command line, we consult the
847 * parsing module to find the main target(s) to create.
984263bc 848 */
0a7e0b85
MO
849 Lst targs = Lst_Initializer(targs);
850
851 if (Lst_IsEmpty(&create))
852 Parse_MainName(&targs);
454224cf 853 else
0a7e0b85 854 Targ_FindList(&targs, &create, TARG_CREATE);
984263bc 855
454224cf
MD
856 if (!compatMake) {
857 /*
858 * Initialize job module before traversing the graph, now that
859 * any .BEGIN and .END targets have been read. This is done
860 * only if the -q flag wasn't given (to prevent the .BEGIN from
861 * being executed should it exist).
862 */
863 if (!queryFlag) {
a34ec481 864 Job_Init(maxJobs);
454224cf
MD
865 jobsRunning = TRUE;
866 }
867
868 /* Traverse the graph, checking on all the targets */
0a7e0b85 869 outOfDate = Make_Run(&targs);
454224cf
MD
870 } else {
871 /*
872 * Compat_Init will take care of creating all the targets as
873 * well as initializing the module.
874 */
0a7e0b85 875 Compat_Run(&targs);
3b340ba1 876 outOfDate = 0;
454224cf 877 }
0a7e0b85 878 Lst_Destroy(&targs, NOFREE);
984263bc
MD
879 }
880
913d5730
MO
881 Lst_Destroy(&variables, free);
882 Lst_Destroy(&makefiles, free);
0a7e0b85 883 Lst_Destroy(&create, free);
984263bc
MD
884
885 /* print the graph now it's been processed if the user requested it */
886 if (DEBUG(GRAPH2))
887 Targ_PrintGraph(2);
888
984263bc 889 if (queryFlag && outOfDate)
fbfaa208 890 return (1);
984263bc 891 else
fbfaa208 892 return (0);
984263bc
MD
893}
894
895/*-
896 * ReadMakefile --
897 * Open and parse the given makefile.
898 *
899 * Results:
900 * TRUE if ok. FALSE if couldn't open file.
901 *
902 * Side Effects:
903 * lots
904 */
905static Boolean
d98710ab 906ReadMakefile(const void *p, const void *q __unused)
984263bc 907{
b83dbac0 908 char *fname; /* makefile to read */
984263bc 909 FILE *stream;
ef1537e7 910 char *name, path[MAXPATHLEN];
984263bc
MD
911 char *MAKEFILE;
912 int setMAKEFILE;
913
d98710ab
MO
914 /* XXX - remove this once constification is done */
915 fname = estrdup(p);
84de9e23 916
984263bc
MD
917 if (!strcmp(fname, "-")) {
918 Parse_File("(stdin)", stdin);
919 Var_Set("MAKEFILE", "", VAR_GLOBAL);
920 } else {
921 setMAKEFILE = strcmp(fname, ".depend");
922
923 /* if we've chdir'd, rebuild the path name */
924 if (curdir != objdir && *fname != '/') {
fbfaa208 925 snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
984263bc
MD
926 /*
927 * XXX The realpath stuff breaks relative includes
928 * XXX in some cases. The problem likely is in
929 * XXX parse.c where it does special things in
930 * XXX ParseDoInclude if the file is relateive
931 * XXX or absolute and not a system file. There
932 * XXX it assumes that if the current file that's
933 * XXX being included is absolute, that any files
934 * XXX that it includes shouldn't do the -I path
935 * XXX stuff, which is inconsistant with historical
936 * XXX behavior. However, I can't pentrate the mists
937 * XXX further, so I'm putting this workaround in
938 * XXX here until such time as the underlying bug
939 * XXX can be fixed.
940 */
941#if THIS_BREAKS_THINGS
942 if (realpath(path, path) != NULL &&
943 (stream = fopen(path, "r")) != NULL) {
944 MAKEFILE = fname;
945 fname = path;
946 goto found;
947 }
948 } else if (realpath(fname, path) != NULL) {
949 MAKEFILE = fname;
950 fname = path;
951 if ((stream = fopen(fname, "r")) != NULL)
952 goto found;
953 }
954#else
955 if ((stream = fopen(path, "r")) != NULL) {
956 MAKEFILE = fname;
957 fname = path;
958 goto found;
959 }
960 } else {
961 MAKEFILE = fname;
962 if ((stream = fopen(fname, "r")) != NULL)
963 goto found;
964 }
965#endif
966 /* look in -I and system include directories. */
0a7e0b85 967 name = Dir_FindFile(fname, &parseIncPath);
984263bc 968 if (!name)
0a7e0b85 969 name = Dir_FindFile(fname, &sysIncPath);
984263bc 970 if (!name || !(stream = fopen(name, "r")))
fbfaa208 971 return (FALSE);
984263bc
MD
972 MAKEFILE = fname = name;
973 /*
974 * set the MAKEFILE variable desired by System V fans -- the
975 * placement of the setting here means it gets set to the last
976 * makefile specified, as it is set by SysV make.
977 */
978found:
979 if (setMAKEFILE)
980 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
981 Parse_File(fname, stream);
fbfaa208 982 fclose(stream);
984263bc 983 }
fbfaa208 984 return (TRUE);
984263bc
MD
985}
986
987/*-
988 * Cmd_Exec --
989 * Execute the command in cmd, and return the output of that command
990 * in a string.
991 *
992 * Results:
993 * A string containing the output of the command, or the empty string
454224cf 994 * If error is not NULL, it contains the reason for the command failure
984263bc
MD
995 *
996 * Side Effects:
997 * The string must be freed by the caller.
998 */
999char *
230209a1 1000Cmd_Exec(const char *cmd, const char **error)
984263bc
MD
1001{
1002 char *args[4]; /* Args for invoking the shell */
1003 int fds[2]; /* Pipe streams */
1004 int cpid; /* Child PID */
1005 int pid; /* PID from wait() */
1006 char *res; /* result */
1007 int status; /* command exit status */
6a3d9147 1008 Buffer *buf; /* buffer to store the result */
984263bc 1009 char *cp;
9cf296a4
MO
1010 size_t blen;
1011 ssize_t rcnt;
984263bc 1012
84de9e23 1013 *error = NULL;
984263bc 1014
899365c2
MO
1015 if (shellPath == NULL)
1016 Shell_Init();
984263bc
MD
1017 /*
1018 * Set up arguments for shell
1019 */
899365c2 1020 args[0] = shellName;
984263bc
MD
1021 args[1] = "-c";
1022 args[2] = cmd;
1023 args[3] = NULL;
1024
1025 /*
1026 * Open a pipe for fetching its output
1027 */
1028 if (pipe(fds) == -1) {
84de9e23 1029 *error = "Couldn't create pipe for \"%s\"";
984263bc
MD
1030 goto bad;
1031 }
1032
1033 /*
1034 * Fork
1035 */
1036 switch (cpid = vfork()) {
1037 case 0:
1038 /*
1039 * Close input side of pipe
1040 */
fbfaa208 1041 close(fds[0]);
984263bc
MD
1042
1043 /*
1044 * Duplicate the output stream to the shell's output, then
1045 * shut the extra thing down. Note we don't fetch the error
1046 * stream...why not? Why?
1047 */
fbfaa208
MO
1048 dup2(fds[1], 1);
1049 close(fds[1]);
984263bc 1050
fbfaa208 1051 execv(shellPath, args);
984263bc
MD
1052 _exit(1);
1053 /*NOTREACHED*/
1054
1055 case -1:
84de9e23 1056 *error = "Couldn't exec \"%s\"";
984263bc
MD
1057 goto bad;
1058
1059 default:
1060 /*
1061 * No need for the writing half
1062 */
fbfaa208 1063 close(fds[1]);
984263bc 1064
fbfaa208 1065 buf = Buf_Init(MAKE_BSIZE);
984263bc
MD
1066
1067 do {
1068 char result[BUFSIZ];
9cf296a4
MO
1069 rcnt = read(fds[0], result, sizeof(result));
1070 if (rcnt != -1)
1071 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1072 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
984263bc
MD
1073 /*
1074 * Close the input side of the pipe.
1075 */
fbfaa208 1076 close(fds[0]);
984263bc
MD
1077
1078 /*
1079 * Wait for the process to exit.
1080 */
fbfaa208 1081 while (((pid = wait(&status)) != cpid) && (pid >= 0))
984263bc
MD
1082 continue;
1083
9cf296a4 1084 if (rcnt == -1)
84de9e23 1085 *error = "Error reading shell's output for \"%s\"";
984263bc 1086
9cf296a4 1087 res = (char *)Buf_GetAll(buf, &blen);
fbfaa208 1088 Buf_Destroy(buf, FALSE);
984263bc
MD
1089
1090 if (status)
84de9e23 1091 *error = "\"%s\" returned non-zero status";
984263bc
MD
1092
1093 /*
1094 * Null-terminate the result, convert newlines to spaces and
1095 * install it in the variable.
1096 */
9cf296a4
MO
1097 res[blen] = '\0';
1098 cp = &res[blen] - 1;
984263bc
MD
1099
1100 if (*cp == '\n') {
1101 /*
1102 * A final newline is just stripped
1103 */
1104 *cp-- = '\0';
1105 }
1106 while (cp >= res) {
1107 if (*cp == '\n') {
1108 *cp = ' ';
1109 }
1110 cp--;
1111 }
1112 break;
1113 }
fbfaa208 1114 return (res);
984263bc
MD
1115bad:
1116 res = emalloc(1);
1117 *res = '\0';
fbfaa208 1118 return (res);
984263bc 1119}
b83dbac0 1120
984263bc
MD
1121/*
1122 * usage --
1123 * exit with usage message
1124 */
1125static void
454224cf 1126usage(void)
984263bc 1127{
fbfaa208 1128 fprintf(stderr, "%s\n%s\n%s\n",
984263bc
MD
1129"usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1130" [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1131" [-m directory] [-V variable] [variable=value] [target ...]");
1132 exit(2);
1133}