Use LST_FOREACH() macro instead of for-loop
[dragonfly.git] / usr.bin / make / main.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#) 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
40  * $FreeBSD: src/usr.bin/make/main.c,v 1.118 2005/02/13 13:33:56 harti Exp $
41  * $DragonFly: src/usr.bin/make/main.c,v 1.134 2005/07/02 10:48:42 okumoto Exp $
42  */
43
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
51  *                      Takes a line of arguments, breaks them and
52  *                      treats them as if they were given when first
53  *                      invoked. Used by the parse module to implement
54  *                      the .MFLAGS target.
55  */
56
57 #ifndef MACHINE
58 #include <sys/utsname.h>
59 #endif
60 #include <sys/param.h>
61 #include <sys/stat.h>
62 #include <sys/time.h>
63 #include <sys/queue.h>
64 #include <sys/resource.h>
65 #include <sys/wait.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <unistd.h>
71
72 #include "arch.h"
73 #include "buf.h"
74 #include "config.h"
75 #include "dir.h"
76 #include "globals.h"
77 #include "job.h"
78 #include "make.h"
79 #include "parse.h"
80 #include "pathnames.h"
81 #include "shell.h"
82 #include "str.h"
83 #include "suff.h"
84 #include "targ.h"
85 #include "util.h"
86 #include "var.h"
87
88 extern char **environ;  /* XXX what header declares this variable? */
89
90 /*
91  * DEFMAXJOBS
92  *      This control the default concurrency. On no occasion will more
93  *      than DEFMAXJOBS targets be created at once.
94  */
95 #define DEFMAXJOBS      1
96
97 typedef struct CLI {
98         /** ordered list of makefiles to read */
99         Lst makefiles;
100
101         /** list of variables to print */
102         Lst variables;
103
104         /** Targets to be made */
105         Lst create;
106
107         /** directories to search when looking for includes */
108         struct Path     parseIncPath;
109
110         /** directories to search when looking for system includes */
111         struct Path     sysIncPath;
112
113         Boolean expandVars;     /* fully expand printed variables */
114         Boolean builtins;       /* -r flag */
115         Boolean forceJobs;      /* -j argument given */
116
117         /**
118          * -q flag:
119          * TRUE if we aren't supposed to really make anything, just
120          * see if the targets are out-of-date
121          */
122         Boolean         queryFlag;
123 } CLI;
124
125 /* (-E) vars to override from env */
126 Lst envFirstVars = Lst_Initializer(envFirstVars);
127
128 Boolean         allPrecious;    /* .PRECIOUS given on line by itself */
129 Boolean         beSilent;       /* -s flag */
130 Boolean         beVerbose;      /* -v flag */
131 Boolean         compatMake;     /* -B argument */
132 Boolean         debug;          /* -d flag */
133 Boolean         ignoreErrors;   /* -i flag */
134 int             jobLimit;       /* -j argument */
135 Boolean         jobsRunning;    /* TRUE if the jobs might be running */
136 Boolean         keepgoing;      /* -k flag */
137 Boolean         noExecute;      /* -n flag */
138 Boolean         touchFlag;      /* -t flag */
139 Boolean         usePipes;       /* !-P flag */
140 uint32_t        warn_cmd;       /* command line warning flags */
141 uint32_t        warn_flags;     /* actual warning flags */
142 uint32_t        warn_nocmd;     /* command line no-warning flags */
143
144 time_t          now;            /* Time at start of make */
145 struct GNode    *DEFAULT;       /* .DEFAULT node */
146
147
148 /**
149  * Exit with usage message.
150  */
151 static void
152 usage(void)
153 {
154         fprintf(stderr,
155             "usage: make [-BPSXeiknqrstv] [-C directory] [-D variable]\n"
156             "\t[-d flags] [-E variable] [-f makefile] [-I directory]\n"
157             "\t[-j max_jobs] [-m directory] [-V variable]\n"
158             "\t[variable=value] [target ...]\n");
159         exit(2);
160 }
161
162 /**
163  * MFLAGS_append
164  *      Append a flag with an optional argument to MAKEFLAGS and MFLAGS
165  */
166 static void
167 MFLAGS_append(const char *flag, char *arg)
168 {
169         char *str;
170
171         Var_Append(".MAKEFLAGS", flag, VAR_GLOBAL);
172         if (arg != NULL) {
173                 str = MAKEFLAGS_quote(arg);
174                 Var_Append(".MAKEFLAGS", str, VAR_GLOBAL);
175                 free(str);
176         }
177
178         Var_Append("MFLAGS", flag, VAR_GLOBAL);
179         if (arg != NULL) {
180                 str = MAKEFLAGS_quote(arg);
181                 Var_Append("MFLAGS", str, VAR_GLOBAL);
182                 free(str);
183         }
184 }
185
186 /**
187  * Open and parse the given makefile.
188  *
189  * Results:
190  *      TRUE if ok. FALSE if couldn't open file.
191  */
192 static Boolean
193 ReadMakefile(Parser *parser, CLI *cli, const char file[], const char curdir[], const char objdir[])
194 {
195         char    path[MAXPATHLEN];
196         FILE    *stream;
197         char    *fname;
198         char    *name;
199
200         if (!strcmp(file, "-")) {
201                 Parse_File(parser, cli, "(stdin)", stdin);
202                 Var_SetGlobal("MAKEFILE", "");
203                 return (TRUE);
204         }
205
206         if (strcmp(curdir, objdir) == 0 || file[0] == '/') {
207                 strcpy(path, file);
208         } else {
209                 /*
210                  * we've chdir'd, rebuild the path name
211                  */
212                 snprintf(path, MAXPATHLEN, "%s/%s", curdir, file);
213         }
214 #if THIS_BREAKS_THINGS
215         /*
216          * XXX The realpath stuff breaks relative includes
217          * XXX in some cases.   The problem likely is in
218          * XXX parse.c where it does special things in
219          * XXX ParseDoInclude if the file is relateive
220          * XXX or absolute and not a system file.  There
221          * XXX it assumes that if the current file that's
222          * XXX being included is absolute, that any files
223          * XXX that it includes shouldn't do the -I path
224          * XXX stuff, which is inconsistant with historical
225          * XXX behavior.  However, I can't pentrate the mists
226          * XXX further, so I'm putting this workaround in
227          * XXX here until such time as the underlying bug
228          * XXX can be fixed.
229          */
230         if (realpath(path, path) == NULL) {
231                 stream = NULL;
232         } else {
233                 stream = fopen(path, "r");
234         }
235 #else
236         stream = fopen(path, "r");
237 #endif
238         if (stream != NULL) {
239                 if (strcmp(file, ".depend") != 0)
240                         Var_SetGlobal("MAKEFILE", file);
241                 Parse_File(parser, cli, path, stream);
242                 fclose(stream);
243                 return (TRUE);
244         }
245
246         /* look in -I and system include directories. */
247         fname = estrdup(file);
248         name = NULL;
249         if (name == NULL)
250                 name = Path_FindFile(fname, &cli->parseIncPath);
251         if (name == NULL)
252                 name = Path_FindFile(fname, &cli->sysIncPath);
253
254         if (name != NULL) {
255                 stream = fopen(name, "r");
256                 if (stream != NULL) {
257                         /*
258                          * set the MAKEFILE variable desired by System V fans
259                          * -- the placement of the setting here means it gets
260                          * set to the last makefile specified, as it is set
261                          * by SysV make.
262                          */
263                         if (strcmp(file, ".depend") != 0)
264                                 Var_SetGlobal("MAKEFILE", name);
265                         Parse_File(parser, cli, name, stream);
266                         fclose(stream);
267                         return (TRUE);
268                 }
269         }
270
271         return (FALSE); /* no makefile found */
272 }
273
274 /**
275  * Read in the built-in rules first, followed by the specified
276  * makefiles or the one of the default makefiles.  Finally .depend
277  * makefile.
278  */
279 static void
280 ReadInputFiles(Parser *parser, CLI *cli, const char curdir[], const char objdir[])
281 {
282         if (cli->builtins) {
283                 char    defsysmk[] = PATH_DEFSYSMK;     /* Path of sys.mk */
284                 Lst     sysMkPath = Lst_Initializer(sysMkPath);
285                 LstNode *ln;
286
287                 Path_Expand(defsysmk, &cli->sysIncPath, &sysMkPath);
288                 if (Lst_IsEmpty(&sysMkPath))
289                         Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
290
291                 LST_FOREACH(ln, &sysMkPath) {
292                         char *name = Lst_Datum(ln);
293                         if (!ReadMakefile(parser, cli, name, curdir, objdir))
294                                 Fatal("make: cannot open %s.", name);
295                 }
296                 Lst_Destroy(&sysMkPath, free);
297         }
298
299         if (!Lst_IsEmpty(&cli->makefiles)) {
300                 LstNode *ln;
301
302                 LST_FOREACH(ln, &cli->makefiles) {
303                         char *name = Lst_Datum(ln);
304                         if (!ReadMakefile(parser, cli, name, curdir, objdir))
305                                 Fatal("make: cannot open %s.", name);
306                 }
307         } else if (ReadMakefile(parser, cli, "BSDmakefile", curdir, objdir)) {
308                 /* read BSDmakefile */
309         } else if (ReadMakefile(parser, cli, "makefile", curdir, objdir)) {
310                 /* read makefile */
311         } else if (ReadMakefile(parser, cli, "Makefile", curdir, objdir)) {
312                 /* read Makefile */
313         } else {
314                 /* No Makefile found */
315         }
316
317         ReadMakefile(parser, cli, ".depend", curdir, objdir);
318 }
319
320 /**
321  * Main_ParseWarn
322  *
323  *      Handle argument to warning option.
324  */
325 int
326 Main_ParseWarn(const char *arg, int iscmd)
327 {
328         int i, neg;
329
330         static const struct {
331                 const char      *option;
332                 uint32_t        flag;
333         } options[] = {
334                 { "dirsyntax",  WARN_DIRSYNTAX },
335                 { NULL,         0 }
336         };
337
338         neg = 0;
339         if (arg[0] == 'n' && arg[1] == 'o') {
340                 neg = 1;
341                 arg += 2;
342         }
343
344         for (i = 0; options[i].option != NULL; i++)
345                 if (strcmp(arg, options[i].option) == 0)
346                         break;
347
348         if (options[i].option == NULL)
349                 /* unknown option */
350                 return (-1);
351
352         if (iscmd) {
353                 if (!neg) {
354                         warn_cmd |= options[i].flag;
355                         warn_nocmd &= ~options[i].flag;
356                         warn_flags |= options[i].flag;
357                 } else {
358                         warn_nocmd |= options[i].flag;
359                         warn_cmd &= ~options[i].flag;
360                         warn_flags &= ~options[i].flag;
361                 }
362         } else {
363                 if (!neg) {
364                         warn_flags |= (options[i].flag & ~warn_nocmd);
365                 } else {
366                         warn_flags &= ~(options[i].flag | warn_cmd);
367                 }
368         }
369         return (0);
370 }
371
372 /**
373  * MainParseArgs
374  *      Parse a given argument vector. Called from main() and from
375  *      Main_ParseArgLine() when the .MAKEFLAGS target is used.
376  *
377  *      XXX: Deal with command line overriding .MAKEFLAGS in makefile
378  *
379  * Side Effects:
380  *      Various global and local flags will be set depending on the flags
381  *      given
382  */
383 static void
384 MainParseArgs(CLI *cli, int argc, char **argv)
385 {
386         int c;
387         Boolean found_dd = FALSE;
388
389 rearg:
390         optind = 1;     /* since we're called more than once */
391         optreset = 1;
392 #define OPTFLAGS "ABC:D:E:I:PSV:Xd:ef:ij:km:nqrstvx:"
393         for (;;) {
394                 if ((optind < argc) && strcmp(argv[optind], "--") == 0) {
395                         found_dd = TRUE;
396                 }
397                 if ((c = getopt(argc, argv, OPTFLAGS)) == -1) {
398                         break;
399                 }
400                 switch(c) {
401
402                 case 'A':
403                         arch_fatal = FALSE;
404                         MFLAGS_append("-A", NULL);
405                         break;
406                 case 'C':
407                         if (chdir(optarg) == -1)
408                                 err(1, "chdir %s", optarg);
409                         break;
410                 case 'D':
411                         Var_SetGlobal(optarg, "1");
412                         MFLAGS_append("-D", optarg);
413                         break;
414                 case 'I':
415                         Path_AddDir(&cli->parseIncPath, optarg);
416                         MFLAGS_append("-I", optarg);
417                         break;
418                 case 'V':
419                         Lst_AtEnd(&cli->variables, estrdup(optarg));
420                         MFLAGS_append("-V", optarg);
421                         break;
422                 case 'X':
423                         cli->expandVars = FALSE;
424                         break;
425                 case 'B':
426                         compatMake = TRUE;
427                         MFLAGS_append("-B", NULL);
428                         unsetenv("MAKE_JOBS_FIFO");
429                         break;
430                 case 'P':
431                         usePipes = FALSE;
432                         MFLAGS_append("-P", NULL);
433                         break;
434                 case 'S':
435                         keepgoing = FALSE;
436                         MFLAGS_append("-S", NULL);
437                         break;
438                 case 'd': {
439                         char *modules = optarg;
440
441                         for (; *modules; ++modules)
442                                 switch (*modules) {
443                                 case 'A':
444                                         debug = ~0;
445                                         break;
446                                 case 'a':
447                                         debug |= DEBUG_ARCH;
448                                         break;
449                                 case 'c':
450                                         debug |= DEBUG_COND;
451                                         break;
452                                 case 'd':
453                                         debug |= DEBUG_DIR;
454                                         break;
455                                 case 'f':
456                                         debug |= DEBUG_FOR;
457                                         break;
458                                 case 'g':
459                                         if (modules[1] == '1') {
460                                                 debug |= DEBUG_GRAPH1;
461                                                 ++modules;
462                                         }
463                                         else if (modules[1] == '2') {
464                                                 debug |= DEBUG_GRAPH2;
465                                                 ++modules;
466                                         }
467                                         break;
468                                 case 'j':
469                                         debug |= DEBUG_JOB;
470                                         break;
471                                 case 'l':
472                                         debug |= DEBUG_LOUD;
473                                         break;
474                                 case 'm':
475                                         debug |= DEBUG_MAKE;
476                                         break;
477                                 case 's':
478                                         debug |= DEBUG_SUFF;
479                                         break;
480                                 case 't':
481                                         debug |= DEBUG_TARG;
482                                         break;
483                                 case 'v':
484                                         debug |= DEBUG_VAR;
485                                         break;
486                                 default:
487                                         warnx("illegal argument to d option "
488                                             "-- %c", *modules);
489                                         usage();
490                                 }
491                         MFLAGS_append("-d", optarg);
492                         break;
493                 }
494                 case 'E':
495                         Lst_AtEnd(&envFirstVars, estrdup(optarg));
496                         MFLAGS_append("-E", optarg);
497                         break;
498                 case 'e':
499                         checkEnvFirst = TRUE;
500                         MFLAGS_append("-e", NULL);
501                         break;
502                 case 'f':
503                         Lst_AtEnd(&cli->makefiles, estrdup(optarg));
504                         break;
505                 case 'i':
506                         ignoreErrors = TRUE;
507                         MFLAGS_append("-i", NULL);
508                         break;
509                 case 'j': {
510                         char *endptr;
511
512                         cli->forceJobs = TRUE;
513                         jobLimit = strtol(optarg, &endptr, 10);
514                         if (jobLimit <= 0 || *endptr != '\0') {
515                                 warnx("illegal number, -j argument -- %s",
516                                     optarg);
517                                 usage();
518                         }
519                         MFLAGS_append("-j", optarg);
520                         break;
521                 }
522                 case 'k':
523                         keepgoing = TRUE;
524                         MFLAGS_append("-k", NULL);
525                         break;
526                 case 'm':
527                         Path_AddDir(&cli->sysIncPath, optarg);
528                         MFLAGS_append("-m", optarg);
529                         break;
530                 case 'n':
531                         noExecute = TRUE;
532                         MFLAGS_append("-n", NULL);
533                         break;
534                 case 'q':
535                         cli->queryFlag = TRUE;
536                         /* Kind of nonsensical, wot? */
537                         MFLAGS_append("-q", NULL);
538                         break;
539                 case 'r':
540                         cli->builtins = FALSE;
541                         MFLAGS_append("-r", NULL);
542                         break;
543                 case 's':
544                         beSilent = TRUE;
545                         MFLAGS_append("-s", NULL);
546                         break;
547                 case 't':
548                         touchFlag = TRUE;
549                         MFLAGS_append("-t", NULL);
550                         break;
551                 case 'v':
552                         beVerbose = TRUE;
553                         MFLAGS_append("-v", NULL);
554                         break;
555                 case 'x':
556                         if (Main_ParseWarn(optarg, 1) != -1)
557                                 MFLAGS_append("-x", optarg);
558                         break;
559                 default:
560                 case '?':
561                         usage();
562                 }
563         }
564         argv += optind;
565         argc -= optind;
566
567         oldVars = TRUE;
568
569         /*
570          * Parse the rest of the arguments.
571          *      o Check for variable assignments and perform them if so.
572          *      o Check for more flags and restart getopt if so.
573          *      o Anything else is taken to be a target and added
574          *        to the end of the "create" list.
575          */
576         for (; *argv != NULL; ++argv, --argc) {
577                 if (Parse_IsVar(*argv)) {
578                         char *ptr = MAKEFLAGS_quote(*argv);
579
580                         Var_Append(".MAKEFLAGS", ptr, VAR_GLOBAL);
581                         Parse_DoVar(*argv, VAR_CMD);
582                         free(ptr);
583
584                 } else if ((*argv)[0] == '-') {
585                         if ((*argv)[1] == '\0') {
586                                 /*
587                                  * (*argv) is a single dash, so we
588                                  * just ignore it.
589                                  */
590                         } else if (found_dd) {
591                                 /*
592                                  * Double dash has been found, ignore
593                                  * any more options.  But what do we do
594                                  * with it?  For now treat it like a target.
595                                  */
596                                 Lst_AtEnd(&cli->create, estrdup(*argv));
597                         } else {
598                                 /*
599                                  * (*argv) is a -flag, so backup argv and
600                                  * argc.  getopt() expects options to start
601                                  * in the 2nd position.
602                                  */
603                                 argc++;
604                                 argv--;
605                                 goto rearg;
606                         }
607
608                 } else if ((*argv)[0] == '\0') {
609                         Punt("illegal (null) argument.");
610
611                 } else {
612                         Lst_AtEnd(&cli->create, estrdup(*argv));
613                 }
614         }
615 }
616
617 /**
618  * Main_ParseArgLine
619  *      Used by the parse module when a .MFLAGS or .MAKEFLAGS target
620  *      is encountered and by main() when reading the .MAKEFLAGS envariable.
621  *      Takes a line of arguments and breaks it into its
622  *      component words and passes those words and the number of them to the
623  *      MainParseArgs function.
624  *      The line should have all its leading whitespace removed.
625  *
626  * Side Effects:
627  *      Only those that come from the various arguments.
628  */
629 void
630 Main_ParseArgLine(CLI *cli, const char line[], int mflags)
631 {
632         ArgArray        aa;
633
634         if (mflags) {
635                 MAKEFLAGS_break(&aa, line);
636         } else {
637                 brk_string(&aa, line, TRUE);
638         }
639         MainParseArgs(cli, aa.argc, aa.argv);
640         ArgArray_Done(&aa);
641 }
642
643 /**
644  * Try to change the current working directory to path, and return
645  * the whole path using getcwd().
646  *
647  * @note for amd managed mount points we really should use pawd(1).
648  */
649 static int
650 chdir_verify_path(const char path[], char newdir[])
651 {
652         struct stat sb;
653
654         /*
655          * Check if the path is a directory.  If not fail without reporting
656          * an error.
657          */
658         if (stat(path, &sb) < 0) {
659                 return (0);
660         }
661         if (S_ISDIR(sb.st_mode) == 0) {
662                 return (0);
663         }
664
665         /*
666          * The path refers to a directory, so we try to change into it. If we
667          * fail, or we fail to obtain the path from root to the directory,
668          * then report an error and fail.
669          */
670         if (chdir(path) < 0) {
671                 warn("warning: %s", path);
672                 return (0);
673         }
674         if (getcwd(newdir, MAXPATHLEN) == NULL) {
675                 warn("warning: %s", path);
676                 return (0);
677         }
678         return (1);
679 }
680
681 static void
682 determine_objdir(const char machine[], char curdir[], char objdir[])
683 {
684         struct stat     sa;
685         char            newdir[MAXPATHLEN];
686         char            mdpath[MAXPATHLEN];
687         const char      *env;
688
689         /*
690          * Find a path to where we are... [-C directory] might have changed
691          * our current directory.
692          */
693         if (getcwd(curdir, MAXPATHLEN) == NULL)
694                 err(2, NULL);
695
696         if (stat(curdir, &sa) == -1)
697                 err(2, "%s", curdir);
698
699         /*
700          * The object directory location is determined using the
701          * following order of preference:
702          *
703          *      1. MAKEOBJDIRPREFIX`cwd`
704          *      2. MAKEOBJDIR
705          *      3. PATH_OBJDIR.${MACHINE}
706          *      4. PATH_OBJDIR
707          *      5. PATH_OBJDIRPREFIX`cwd`
708          *
709          * If one of the first two fails, use the current directory.
710          * If the remaining three all fail, use the current directory.
711          */
712         if ((env = getenv("MAKEOBJDIRPREFIX")) != NULL) {
713                 snprintf(mdpath, MAXPATHLEN, "%s%s", env, curdir);
714                 if (chdir_verify_path(mdpath, newdir)) {
715                         strcpy(objdir, newdir);
716                         return;
717                 }
718                 strcpy(objdir, curdir);
719                 return;
720         }
721
722         if ((env = getenv("MAKEOBJDIR")) != NULL) {
723                 if (chdir_verify_path(env, newdir)) {
724                         strcpy(objdir, newdir);
725                         return;
726                 }
727                 strcpy(objdir, curdir);
728                 return;
729         }
730
731         snprintf(mdpath, MAXPATHLEN, "%s.%s", PATH_OBJDIR, machine);
732         if (chdir_verify_path(mdpath, newdir)) {
733                 strcpy(objdir, newdir);
734                 return;
735         }
736
737         if (chdir_verify_path(PATH_OBJDIR, newdir)) {
738                 strcpy(objdir, newdir);
739                 return;
740         }
741
742         snprintf(mdpath, MAXPATHLEN, "%s%s", PATH_OBJDIRPREFIX, curdir);
743         if (chdir_verify_path(mdpath, newdir)) {
744                 strcpy(objdir, newdir);
745                 return;
746         }
747
748         strcpy(objdir, curdir);
749 }
750
751 /**
752  * Initialize various make variables.
753  *      MAKE also gets this name, for compatibility
754  *      .MAKEFLAGS gets set to the empty string just in case.
755  *      MFLAGS also gets initialized empty, for compatibility.
756  */
757 static void
758 InitVariables(const char progname[])
759 {
760         const char      *machine;
761         const char      *machine_arch;
762         const char      *machine_cpu;
763
764         Var_SetGlobal("MAKE", progname);
765         Var_SetGlobal(".MAKEFLAGS", "");
766         Var_SetGlobal("MFLAGS", "");
767
768         Var_SetGlobal(".DIRECTIVE_MAKEENV", "YES");
769         Var_SetGlobal(".ST_EXPORTVAR", "YES");
770 #ifdef MAKE_VERSION
771         Var_SetGlobal("MAKE_VERSION", MAKE_VERSION);
772 #endif
773
774         /*
775          * Get the name of this type of MACHINE from utsname
776          * so we can share an executable for similar machines.
777          * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
778          *
779          * Note that while MACHINE is decided at run-time,
780          * MACHINE_ARCH is always known at compile time.
781          */
782         if ((machine = getenv("MACHINE")) == NULL) {
783 #ifdef MACHINE
784                 machine = MACHINE;
785 #else
786                 static struct utsname   utsname;
787                 if (uname(&utsname) == -1)
788                         err(2, "uname");
789                 machine = utsname.machine;
790 #endif
791         }
792
793         if ((machine_arch = getenv("MACHINE_ARCH")) == NULL) {
794 #ifdef MACHINE_ARCH
795                 machine_arch = MACHINE_ARCH;
796 #else
797                 machine_arch = "unknown";
798 #endif
799         }
800
801         /*
802          * Set machine_cpu to the minumum supported CPU revision based
803          * on the target architecture, if not already set.
804          */
805         if ((machine_cpu = getenv("MACHINE_CPU")) == NULL) {
806                 if (!strcmp(machine_arch, "i386"))
807                         machine_cpu = "i386";
808                 else if (!strcmp(machine_arch, "alpha"))
809                         machine_cpu = "ev4";
810                 else
811                         machine_cpu = "unknown";
812         }
813
814         Var_SetGlobal("MACHINE", machine);
815         Var_SetGlobal("MACHINE_ARCH", machine_arch);
816         Var_SetGlobal("MACHINE_CPU", machine_cpu);
817 }
818
819 /**
820  * Build targets.
821  *
822  * We have read the entire graph and need to make
823  * a list of targets to create.  If none were given
824  * on the command line, we consult the parsing
825  * module to find the main target(s) to create.
826  */
827 static int
828 build_stuff(CLI *cli)
829 {
830         int     status;
831         Lst     targs = Lst_Initializer(targs);
832
833         if (Lst_IsEmpty(&cli->create))
834                 Parse_MainName(&targs);
835         else
836                 Targ_FindList(&targs, &cli->create, TARG_CREATE);
837
838         /* Traverse the graph, checking on all the targets */
839         if (compatMake) {
840                 status = Compat_Run(&targs, cli->queryFlag);
841         } else {
842                 status = Make_Run(&targs, cli->queryFlag);
843         }
844
845         Lst_Destroy(&targs, NOFREE);
846         return (status);
847 }
848
849 /**
850  * main
851  *      The main function, for obvious reasons. Initializes variables
852  *      and a few modules, then parses the arguments give it in the
853  *      environment and on the command line. Reads the system makefile
854  *      followed by either Makefile, makefile or the file given by the
855  *      -f argument. Sets the .MAKEFLAGS PMake variable based on all the
856  *      flags it has received by then uses either the Make or the Compat
857  *      module to create the initial list of targets.
858  *
859  * Results:
860  *      If -q was given, exits -1 if anything was out-of-date. Else it exits
861  *      0.
862  *
863  * Side Effects:
864  *      The program exits when done. Targets are created. etc. etc. etc.
865  */
866 int
867 main(int argc, char **argv)
868 {
869         CLI             cli;
870         Parser          parser;
871         int             status;         /* exit status */
872         char            curdir[MAXPATHLEN];     /* startup directory */
873         char            objdir[MAXPATHLEN];     /* where we chdir'ed to */
874         const char      *make_flags;
875
876         /*------------------------------------------------------------*
877          * This section initializes stuff that require no input.
878          *------------------------------------------------------------*/
879         /*
880          * Initialize program globals.
881          */
882         beSilent = FALSE;               /* Print commands as executed */
883         ignoreErrors = FALSE;           /* Pay attention to non-zero returns */
884         noExecute = FALSE;              /* Execute all commands */
885         keepgoing = FALSE;              /* Stop on error */
886         allPrecious = FALSE;            /* Remove targets when interrupted */
887         touchFlag = FALSE;              /* Actually update targets */
888         usePipes = TRUE;                /* Catch child output in pipes */
889         debug = 0;                      /* No debug verbosity, please. */
890         jobsRunning = FALSE;
891
892         jobLimit = DEFMAXJOBS;
893         compatMake = FALSE;             /* No compat mode */
894
895         /*
896          * Initialize program flags.
897          */
898         Lst_Init(&cli.makefiles);
899         Lst_Init(&cli.variables);
900         Lst_Init(&cli.create);
901         TAILQ_INIT(&cli.parseIncPath);
902         TAILQ_INIT(&cli.sysIncPath);
903
904         cli.expandVars = TRUE;
905         cli.builtins = TRUE;            /* Read the built-in rules */
906         cli.queryFlag = FALSE;
907         cli.forceJobs = FALSE;
908
909         /*
910          * Initialize the various modules.
911          */
912         Proc_Init();
913         Shell_Init(DEFSHELLNAME);
914         Targ_Init();
915         Suff_Init();
916         Dir_Init();
917
918         /*------------------------------------------------------------*
919          * This section initializes stuff that depend on things
920          * in the enviornment, command line, or a input file.
921          *------------------------------------------------------------*/
922         Var_Init(environ);
923
924         InitVariables(argv[0]);
925
926         /*
927          * First snag things out of the MAKEFLAGS environment
928          * variable.  Then parse the command line arguments.
929          */
930         if ((make_flags = getenv("MAKEFLAGS")) != NULL) {
931                 Main_ParseArgLine(&cli, make_flags, 1);
932         }
933         MainParseArgs(&cli, argc, argv);
934
935         determine_objdir(Var_Value("MACHINE", VAR_GLOBAL), curdir, objdir);
936         Var_SetGlobal(".CURDIR", curdir);
937         Var_SetGlobal(".OBJDIR", objdir);
938
939         /*
940          * Set up the .TARGETS variable to contain the list of targets to be
941          * created. If none specified, make the variable empty -- the parser
942          * will fill the thing in with the default or .MAIN target.
943          */
944         if (Lst_IsEmpty(&cli.create)) {
945                 Var_SetGlobal(".TARGETS", "");
946         } else {
947                 LstNode *ln;
948
949                 LST_FOREACH(ln, &cli.create) {
950                         char *name = Lst_Datum(ln);
951
952                         Var_Append(".TARGETS", name, VAR_GLOBAL);
953                 }
954         }
955
956         Dir_CurObj(curdir, objdir);
957
958         /*
959          * If no user-supplied system path was given (through the -m option)
960          * add the directories from the DEFSYSPATH (more than one may be given
961          * as dir1:...:dirn) to the system include path.
962          */
963         if (TAILQ_EMPTY(&cli.sysIncPath)) {
964                 char syspath[] = PATH_DEFSYSPATH;
965                 char *start = syspath;
966                 char *cp;
967
968                 while ((cp = strsep(&start, ":")) != NULL) {
969                         Path_AddDir(&cli.sysIncPath, cp);
970                 }
971         }
972
973         if (getenv("MAKE_JOBS_FIFO") != NULL)
974                 cli.forceJobs = TRUE;
975
976         /*
977          * Be compatible if user did not specify -j and did not explicitly
978          * turned compatibility on
979          */
980         if (compatMake == FALSE && cli.forceJobs == FALSE)
981                 compatMake = TRUE;
982
983         DEFAULT = NULL;
984         time(&now);
985
986         parser.create = &cli.create;
987         parser.parseIncPath = &cli.parseIncPath;
988         parser.sysIncPath = &cli.sysIncPath;
989
990         ReadInputFiles(&parser, &cli, curdir, objdir);
991
992         /*------------------------------------------------------------*
993          * We are finished processing inputs.
994          *------------------------------------------------------------*/
995
996         /* Install all the flags into the MAKE envariable. */
997         {
998                 const char *p;
999
1000                 p = Var_Value(".MAKEFLAGS", VAR_GLOBAL);
1001                 if (p != NULL && *p != '\0')
1002                         setenv("MAKEFLAGS", p, 1);
1003         }
1004
1005         /*
1006          * For compatibility, look at the directories in the VPATH variable
1007          * and add them to the search path, if the variable is defined. The
1008          * variable's value is in the same format as the PATH envariable, i.e.
1009          * <directory>:<directory>:<directory>...
1010          */
1011         if (Var_Exists("VPATH", VAR_CMD)) {
1012                 Buffer  *buf = Var_Subst("${VPATH}", VAR_CMD, FALSE);
1013                 char    *start = Buf_Data(buf);
1014                 char    *cp;
1015
1016                 while ((cp = strsep(&start, ":")) != NULL) {
1017                         Path_AddDir(&dirSearchPath, cp);
1018                 }
1019
1020                 Buf_Destroy(buf, TRUE);
1021         }
1022
1023         /*
1024          * Now that all search paths have been read for suffixes et al, it's
1025          * time to add the default search path to their lists...
1026          */
1027         Suff_DoPaths();
1028
1029         /* print the initial graph, if the user requested it */
1030         if (DEBUG(GRAPH1))
1031                 Targ_PrintGraph(1);
1032
1033         if (Lst_IsEmpty(&cli.variables)) {
1034                 status = build_stuff(&cli);
1035         } else {
1036                 /* Print the values of variables requested by the user. */
1037                 Var_Print(&cli.variables, cli.expandVars);
1038
1039                 /*
1040                  * XXX
1041                  * This should be a "don't care", we do not check
1042                  * the status of any files.  It might make sense to
1043                  * modify Var_Print() to indicate that one of the
1044                  * requested variables did not exist, and use that
1045                  * as the return status.
1046                  * XXX
1047                  */
1048                 status = cli.queryFlag ? 1 : 0;
1049         }
1050
1051         /* print the graph now it's been processed if the user requested it */
1052         if (DEBUG(GRAPH2))
1053                 Targ_PrintGraph(2);
1054
1055 #if 0
1056         TAILQ_DESTROY(&cli.sysIncPath);
1057         TAILQ_DESTROY(&cli.parseIncPath);
1058 #endif
1059         Lst_Destroy(&cli.create, free);
1060         Lst_Destroy(&cli.variables, free);
1061         Lst_Destroy(&cli.makefiles, free);
1062
1063         return (status);
1064 }
1065