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