1 /* $NetBSD: parse.c,v 1.443 2020/11/16 21:39:22 rillig Exp $ */
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 * Parsing of makefiles.
74 * Parse_File is the main entry point and controls most of the other
75 * functions in this module.
77 * The directories for the .include "..." directive are kept in
78 * 'parseIncPath', while those for .include <...> are kept in 'sysIncPath'.
79 * The targets currently being defined are kept in 'targets'.
82 * Parse_Init Initialize the module
84 * Parse_End Clean up the module
86 * Parse_File Parse a top-level makefile. Included files are
87 * handled by Parse_include_file though.
89 * Parse_IsVar Return TRUE if the given line is a variable
90 * assignment. Used by MainParseArgs to determine if
91 * an argument is a target or a variable assignment.
92 * Used internally for pretty much the same thing.
94 * Parse_Error Report a parse error, a warning or an informational
97 * Parse_MainName Returns a list of the main target to create.
100 #include <sys/types.h>
101 #include <sys/stat.h>
112 #include <sys/mman.h>
115 #define MAP_COPY MAP_PRIVATE
124 #include "pathnames.h"
126 /* "@(#)parse.c 8.3 (Berkeley) 3/19/94" */
127 MAKE_RCSID("$NetBSD: parse.c,v 1.443 2020/11/16 21:39:22 rillig Exp $");
129 /* types and constants */
132 * Structure for a file being read ("included file")
134 typedef struct IFile {
135 char *fname; /* name of file (relative? absolute?) */
136 Boolean fromForLoop; /* simulated .include by the .for loop */
137 int lineno; /* current line number in file */
138 int first_lineno; /* line number of start of text */
139 unsigned int cond_depth; /* 'if' nesting when file opened */
140 Boolean depending; /* state of doing_depend on EOF */
142 /* The buffer from which the file's content is read. */
144 char *buf_ptr; /* next char to be read */
147 char *(*nextbuf)(void *, size_t *); /* Function to get more data */
148 void *nextbuf_arg; /* Opaque arg for nextbuf() */
149 struct loadedfile *lf; /* loadedfile object, if any */
153 * Tokens for target attributes
155 typedef enum ParseSpecial {
156 SP_ATTRIBUTE, /* Generic attribute */
157 SP_BEGIN, /* .BEGIN */
158 SP_DEFAULT, /* .DEFAULT */
159 SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
161 SP_ERROR, /* .ERROR */
162 SP_IGNORE, /* .IGNORE */
163 SP_INCLUDES, /* .INCLUDES; not mentioned in the manual page */
164 SP_INTERRUPT, /* .INTERRUPT */
165 SP_LIBS, /* .LIBS; not mentioned in the manual page */
166 SP_MAIN, /* .MAIN and we don't have anything user-specified to
169 SP_MFLAGS, /* .MFLAGS or .MAKEFLAGS */
170 SP_NOMETA, /* .NOMETA */
171 SP_NOMETA_CMP, /* .NOMETA_CMP */
172 SP_NOPATH, /* .NOPATH */
173 SP_NOT, /* Not special */
174 SP_NOTPARALLEL, /* .NOTPARALLEL or .NO_PARALLEL */
175 SP_NULL, /* .NULL; not mentioned in the manual page */
176 SP_OBJDIR, /* .OBJDIR */
177 SP_ORDER, /* .ORDER */
178 SP_PARALLEL, /* .PARALLEL; not mentioned in the manual page */
179 SP_PATH, /* .PATH or .PATH.suffix */
180 SP_PHONY, /* .PHONY */
182 SP_POSIX, /* .POSIX; not mentioned in the manual page */
184 SP_PRECIOUS, /* .PRECIOUS */
185 SP_SHELL, /* .SHELL */
186 SP_SILENT, /* .SILENT */
187 SP_SINGLESHELL, /* .SINGLESHELL; not mentioned in the manual page */
188 SP_STALE, /* .STALE */
189 SP_SUFFIXES, /* .SUFFIXES */
193 typedef List SearchPathList;
194 typedef ListNode SearchPathListNode;
199 * The main target to create. This is the first target on the first
200 * dependency line in the first makefile.
202 static GNode *mainNode;
206 /* During parsing, the targets from the left-hand side of the currently
207 * active dependency line, or NULL if the current line does not belong to a
208 * dependency line, for example because it is a variable assignment.
210 * See unit-tests/deptgt.mk, keyword "parse.c:targets". */
211 static GNodeList *targets;
214 /* All shell commands for all targets, in no particular order and possibly
215 * with duplicates. Kept in a separate list since the commands from .USE or
216 * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
217 * easily understandable ownership over the allocated strings. */
218 static StringList *targCmds;
222 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
223 * seen, then set to each successive source on the line.
225 static GNode *order_pred;
229 /* number of fatal errors */
230 static int fatals = 0;
233 * Variables for doing includes
236 /* The include chain of makefiles. At the bottom is the top-level makefile
237 * from the command line, and on top of that, there are the included files or
238 * .for loops, up to and including the current file.
240 * This data could be used to print stack traces on parse errors. As of
241 * 2020-09-14, this is not done though. It seems quite simple to print the
242 * tuples (fname:lineno:fromForLoop), from top to bottom. This simple idea is
243 * made complicated by the fact that the .for loops also use this stack for
244 * storing information.
246 * The lineno fields of the IFiles with fromForLoop == TRUE look confusing,
247 * which is demonstrated by the test 'include-main.mk'. They seem sorted
248 * backwards since they tell the number of completely parsed lines, which for
249 * a .for loop is right after the terminating .endfor. To compensate for this
250 * confusion, there is another field first_lineno pointing at the start of the
251 * .for loop, 1-based for human consumption.
253 * To make the stack trace intuitive, the entry below the first .for loop must
254 * be ignored completely since neither its lineno nor its first_lineno is
255 * useful. Instead, the topmost of each chain of .for loop needs to be
256 * printed twice, once with its first_lineno and once with its lineno.
258 * As of 2020-10-28, using the above rules, the stack trace for the .info line
259 * in include-subsub.mk would be:
261 * includes[5]: include-subsub.mk:4
262 * (lineno, from an .include)
263 * includes[4]: include-sub.mk:32
264 * (lineno, from a .for loop below an .include)
265 * includes[4]: include-sub.mk:31
266 * (first_lineno, from a .for loop, lineno == 32)
267 * includes[3]: include-sub.mk:30
268 * (first_lineno, from a .for loop, lineno == 33)
269 * includes[2]: include-sub.mk:29
270 * (first_lineno, from a .for loop, lineno == 34)
271 * includes[1]: include-sub.mk:35
272 * (not printed since it is below a .for loop)
273 * includes[0]: include-main.mk:27
275 static Vector /* of IFile */ includes;
280 return Vector_Get(&includes, i);
283 /* The file that is currently being read. */
287 return GetInclude(includes.len - 1);
291 SearchPath *parseIncPath; /* dirs for "..." includes */
292 SearchPath *sysIncPath; /* dirs for <...> includes */
293 SearchPath *defSysIncPath; /* default for sysIncPath */
298 * The parseKeywords table is searched using binary search when deciding
299 * if a target or source is special. The 'spec' field is the ParseSpecial
300 * type of the keyword (SP_NOT if the keyword isn't special as a target) while
301 * the 'op' field is the operator to apply to the list of targets if the
302 * keyword is used as a source ("0" if the keyword isn't special as a source)
304 static const struct {
305 const char *name; /* Name of keyword */
306 ParseSpecial spec; /* Type when used as a target */
307 GNodeType op; /* Operator when used as a source */
308 } parseKeywords[] = {
309 { ".BEGIN", SP_BEGIN, 0 },
310 { ".DEFAULT", SP_DEFAULT, 0 },
311 { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, 0 },
312 { ".END", SP_END, 0 },
313 { ".ERROR", SP_ERROR, 0 },
314 { ".EXEC", SP_ATTRIBUTE, OP_EXEC },
315 { ".IGNORE", SP_IGNORE, OP_IGNORE },
316 { ".INCLUDES", SP_INCLUDES, 0 },
317 { ".INTERRUPT", SP_INTERRUPT, 0 },
318 { ".INVISIBLE", SP_ATTRIBUTE, OP_INVISIBLE },
319 { ".JOIN", SP_ATTRIBUTE, OP_JOIN },
320 { ".LIBS", SP_LIBS, 0 },
321 { ".MADE", SP_ATTRIBUTE, OP_MADE },
322 { ".MAIN", SP_MAIN, 0 },
323 { ".MAKE", SP_ATTRIBUTE, OP_MAKE },
324 { ".MAKEFLAGS", SP_MFLAGS, 0 },
325 { ".META", SP_META, OP_META },
326 { ".MFLAGS", SP_MFLAGS, 0 },
327 { ".NOMETA", SP_NOMETA, OP_NOMETA },
328 { ".NOMETA_CMP", SP_NOMETA_CMP, OP_NOMETA_CMP },
329 { ".NOPATH", SP_NOPATH, OP_NOPATH },
330 { ".NOTMAIN", SP_ATTRIBUTE, OP_NOTMAIN },
331 { ".NOTPARALLEL", SP_NOTPARALLEL, 0 },
332 { ".NO_PARALLEL", SP_NOTPARALLEL, 0 },
333 { ".NULL", SP_NULL, 0 },
334 { ".OBJDIR", SP_OBJDIR, 0 },
335 { ".OPTIONAL", SP_ATTRIBUTE, OP_OPTIONAL },
336 { ".ORDER", SP_ORDER, 0 },
337 { ".PARALLEL", SP_PARALLEL, 0 },
338 { ".PATH", SP_PATH, 0 },
339 { ".PHONY", SP_PHONY, OP_PHONY },
341 { ".POSIX", SP_POSIX, 0 },
343 { ".PRECIOUS", SP_PRECIOUS, OP_PRECIOUS },
344 { ".RECURSIVE", SP_ATTRIBUTE, OP_MAKE },
345 { ".SHELL", SP_SHELL, 0 },
346 { ".SILENT", SP_SILENT, OP_SILENT },
347 { ".SINGLESHELL", SP_SINGLESHELL, 0 },
348 { ".STALE", SP_STALE, 0 },
349 { ".SUFFIXES", SP_SUFFIXES, 0 },
350 { ".USE", SP_ATTRIBUTE, OP_USE },
351 { ".USEBEFORE", SP_ATTRIBUTE, OP_USEBEFORE },
352 { ".WAIT", SP_WAIT, 0 },
358 /* XXX: What is the lifetime of this path? Who manages the memory? */
359 const char *path; /* name, for error reports */
360 char *buf; /* contents buffer */
361 size_t len; /* length of contents */
362 size_t maplen; /* length of mmap area, or 0 */
363 Boolean used; /* XXX: have we used the data yet */
366 /* XXX: What is the lifetime of the path? Who manages the memory? */
367 static struct loadedfile *
368 loadedfile_create(const char *path)
370 struct loadedfile *lf;
372 lf = bmake_malloc(sizeof *lf);
373 lf->path = path == NULL ? "(stdin)" : path;
382 loadedfile_destroy(struct loadedfile *lf)
384 if (lf->buf != NULL) {
387 munmap(lf->buf, lf->maplen);
396 * nextbuf() operation for loadedfile, as needed by the weird and twisted
397 * logic below. Once that's cleaned up, we can get rid of lf->used...
400 loadedfile_nextbuf(void *x, size_t *len)
402 struct loadedfile *lf = x;
413 * Try to get the size of a file.
416 load_getsize(int fd, size_t *ret)
420 if (fstat(fd, &st) < 0)
423 if (!S_ISREG(st.st_mode))
427 * st_size is an off_t, which is 64 bits signed; *ret is
428 * size_t, which might be 32 bits unsigned or 64 bits
429 * unsigned. Rather than being elaborate, just punt on
430 * files that are more than 2^31 bytes. We should never
431 * see a makefile that size in practice...
433 * While we're at it reject negative sizes too, just in case.
435 if (st.st_size < 0 || st.st_size > 0x7fffffff)
438 *ret = (size_t)st.st_size;
444 loadedfile_mmap(struct loadedfile *lf, int fd)
446 static unsigned long pagesize = 0;
448 if (!load_getsize(fd, &lf->len))
451 /* found a size, try mmap */
454 pagesize = (unsigned long)sysconf(_SC_PAGESIZE);
456 if (pagesize == 0 || pagesize == (unsigned long)-1)
459 /* round size up to a page */
460 lf->maplen = pagesize * ((lf->len + pagesize - 1) / pagesize);
463 * XXX hack for dealing with empty files; remove when
464 * we're no longer limited by interfacing to the old
465 * logic elsewhere in this file.
468 lf->maplen = pagesize;
471 * FUTURE: remove PROT_WRITE when the parser no longer
472 * needs to scribble on the input.
474 lf->buf = mmap(NULL, lf->maplen, PROT_READ|PROT_WRITE,
475 MAP_FILE|MAP_COPY, fd, 0);
476 if (lf->buf == MAP_FAILED)
479 if (lf->len == lf->maplen && lf->buf[lf->len - 1] != '\n') {
480 char *b = bmake_malloc(lf->len + 1);
482 memcpy(b, lf->buf, lf->len++);
483 munmap(lf->buf, lf->maplen);
495 * Until the path search logic can be moved under here instead of
496 * being in the caller in another source file, we need to have the fd
497 * passed in already open. Bleh.
499 * If the path is NULL, use stdin.
501 static struct loadedfile *
502 loadfile(const char *path, int fd)
504 struct loadedfile *lf;
508 lf = loadedfile_create(path);
515 fd = open(path, O_RDONLY);
518 Error("%s: %s", path, strerror(errno));
525 if (loadedfile_mmap(lf, fd))
529 /* cannot mmap; load the traditional way */
533 lf->buf = bmake_malloc(lf->len);
537 assert(bufpos <= lf->len);
538 if (bufpos == lf->len) {
539 if (lf->len > SIZE_MAX/2) {
541 Error("%s: file too large", path);
545 lf->buf = bmake_realloc(lf->buf, lf->len);
547 assert(bufpos < lf->len);
548 result = read(fd, lf->buf + bufpos, lf->len - bufpos);
550 Error("%s: read error: %s", path, strerror(errno));
556 bufpos += (size_t)result;
558 assert(bufpos <= lf->len);
561 /* truncate malloc region to actual length (maybe not useful) */
563 /* as for mmap case, ensure trailing \n */
564 if (lf->buf[lf->len - 1] != '\n')
566 lf->buf = bmake_realloc(lf->buf, lf->len);
567 lf->buf[lf->len - 1] = '\n';
581 /* Check if the current character is escaped on the current line. */
583 ParseIsEscaped(const char *line, const char *c)
585 Boolean active = FALSE;
595 /* Add the filename and lineno to the GNode so that we remember where it
596 * was first defined. */
600 IFile *curFile = CurFile();
601 gn->fname = curFile->fname;
602 gn->lineno = curFile->lineno;
605 /* Look in the table of keywords for one matching the given string.
606 * Return the index of the keyword, or -1 if it isn't there. */
608 ParseFindKeyword(const char *str)
611 int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
614 int cur = start + (end - start) / 2;
615 int diff = strcmp(str, parseKeywords[cur].name);
623 } while (start <= end);
629 PrintLocation(FILE *f, const char *fname, size_t lineno)
631 char dirbuf[MAXPATHLEN+1];
632 const char *dir, *base;
633 void *dir_freeIt, *base_freeIt;
635 if (*fname == '/' || strcmp(fname, "(stdin)") == 0) {
636 (void)fprintf(f, "\"%s\" line %zu: ", fname, lineno);
640 /* Find out which makefile is the culprit.
641 * We try ${.PARSEDIR} and apply realpath(3) if not absolute. */
643 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &dir_freeIt);
647 dir = realpath(dir, dirbuf);
649 base = Var_Value(".PARSEFILE", VAR_GLOBAL, &base_freeIt);
651 const char *slash = strrchr(fname, '/');
652 base = slash != NULL ? slash + 1 : fname;
655 (void)fprintf(f, "\"%s/%s\" line %zu: ", dir, base, lineno);
656 bmake_free(base_freeIt);
657 bmake_free(dir_freeIt);
661 ParseVErrorInternal(FILE *f, const char *fname, size_t lineno,
662 ParseErrorLevel type, const char *fmt, va_list ap)
664 static Boolean fatal_warning_error_printed = FALSE;
666 (void)fprintf(f, "%s: ", progname);
669 PrintLocation(f, fname, lineno);
670 if (type == PARSE_WARNING)
671 (void)fprintf(f, "warning: ");
672 (void)vfprintf(f, fmt, ap);
673 (void)fprintf(f, "\n");
676 if (type == PARSE_INFO)
678 if (type == PARSE_FATAL || opts.parseWarnFatal)
680 if (opts.parseWarnFatal && !fatal_warning_error_printed) {
681 Error("parsing warnings being treated as errors");
682 fatal_warning_error_printed = TRUE;
687 ParseErrorInternal(const char *fname, size_t lineno,
688 ParseErrorLevel type, const char *fmt, ...)
692 (void)fflush(stdout);
694 ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
697 if (opts.debug_file != stderr && opts.debug_file != stdout) {
699 ParseVErrorInternal(opts.debug_file, fname, lineno, type,
705 /* Print a parse error message, including location information.
707 * If the level is PARSE_FATAL, continue parsing until the end of the
708 * current top-level makefile, then exit (see Parse_File).
710 * Fmt is given without a trailing newline. */
712 Parse_Error(ParseErrorLevel type, const char *fmt, ...)
718 if (includes.len == 0) {
722 IFile *curFile = CurFile();
723 fname = curFile->fname;
724 lineno = (size_t)curFile->lineno;
728 (void)fflush(stdout);
729 ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
732 if (opts.debug_file != stderr && opts.debug_file != stdout) {
734 ParseVErrorInternal(opts.debug_file, fname, lineno, type,
741 /* Parse and handle a .info, .warning or .error directive.
742 * For an .error directive, immediately exit. */
744 ParseMessage(const char *directive)
746 const char *p = directive;
747 int mtype = *p == 'i' ? PARSE_INFO :
748 *p == 'w' ? PARSE_WARNING : PARSE_FATAL;
751 while (ch_isalpha(*p))
754 return FALSE; /* missing argument */
756 cpp_skip_whitespace(&p);
757 (void)Var_Subst(p, VAR_CMDLINE, VARE_WANTRES, &arg);
758 /* TODO: handle errors */
760 Parse_Error(mtype, "%s", arg);
763 if (mtype == PARSE_FATAL) {
764 PrintOnError(NULL, NULL);
770 /* Add the child to the parent's children.
772 * Additionally, add the parent to the child's parents, but only if the
773 * target is not special. An example for such a special target is .END,
774 * which does not need to be informed once the child target has been made. */
776 LinkSource(GNode *pgn, GNode *cgn, Boolean isSpecial)
778 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(pgn->cohorts))
779 pgn = pgn->cohorts->last->datum;
781 Lst_Append(pgn->children, cgn);
784 /* Special targets like .END don't need any children. */
786 Lst_Append(cgn->parents, pgn);
789 debug_printf("# %s: added child %s - %s\n",
790 __func__, pgn->name, cgn->name);
791 Targ_PrintNode(pgn, 0);
792 Targ_PrintNode(cgn, 0);
796 /* Add the node to each target from the current dependency group. */
798 LinkToTargets(GNode *gn, Boolean isSpecial)
801 for (ln = targets->first; ln != NULL; ln = ln->next)
802 LinkSource(ln->datum, gn, isSpecial);
806 TryApplyDependencyOperator(GNode *gn, GNodeType op)
809 * If the node occurred on the left-hand side of a dependency and the
810 * operator also defines a dependency, they must match.
812 if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
813 ((op & OP_OPMASK) != (gn->type & OP_OPMASK)))
815 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
819 if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
821 * If the node was of the left-hand side of a '::' operator, we need
822 * to create a new instance of it for the children and commands on
823 * this dependency line since each of these dependency groups has its
824 * own attributes and commands, separate from the others.
826 * The new instance is placed on the 'cohorts' list of the
827 * initial one (note the initial one is not on its own cohorts list)
828 * and the new instance is linked to all parents of the initial
834 * Propagate copied bits to the initial node. They'll be propagated
835 * back to the rest of the cohorts later.
837 gn->type |= op & ~OP_OPMASK;
839 cohort = Targ_NewInternalNode(gn->name);
843 * Make the cohort invisible as well to avoid duplicating it into
844 * other variables. True, parents of this target won't tend to do
845 * anything with their local variables, but better safe than
846 * sorry. (I think this is pointless now, since the relevant list
847 * traversals will no longer see this node anyway. -mycroft)
849 cohort->type = op | OP_INVISIBLE;
850 Lst_Append(gn->cohorts, cohort);
851 cohort->centurion = gn;
852 gn->unmade_cohorts++;
853 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
854 (unsigned int)gn->unmade_cohorts % 1000000);
857 * We don't want to nuke any previous flags (whatever they were) so we
858 * just OR the new operator into the old.
867 ApplyDependencyOperator(GNodeType op)
870 for (ln = targets->first; ln != NULL; ln = ln->next)
871 if (!TryApplyDependencyOperator(ln->datum, op))
876 ParseDoSrcKeyword(const char *src, ParseSpecial specType)
878 static int wait_number = 0;
882 if (*src == '.' && ch_isupper(src[1])) {
883 int keywd = ParseFindKeyword(src);
885 GNodeType op = parseKeywords[keywd].op;
887 ApplyDependencyOperator(op);
890 if (parseKeywords[keywd].spec == SP_WAIT) {
892 * We add a .WAIT node in the dependency list.
893 * After any dynamic dependencies (and filename globbing)
894 * have happened, it is given a dependency on each
895 * previous child, back until the previous .WAIT node.
896 * The next child won't be scheduled until the .WAIT node
898 * We give each .WAIT node a unique name (mainly for
901 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
902 gn = Targ_NewInternalNode(wait_src);
905 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
906 LinkToTargets(gn, specType != SP_NOT);
915 ParseDoSrcMain(const char *src)
918 * In a line like ".MAIN: source1 source2", it means we need to add
919 * the sources of said target to the list of things to create.
921 * Note that this will only be invoked if the user didn't specify a
922 * target on the command line. This is to allow .ifmake to succeed.
924 * XXX: Double-check all of the above comment.
926 Lst_Append(opts.create, bmake_strdup(src));
928 * Add the name to the .TARGETS variable as well, so the user can
929 * employ that, if desired.
931 Var_Append(".TARGETS", src, VAR_GLOBAL);
935 ParseDoSrcOrder(const char *src)
939 * Create proper predecessor/successor links between the previous
940 * source and the current one.
942 gn = Targ_GetNode(src);
945 if (order_pred != NULL) {
946 Lst_Append(order_pred->order_succ, gn);
947 Lst_Append(gn->order_pred, order_pred);
949 debug_printf("# %s: added Order dependency %s - %s\n",
950 __func__, order_pred->name, gn->name);
951 Targ_PrintNode(order_pred, 0);
952 Targ_PrintNode(gn, 0);
956 * The current source now becomes the predecessor for the next one.
962 ParseDoSrcOther(const char *src, GNodeType tOp, ParseSpecial specType)
967 * If the source is not an attribute, we need to find/create
968 * a node for it. After that we can apply any operator to it
969 * from a special target or link it to its parents, as
972 * In the case of a source that was the object of a :: operator,
973 * the attribute is applied to all of its instances (as kept in
974 * the 'cohorts' list of the node) or all the cohorts are linked
975 * to all the targets.
978 /* Find/create the 'src' node and attach to all targets */
979 gn = Targ_GetNode(src);
985 LinkToTargets(gn, specType != SP_NOT);
988 /* Given the name of a source in a dependency line, figure out if it is an
989 * attribute (such as .SILENT) and apply it to the targets if it is. Else
990 * decide if there is some attribute which should be applied *to* the source
991 * because of some special target (such as .PHONY) and apply it if so.
992 * Otherwise, make the source a child of the targets in the list 'targets'.
995 * tOp operator (if any) from special targets
996 * src name of the source to handle
999 ParseDoSrc(GNodeType tOp, const char *src, ParseSpecial specType)
1001 if (ParseDoSrcKeyword(src, specType))
1004 if (specType == SP_MAIN)
1005 ParseDoSrcMain(src);
1006 else if (specType == SP_ORDER)
1007 ParseDoSrcOrder(src);
1009 ParseDoSrcOther(src, tOp, specType);
1012 /* If we have yet to decide on a main target to make, in the absence of any
1013 * user input, we want the first target on the first dependency line that is
1014 * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made. */
1016 FindMainTarget(void)
1020 if (mainNode != NULL)
1023 for (ln = targets->first; ln != NULL; ln = ln->next) {
1024 GNode *gn = ln->datum;
1025 if (!(gn->type & OP_NOTARGET)) {
1034 * We got to the end of the line while we were still looking at targets.
1036 * Ending a dependency line without an operator is a Bozo no-no. As a
1037 * heuristic, this is also often triggered by undetected conflicts from
1041 ParseErrorNoDependency(const char *lstart)
1043 if ((strncmp(lstart, "<<<<<<", 6) == 0) ||
1044 (strncmp(lstart, "======", 6) == 0) ||
1045 (strncmp(lstart, ">>>>>>", 6) == 0))
1046 Parse_Error(PARSE_FATAL,
1047 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1048 else if (lstart[0] == '.') {
1049 const char *dirstart = lstart + 1;
1051 cpp_skip_whitespace(&dirstart);
1053 while (ch_isalnum(*dirend) || *dirend == '-')
1055 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
1056 (int)(dirend - dirstart), dirstart);
1058 Parse_Error(PARSE_FATAL, "Need an operator");
1062 ParseDependencyTargetWord(/*const*/ char **pp, const char *lstart)
1064 /*const*/ char *cp = *pp;
1066 while (*cp != '\0') {
1067 if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' || *cp == '(') &&
1068 !ParseIsEscaped(lstart, cp))
1073 * Must be a dynamic source (would have been expanded
1074 * otherwise), so call the Var module to parse the puppy
1075 * so we can safely advance beyond it...There should be
1076 * no errors in this, as they would have been discovered
1077 * in the initial Var_Subst and we wouldn't be here.
1079 const char *nested_p = cp;
1080 const char *nested_val;
1083 (void)Var_Parse(&nested_p, VAR_CMDLINE,
1084 VARE_WANTRES | VARE_UNDEFERR, &nested_val, &freeIt);
1085 /* TODO: handle errors */
1087 cp += nested_p - cp;
1095 /* Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER. */
1097 ParseDoDependencyTargetSpecial(ParseSpecial *inout_specType,
1099 SearchPathList **inout_paths)
1101 switch (*inout_specType) {
1103 if (*inout_paths == NULL)
1104 *inout_paths = Lst_New();
1105 Lst_Append(*inout_paths, dirSearchPath);
1108 /* Allow targets from the command line to override the .MAIN node. */
1109 if (!Lst_IsEmpty(opts.create))
1110 *inout_specType = SP_NOT;
1116 case SP_INTERRUPT: {
1117 GNode *gn = Targ_GetNode(line);
1120 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1121 Lst_Append(targets, gn);
1125 /* Need to create a node to hang commands on, but we don't want it
1126 * in the graph, nor do we want it to be the Main Target. We claim
1127 * the node is a transformation rule to make life easier later,
1128 * when we'll use Make_HandleUse to actually apply the .DEFAULT
1130 GNode *gn = GNode_New(".DEFAULT");
1131 gn->type |= OP_NOTMAIN|OP_TRANSFORM;
1132 Lst_Append(targets, gn);
1136 case SP_DELETE_ON_ERROR:
1137 deleteOnError = TRUE;
1139 case SP_NOTPARALLEL:
1142 case SP_SINGLESHELL:
1143 opts.compatMake = TRUE;
1154 * .PATH<suffix> has to be handled specially.
1155 * Call on the suffix module to give us a path to modify.
1158 ParseDoDependencyTargetPath(const char *line, SearchPathList **inout_paths)
1162 path = Suff_GetPath(&line[5]);
1164 Parse_Error(PARSE_FATAL,
1165 "Suffix '%s' not defined (yet)",
1170 if (*inout_paths == NULL)
1171 *inout_paths = Lst_New();
1172 Lst_Append(*inout_paths, path);
1178 * See if it's a special target and if so set specType to match it.
1181 ParseDoDependencyTarget(const char *line, ParseSpecial *inout_specType,
1182 GNodeType *out_tOp, SearchPathList **inout_paths)
1186 if (!(*line == '.' && ch_isupper(line[1])))
1190 * See if the target is a special target that must have it
1191 * or its sources handled specially.
1193 keywd = ParseFindKeyword(line);
1195 if (*inout_specType == SP_PATH && parseKeywords[keywd].spec != SP_PATH) {
1196 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1200 *inout_specType = parseKeywords[keywd].spec;
1201 *out_tOp = parseKeywords[keywd].op;
1203 ParseDoDependencyTargetSpecial(inout_specType, line, inout_paths);
1205 } else if (strncmp(line, ".PATH", 5) == 0) {
1206 *inout_specType = SP_PATH;
1207 if (!ParseDoDependencyTargetPath(line, inout_paths))
1214 ParseDoDependencyTargetMundane(char *line, StringList *curTargs)
1216 if (Dir_HasWildcards(line)) {
1218 * Targets are to be sought only in the current directory,
1219 * so create an empty path for the thing. Note we need to
1220 * use Dir_Destroy in the destruction of the path as the
1221 * Dir module could have added a directory to the path...
1223 SearchPath *emptyPath = Lst_New();
1225 Dir_Expand(line, emptyPath, curTargs);
1227 Lst_Destroy(emptyPath, Dir_Destroy);
1230 * No wildcards, but we want to avoid code duplication,
1231 * so create a list with the word on it.
1233 Lst_Append(curTargs, line);
1236 /* Apply the targets. */
1238 while (!Lst_IsEmpty(curTargs)) {
1239 char *targName = Lst_Dequeue(curTargs);
1240 GNode *gn = Suff_IsTransform(targName)
1241 ? Suff_AddTransform(targName)
1242 : Targ_GetNode(targName);
1246 Lst_Append(targets, gn);
1251 ParseDoDependencyTargetExtraWarn(char **pp, const char *lstart)
1253 Boolean warning = FALSE;
1256 while (*cp != '\0') {
1257 if (!ParseIsEscaped(lstart, cp) && (*cp == '!' || *cp == ':'))
1259 if (ParseIsEscaped(lstart, cp) || (*cp != ' ' && *cp != '\t'))
1264 Parse_Error(PARSE_WARNING, "Extra target ignored");
1270 ParseDoDependencyCheckSpec(ParseSpecial specType)
1274 Parse_Error(PARSE_WARNING,
1275 "Special and mundane targets don't mix. "
1276 "Mundane ones ignored");
1285 * These create nodes on which to hang commands, so targets
1286 * shouldn't be empty...
1289 /* Nothing special here -- targets can be empty if it wants. */
1295 ParseDoDependencyParseOp(char **pp, const char *lstart, GNodeType *out_op)
1297 const char *cp = *pp;
1307 *out_op = OP_DOUBLEDEP;
1310 *out_op = OP_DEPENDS;
1317 const char *msg = lstart[0] == '.' ? "Unknown directive"
1318 : "Missing dependency operator";
1319 Parse_Error(PARSE_FATAL, "%s", msg);
1325 ClearPaths(SearchPathList *paths)
1327 if (paths != NULL) {
1328 SearchPathListNode *ln;
1329 for (ln = paths->first; ln != NULL; ln = ln->next)
1330 Dir_ClearPath(ln->datum);
1337 ParseDoDependencySourcesEmpty(ParseSpecial specType, SearchPathList *paths)
1341 Suff_ClearSuffixes();
1347 opts.ignoreErrors = TRUE;
1350 opts.beSilent = TRUE;
1357 Var_Set("%POSIX", "1003.2", VAR_GLOBAL);
1366 AddToPaths(const char *dir, SearchPathList *paths)
1368 if (paths != NULL) {
1369 SearchPathListNode *ln;
1370 for (ln = paths->first; ln != NULL; ln = ln->next)
1371 (void)Dir_AddDir(ln->datum, dir);
1376 * If the target was one that doesn't take files as its sources
1377 * but takes something like suffixes, we take each
1378 * space-separated word on the line as a something and deal
1379 * with it accordingly.
1381 * If the target was .SUFFIXES, we take each source as a
1382 * suffix and add it to the list of suffixes maintained by the
1385 * If the target was a .PATH, we add the source as a directory
1386 * to search on the search path.
1388 * If it was .INCLUDES, the source is taken to be the suffix of
1389 * files which will be #included and whose search path should
1390 * be present in the .INCLUDES variable.
1392 * If it was .LIBS, the source is taken to be the suffix of
1393 * files which are considered libraries and whose search path
1394 * should be present in the .LIBS variable.
1396 * If it was .NULL, the source is the suffix to use when a file
1397 * has no valid suffix.
1399 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1400 * and will cause make to do a new chdir to that path.
1403 ParseDoDependencySourceSpecial(ParseSpecial specType, char *word,
1404 SearchPathList *paths)
1408 Suff_AddSuffix(word, &mainNode);
1411 AddToPaths(word, paths);
1414 Suff_AddInclude(word);
1423 Main_SetObjdir(FALSE, "%s", word);
1431 ParseDoDependencyTargets(char **inout_cp,
1434 ParseSpecial *inout_specType,
1435 GNodeType *inout_tOp,
1436 SearchPathList **inout_paths,
1437 StringList *curTargs)
1439 char *cp = *inout_cp;
1440 char *line = *inout_line;
1445 * Here LINE points to the beginning of the next word, and
1446 * LSTART points to the actual beginning of the line.
1449 /* Find the end of the next word. */
1451 ParseDependencyTargetWord(&cp, lstart);
1454 * If the word is followed by a left parenthesis, it's the
1455 * name of an object file inside an archive (ar file).
1457 if (!ParseIsEscaped(lstart, cp) && *cp == '(') {
1459 * Archives must be handled specially to make sure the OP_ARCHV
1460 * flag is set in their 'type' field, for one thing, and because
1461 * things like "archive(file1.o file2.o file3.o)" are permissible.
1462 * Arch_ParseArchive will set 'line' to be the first non-blank
1463 * after the archive-spec. It creates/finds nodes for the members
1464 * and places them on the given list, returning TRUE if all
1465 * went well and FALSE if there was an error in the
1466 * specification. On error, line should remain untouched.
1468 if (!Arch_ParseArchive(&line, targets, VAR_CMDLINE)) {
1469 Parse_Error(PARSE_FATAL,
1470 "Error in archive specification: \"%s\"", line);
1473 /* Done with this word; on to the next. */
1480 ParseErrorNoDependency(lstart);
1484 /* Insert a null terminator. */
1488 if (!ParseDoDependencyTarget(line, inout_specType, inout_tOp,
1493 * Have word in line. Get or create its node and stick it at
1494 * the end of the targets list
1496 if (*inout_specType == SP_NOT && *line != '\0')
1497 ParseDoDependencyTargetMundane(line, curTargs);
1498 else if (*inout_specType == SP_PATH && *line != '.' && *line != '\0')
1499 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1501 /* Don't need the inserted null terminator any more. */
1505 * If it is a special type and not .PATH, it's the only target we
1506 * allow on this line...
1508 if (*inout_specType != SP_NOT && *inout_specType != SP_PATH)
1509 ParseDoDependencyTargetExtraWarn(&cp, lstart);
1511 pp_skip_whitespace(&cp);
1516 if ((*line == '!' || *line == ':') && !ParseIsEscaped(lstart, line))
1526 ParseDoDependencySourcesSpecial(char *start, char *end,
1527 ParseSpecial specType, SearchPathList *paths)
1532 while (*end && !ch_isspace(*end))
1536 ParseDoDependencySourceSpecial(specType, start, paths);
1540 pp_skip_whitespace(&end);
1546 ParseDoDependencySourcesMundane(char *start, char *end,
1547 ParseSpecial specType, GNodeType tOp)
1549 while (*start != '\0') {
1551 * The targets take real sources, so we must beware of archive
1552 * specifications (i.e. things with left parentheses in them)
1553 * and handle them accordingly.
1555 for (; *end && !ch_isspace(*end); end++) {
1556 if (*end == '(' && end > start && end[-1] != '$') {
1558 * Only stop for a left parenthesis if it isn't at the
1559 * start of a word (that'll be for variable changes
1560 * later) and isn't preceded by a dollar sign (a dynamic
1568 GNodeList *sources = Lst_New();
1569 if (!Arch_ParseArchive(&start, sources, VAR_CMDLINE)) {
1570 Parse_Error(PARSE_FATAL,
1571 "Error in source archive spec \"%s\"", start);
1575 while (!Lst_IsEmpty(sources)) {
1576 GNode *gn = Lst_Dequeue(sources);
1577 ParseDoSrc(tOp, gn->name, specType);
1587 ParseDoSrc(tOp, start, specType);
1589 pp_skip_whitespace(&end);
1595 /* Parse a dependency line consisting of targets, followed by a dependency
1596 * operator, optionally followed by sources.
1598 * The nodes of the sources are linked as children to the nodes of the
1599 * targets. Nodes are created as necessary.
1601 * The operator is applied to each node in the global 'targets' list,
1602 * which is where the nodes found for the targets are kept, by means of
1603 * the ParseDoOp function.
1605 * The sources are parsed in much the same way as the targets, except
1606 * that they are expanded using the wildcarding scheme of the C-Shell,
1607 * and a target is created for each expanded word. Each of the resulting
1608 * nodes is then linked to each of the targets as one of its children.
1610 * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1611 * specially. These are the ones detailed by the specType variable.
1613 * The storing of transformation rules such as '.c.o' is also taken care of
1614 * here. A target is recognized as a transformation rule by calling
1615 * Suff_IsTransform. If it is a transformation rule, its node is gotten
1616 * from the suffix module via Suff_AddTransform rather than the standard
1617 * Targ_FindNode in the target module.
1619 * Upon return, the value of the line is unspecified.
1622 ParseDoDependency(char *line)
1624 char *cp; /* our current position */
1625 GNodeType op; /* the operator on the line */
1626 SearchPathList *paths; /* search paths to alter when parsing
1627 * a list of .PATH targets */
1628 GNodeType tOp; /* operator from special target */
1629 StringList *curTargs; /* target names to be found and added
1630 * to the targets list */
1631 char *lstart = line;
1634 * specType contains the SPECial TYPE of the current target. It is SP_NOT
1635 * if the target is unspecial. If it *is* special, however, the children
1636 * are linked as children of the parent but not vice versa.
1638 ParseSpecial specType = SP_NOT;
1640 DEBUG1(PARSE, "ParseDoDependency(%s)\n", line);
1645 curTargs = Lst_New();
1648 * First, grind through the targets.
1650 if (!ParseDoDependencyTargets(&cp, &line, lstart, &specType, &tOp, &paths,
1654 /* Don't need the list of target names anymore.
1655 * The targets themselves are now in the global variable 'targets'. */
1659 if (!Lst_IsEmpty(targets))
1660 ParseDoDependencyCheckSpec(specType);
1663 * Have now parsed all the target names. Must parse the operator next.
1665 if (!ParseDoDependencyParseOp(&cp, lstart, &op))
1669 * Apply the operator to the target. This is how we remember which
1670 * operator a target was defined with. It fails if the operator
1671 * used isn't consistent across all references.
1673 ApplyDependencyOperator(op);
1676 * Onward to the sources.
1678 * LINE will now point to the first source word, if any, or the
1679 * end of the string if not.
1681 pp_skip_whitespace(&cp);
1682 line = cp; /* XXX: 'line' is an inappropriate name */
1685 * Several special targets take different actions if present with no
1687 * a .SUFFIXES line with no sources clears out all old suffixes
1688 * a .PRECIOUS line makes all targets precious
1689 * a .IGNORE line ignores errors for all targets
1690 * a .SILENT line creates silence when making all targets
1691 * a .PATH removes all directories from the search path(s).
1693 if (line[0] == '\0') {
1694 ParseDoDependencySourcesEmpty(specType, paths);
1695 } else if (specType == SP_MFLAGS) {
1697 * Call on functions in main.c to deal with these arguments and
1698 * set the initial character to a null-character so the loop to
1699 * get sources won't get anything
1701 Main_ParseArgLine(line);
1703 } else if (specType == SP_SHELL) {
1704 if (!Job_ParseShell(line)) {
1705 Parse_Error(PARSE_FATAL, "improper shell specification");
1709 } else if (specType == SP_NOTPARALLEL || specType == SP_SINGLESHELL ||
1710 specType == SP_DELETE_ON_ERROR) {
1714 /* Now go for the sources. */
1715 if (specType == SP_SUFFIXES || specType == SP_PATH ||
1716 specType == SP_INCLUDES || specType == SP_LIBS ||
1717 specType == SP_NULL || specType == SP_OBJDIR)
1719 ParseDoDependencySourcesSpecial(line, cp, specType, paths);
1724 if (specType == SP_PATH)
1727 assert(paths == NULL);
1728 if (!ParseDoDependencySourcesMundane(line, cp, specType, tOp))
1737 if (curTargs != NULL)
1741 typedef struct VarAssignParsed {
1742 const char *nameStart; /* unexpanded */
1743 const char *nameEnd; /* before operator adjustment */
1744 const char *eq; /* the '=' of the assignment operator */
1747 /* Determine the assignment operator and adjust the end of the variable
1748 * name accordingly. */
1750 AdjustVarassignOp(const VarAssignParsed *pvar, const char *value,
1753 const char *op = pvar->eq;
1754 const char * const name = pvar->nameStart;
1757 if (op > name && op[-1] == '+') {
1761 } else if (op > name && op[-1] == '?') {
1765 } else if (op > name && op[-1] == ':') {
1769 } else if (op > name && op[-1] == '!') {
1776 while (op > name && ch_isspace(op[-1]))
1779 if (op >= name + 3 && op[-3] == ':' && op[-2] == 's' && op[-1] == 'h') {
1787 const char *nameEnd = pvar->nameEnd < op ? pvar->nameEnd : op;
1788 out_var->varname = bmake_strsedup(pvar->nameStart, nameEnd);
1790 out_var->value = value;
1794 /* Parse a variable assignment, consisting of a single-word variable name,
1795 * optional whitespace, an assignment operator, optional whitespace and the
1798 * Note: There is a lexical ambiguity with assignment modifier characters
1799 * in variable names. This routine interprets the character before the =
1800 * as a modifier. Therefore, an assignment like
1802 * is interpreted as "C+ +=" instead of "C++ =".
1804 * Used for both lines in a file and command line arguments. */
1806 Parse_IsVar(const char *p, VarAssign *out_var)
1808 VarAssignParsed pvar;
1809 const char *firstSpace = NULL;
1812 cpp_skip_hspace(&p); /* Skip to variable name */
1814 /* During parsing, the '+' of the '+=' operator is initially parsed
1815 * as part of the variable name. It is later corrected, as is the ':sh'
1816 * modifier. Of these two (nameEnd and op), the earlier one determines the
1817 * actual end of the variable name. */
1820 pvar.nameEnd = NULL;
1824 /* Scan for one of the assignment operators outside a variable expansion */
1825 while (*p != '\0') {
1827 if (ch == '(' || ch == '{') {
1831 if (ch == ')' || ch == '}') {
1839 if (ch == ' ' || ch == '\t')
1840 if (firstSpace == NULL)
1842 while (ch == ' ' || ch == '\t')
1846 if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1853 pvar.nameEnd = firstSpace != NULL ? firstSpace : p - 1;
1854 cpp_skip_whitespace(&p);
1855 AdjustVarassignOp(&pvar, p, out_var);
1858 if (*p == '=' && (ch == '+' || ch == ':' || ch == '?' || ch == '!')) {
1860 pvar.nameEnd = firstSpace != NULL ? firstSpace : p;
1862 cpp_skip_whitespace(&p);
1863 AdjustVarassignOp(&pvar, p, out_var);
1866 if (firstSpace != NULL)
1874 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *ctxt)
1877 if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1878 /* Check for syntax errors such as unclosed expressions or
1879 * unknown modifiers. */
1880 char *expandedValue;
1882 (void)Var_Subst(uvalue, ctxt, VARE_NONE, &expandedValue);
1883 /* TODO: handle errors */
1884 free(expandedValue);
1890 VarAssign_EvalSubst(const char *name, const char *uvalue, GNode *ctxt,
1891 const char **out_avalue, void **out_avalue_freeIt)
1893 const char *avalue = uvalue;
1895 Boolean savedPreserveUndefined = preserveUndefined;
1897 /* TODO: Can this assignment to preserveUndefined be moved further down
1898 * to the actually interesting Var_Subst call, without affecting any
1901 * It might affect the implicit expansion of the variable name in the
1902 * Var_Exists and Var_Set calls, even though it's unlikely that anyone
1903 * cared about this edge case when adding this code. In addition,
1904 * variable assignments should not refer to any undefined variables in
1905 * the variable name. */
1906 preserveUndefined = TRUE;
1909 * make sure that we set the variable the first time to nothing
1910 * so that it gets substituted!
1912 if (!Var_Exists(name, ctxt))
1913 Var_Set(name, "", ctxt);
1915 (void)Var_Subst(uvalue, ctxt, VARE_WANTRES|VARE_KEEP_DOLLAR, &evalue);
1916 /* TODO: handle errors */
1917 preserveUndefined = savedPreserveUndefined;
1919 Var_Set(name, avalue, ctxt);
1921 *out_avalue = avalue;
1922 *out_avalue_freeIt = evalue;
1926 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *ctxt,
1927 const char **out_avalue, void **out_avalue_freeIt)
1929 const char *cmd, *errfmt;
1931 void *cmd_freeIt = NULL;
1934 if (strchr(cmd, '$') != NULL) {
1936 (void)Var_Subst(cmd, VAR_CMDLINE, VARE_WANTRES | VARE_UNDEFERR, &ecmd);
1937 /* TODO: handle errors */
1938 cmd = cmd_freeIt = ecmd;
1941 cmdOut = Cmd_Exec(cmd, &errfmt);
1942 Var_Set(name, cmdOut, ctxt);
1943 *out_avalue = *out_avalue_freeIt = cmdOut;
1946 Parse_Error(PARSE_WARNING, errfmt, cmd);
1951 /* Perform a variable assignment.
1953 * The actual value of the variable is returned in *out_avalue and
1954 * *out_avalue_freeIt. Especially for VAR_SUBST and VAR_SHELL this can differ
1955 * from the literal value.
1957 * Return whether the assignment was actually done. The assignment is only
1958 * skipped if the operator is '?=' and the variable already exists. */
1960 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1961 GNode *ctxt, const char **out_avalue, void **out_avalue_freeIt)
1963 const char *avalue = uvalue;
1964 void *avalue_freeIt = NULL;
1966 if (op == VAR_APPEND)
1967 Var_Append(name, uvalue, ctxt);
1968 else if (op == VAR_SUBST)
1969 VarAssign_EvalSubst(name, uvalue, ctxt, &avalue, &avalue_freeIt);
1970 else if (op == VAR_SHELL)
1971 VarAssign_EvalShell(name, uvalue, ctxt, &avalue, &avalue_freeIt);
1973 if (op == VAR_DEFAULT && Var_Exists(name, ctxt)) {
1974 *out_avalue_freeIt = NULL;
1978 /* Normal assignment -- just do it. */
1979 Var_Set(name, uvalue, ctxt);
1982 *out_avalue = avalue;
1983 *out_avalue_freeIt = avalue_freeIt;
1988 VarAssignSpecial(const char *name, const char *avalue)
1990 if (strcmp(name, MAKEOVERRIDES) == 0)
1991 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1992 else if (strcmp(name, ".CURDIR") == 0) {
1994 * Someone is being (too?) clever...
1995 * Let's pretend they know what they are doing and
1996 * re-initialize the 'cur' CachedDir.
1998 Dir_InitCur(avalue);
2000 } else if (strcmp(name, MAKE_JOB_PREFIX) == 0)
2002 else if (strcmp(name, MAKE_EXPORTED) == 0)
2003 Var_Export(avalue, FALSE);
2006 /* Perform the variable variable assignment in the given context. */
2008 Parse_DoVar(VarAssign *var, GNode *ctxt)
2010 const char *avalue; /* actual value (maybe expanded) */
2011 void *avalue_freeIt;
2013 VarCheckSyntax(var->op, var->value, ctxt);
2014 if (VarAssign_Eval(var->varname, var->op, var->value, ctxt,
2015 &avalue, &avalue_freeIt))
2016 VarAssignSpecial(var->varname, avalue);
2018 free(avalue_freeIt);
2023 /* See if the command possibly calls a sub-make by using the variable
2024 * expressions ${.MAKE}, ${MAKE} or the plain word "make". */
2026 MaybeSubMake(const char *cmd)
2030 for (start = cmd; *start != '\0'; start++) {
2031 const char *p = start;
2034 /* XXX: What if progname != "make"? */
2035 if (p[0] == 'm' && p[1] == 'a' && p[2] == 'k' && p[3] == 'e')
2036 if (start == cmd || !ch_isalnum(p[-1]))
2037 if (!ch_isalnum(p[4]))
2052 if (*p == '.') /* Accept either ${.MAKE} or ${MAKE}. */
2055 if (p[0] == 'M' && p[1] == 'A' && p[2] == 'K' && p[3] == 'E')
2062 /* Append the command to the target node.
2064 * The node may be marked as a submake node if the command is determined to
2067 ParseAddCmd(GNode *gn, char *cmd)
2069 /* Add to last (ie current) cohort for :: targets */
2070 if ((gn->type & OP_DOUBLEDEP) && gn->cohorts->last != NULL)
2071 gn = gn->cohorts->last->datum;
2073 /* if target already supplied, ignore commands */
2074 if (!(gn->type & OP_HAS_COMMANDS)) {
2075 Lst_Append(gn->commands, cmd);
2076 if (MaybeSubMake(cmd))
2077 gn->type |= OP_SUBMAKE;
2081 /* XXX: We cannot do this until we fix the tree */
2082 Lst_Append(gn->commands, cmd);
2083 Parse_Error(PARSE_WARNING,
2084 "overriding commands for target \"%s\"; "
2085 "previous commands defined at %s: %d ignored",
2086 gn->name, gn->fname, gn->lineno);
2088 Parse_Error(PARSE_WARNING,
2089 "duplicate script for target \"%s\" ignored",
2091 ParseErrorInternal(gn->fname, (size_t)gn->lineno, PARSE_WARNING,
2092 "using previous script for \"%s\" defined here",
2098 /* Add a directory to the path searched for included makefiles bracketed
2099 * by double-quotes. */
2101 Parse_AddIncludeDir(const char *dir)
2103 (void)Dir_AddDir(parseIncPath, dir);
2106 /* Handle one of the .[-ds]include directives by remembering the current file
2107 * and pushing the included file on the stack. After the included file has
2108 * finished, parsing continues with the including file; see Parse_SetInput
2111 * System includes are looked up in sysIncPath, any other includes are looked
2112 * up in the parsedir and then in the directories specified by the -I command
2116 Parse_include_file(char *file, Boolean isSystem, Boolean depinc, Boolean silent)
2118 struct loadedfile *lf;
2119 char *fullname; /* full pathname of file */
2121 char *slash, *incdir;
2125 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2127 if (fullname == NULL && !isSystem) {
2129 * Include files contained in double-quotes are first searched
2130 * relative to the including file's location. We don't want to
2131 * cd there, of course, so we just tack on the old file's
2132 * leading path components and call Dir_FindFile to see if
2133 * we can locate the file.
2136 incdir = bmake_strdup(CurFile()->fname);
2137 slash = strrchr(incdir, '/');
2138 if (slash != NULL) {
2140 /* Now do lexical processing of leading "../" on the filename */
2141 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2142 slash = strrchr(incdir + 1, '/');
2143 if (slash == NULL || strcmp(slash, "/..") == 0)
2147 newName = str_concat3(incdir, "/", file + i);
2148 fullname = Dir_FindFile(newName, parseIncPath);
2149 if (fullname == NULL)
2150 fullname = Dir_FindFile(newName, dirSearchPath);
2155 if (fullname == NULL) {
2157 * Makefile wasn't found in same directory as included makefile.
2158 * Search for it first on the -I search path,
2159 * then on the .PATH search path, if not found in a -I directory.
2160 * If we have a suffix specific path we should use that.
2163 SearchPath *suffPath = NULL;
2165 if ((suff = strrchr(file, '.'))) {
2166 suffPath = Suff_GetPath(suff);
2167 if (suffPath != NULL)
2168 fullname = Dir_FindFile(file, suffPath);
2170 if (fullname == NULL) {
2171 fullname = Dir_FindFile(file, parseIncPath);
2172 if (fullname == NULL)
2173 fullname = Dir_FindFile(file, dirSearchPath);
2178 /* Looking for a system file or file still not found */
2179 if (fullname == NULL) {
2181 * Look for it on the system path
2183 SearchPath *path = Lst_IsEmpty(sysIncPath) ? defSysIncPath : sysIncPath;
2184 fullname = Dir_FindFile(file, path);
2187 if (fullname == NULL) {
2189 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2193 /* Actually open the file... */
2194 fd = open(fullname, O_RDONLY);
2197 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2203 lf = loadfile(fullname, fd);
2205 /* Start reading from this file next */
2206 Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2209 doing_depend = depinc; /* only turn it on */
2213 ParseDoInclude(char *line)
2215 char endc; /* the character which ends the file spec */
2216 char *cp; /* current position in file spec */
2217 Boolean silent = *line != 'i';
2218 char *file = line + (silent ? 8 : 7);
2220 /* Skip to delimiter character so we know where to look */
2221 pp_skip_hspace(&file);
2223 if (*file != '"' && *file != '<') {
2224 Parse_Error(PARSE_FATAL,
2225 ".include filename must be delimited by '\"' or '<'");
2230 * Set the search path on which to find the include file based on the
2231 * characters which bracket its name. Angle-brackets imply it's
2232 * a system Makefile while double-quotes imply it's a user makefile
2239 /* Skip to matching delimiter */
2240 for (cp = ++file; *cp && *cp != endc; cp++)
2244 Parse_Error(PARSE_FATAL,
2245 "Unclosed .include filename. '%c' expected", endc);
2252 * Substitute for any variables in the filename before trying to
2255 (void)Var_Subst(file, VAR_CMDLINE, VARE_WANTRES, &file);
2256 /* TODO: handle errors */
2258 Parse_include_file(file, endc == '>', *line == 'd', silent);
2262 /* Split filename into dirname + basename, then assign these to the
2263 * given variables. */
2265 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2267 const char *slash, *dirname, *basename;
2270 slash = strrchr(filename, '/');
2271 if (slash == NULL) {
2273 basename = filename;
2276 dirname = freeIt = bmake_strsedup(filename, slash);
2277 basename = slash + 1;
2280 Var_Set(dirvar, dirname, VAR_GLOBAL);
2281 Var_Set(filevar, basename, VAR_GLOBAL);
2283 DEBUG5(PARSE, "%s: ${%s} = `%s' ${%s} = `%s'\n",
2284 __func__, dirvar, dirname, filevar, basename);
2288 /* Return the immediately including file.
2290 * This is made complicated since the .for loop is implemented as a special
2291 * kind of .include; see For_Run. */
2293 GetActuallyIncludingFile(void)
2296 const IFile *incs = GetInclude(0);
2298 for (i = includes.len; i >= 2; i--)
2299 if (!incs[i - 1].fromForLoop)
2300 return incs[i - 2].fname;
2304 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2306 ParseSetParseFile(const char *filename)
2308 const char *including;
2310 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2312 including = GetActuallyIncludingFile();
2313 if (including != NULL) {
2314 SetFilenameVars(including,
2315 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2317 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2318 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2323 StrContainsWord(const char *str, const char *word)
2325 size_t strLen = strlen(str);
2326 size_t wordLen = strlen(word);
2327 const char *p, *end;
2329 if (strLen < wordLen)
2330 return FALSE; /* str is too short to contain word */
2332 end = str + strLen - wordLen;
2333 for (p = str; p != NULL; p = strchr(p, ' ')) {
2337 return FALSE; /* cannot contain word */
2339 if (memcmp(p, word, wordLen) == 0 &&
2340 (p[wordLen] == '\0' || p[wordLen] == ' '))
2346 /* XXX: Searching through a set of words with this linear search is
2347 * inefficient for variables that contain thousands of words. */
2348 /* XXX: The paths in this list don't seem to be normalized in any way. */
2350 VarContainsWord(const char *varname, const char *word)
2353 const char *val = Var_Value(varname, VAR_GLOBAL, &val_freeIt);
2354 Boolean found = val != NULL && StrContainsWord(val, word);
2355 bmake_free(val_freeIt);
2359 /* Track the makefiles we read - so makefiles can set dependencies on them.
2360 * Avoid adding anything more than once.
2362 * Time complexity: O(n) per call, in total O(n^2), where n is the number
2363 * of makefiles that have been loaded. */
2365 ParseTrackInput(const char *name)
2367 if (!VarContainsWord(MAKE_MAKEFILES, name))
2368 Var_Append(MAKE_MAKEFILES, name, VAR_GLOBAL);
2372 /* Start parsing from the given source.
2374 * The given file is added to the includes stack. */
2376 Parse_SetInput(const char *name, int line, int fd,
2377 char *(*nextbuf)(void *, size_t *), void *arg)
2382 Boolean fromForLoop = name == NULL;
2385 name = CurFile()->fname;
2387 ParseTrackInput(name);
2390 debug_printf("%s: file %s, line %d, fd %d, nextbuf %s, arg %p\n",
2391 __func__, name, line, fd,
2392 nextbuf == loadedfile_nextbuf ? "loadedfile" : "other",
2395 if (fd == -1 && nextbuf == NULL)
2399 curFile = Vector_Push(&includes);
2400 curFile->fname = bmake_strdup(name);
2401 curFile->fromForLoop = fromForLoop;
2402 curFile->lineno = line;
2403 curFile->first_lineno = line;
2404 curFile->nextbuf = nextbuf;
2405 curFile->nextbuf_arg = arg;
2407 curFile->depending = doing_depend; /* restore this on EOF */
2409 assert(nextbuf != NULL);
2411 /* Get first block of input data */
2412 buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2414 /* Was all a waste of time ... */
2416 free(curFile->fname);
2420 curFile->buf_freeIt = buf;
2421 curFile->buf_ptr = buf;
2422 curFile->buf_end = buf + len;
2424 curFile->cond_depth = Cond_save_depth();
2425 ParseSetParseFile(name);
2428 /* Check if the directive is an include directive. */
2430 IsInclude(const char *dir, Boolean sysv)
2432 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2435 if (strncmp(dir, "include", 7) != 0)
2438 /* Space is not mandatory for BSD .include */
2439 return !sysv || ch_isspace(dir[7]);
2444 /* Check if the line is a SYSV include directive. */
2446 IsSysVInclude(const char *line)
2450 if (!IsInclude(line, TRUE))
2453 /* Avoid interpreting a dependency line as an include */
2454 for (p = line; (p = strchr(p, ':')) != NULL;) {
2456 /* end of line -> it's a dependency */
2460 /* '::' operator or ': ' -> it's a dependency */
2461 if (*p == ':' || ch_isspace(*p))
2467 /* Push to another file. The line points to the word "include". */
2469 ParseTraditionalInclude(char *line)
2471 char *cp; /* current position in file spec */
2472 Boolean done = FALSE;
2473 Boolean silent = line[0] != 'i';
2474 char *file = line + (silent ? 8 : 7);
2477 DEBUG2(PARSE, "%s: %s\n", __func__, file);
2479 pp_skip_whitespace(&file);
2482 * Substitute for any variables in the file name before trying to
2485 (void)Var_Subst(file, VAR_CMDLINE, VARE_WANTRES, &all_files);
2486 /* TODO: handle errors */
2488 if (*file == '\0') {
2489 Parse_Error(PARSE_FATAL, "Filename missing from \"include\"");
2493 for (file = all_files; !done; file = cp + 1) {
2494 /* Skip to end of line or next whitespace */
2495 for (cp = file; *cp && !ch_isspace(*cp); cp++)
2503 Parse_include_file(file, FALSE, FALSE, silent);
2511 /* Parse "export <variable>=<value>", and actually export it. */
2513 ParseGmakeExport(char *line)
2515 char *variable = line + 6;
2518 DEBUG2(PARSE, "%s: %s\n", __func__, variable);
2520 pp_skip_whitespace(&variable);
2522 for (value = variable; *value && *value != '='; value++)
2525 if (*value != '=') {
2526 Parse_Error(PARSE_FATAL,
2527 "Variable/Value missing from \"export\"");
2530 *value++ = '\0'; /* terminate variable */
2533 * Expand the value before putting it in the environment.
2535 (void)Var_Subst(value, VAR_CMDLINE, VARE_WANTRES, &value);
2536 /* TODO: handle errors */
2538 setenv(variable, value, 1);
2543 /* Called when EOF is reached in the current file. If we were reading an
2544 * include file or a .for loop, the includes stack is popped and things set
2545 * up to go back to reading the previous file at the previous location.
2548 * TRUE to continue parsing, i.e. it had only reached the end of an
2549 * included file, FALSE if the main file has been parsed completely.
2556 IFile *curFile = CurFile();
2558 assert(curFile->nextbuf != NULL);
2560 doing_depend = curFile->depending; /* restore this */
2561 /* get next input buffer, if any */
2562 ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2563 curFile->buf_ptr = ptr;
2564 curFile->buf_freeIt = ptr;
2565 curFile->buf_end = ptr + len; /* XXX: undefined behavior if ptr == NULL */
2566 curFile->lineno = curFile->first_lineno;
2568 return TRUE; /* Iterate again */
2570 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2571 Cond_restore_depth(curFile->cond_depth);
2573 if (curFile->lf != NULL) {
2574 loadedfile_destroy(curFile->lf);
2578 /* Dispose of curFile info */
2579 /* Leak curFile->fname because all the gnodes have pointers to it */
2580 free(curFile->buf_freeIt);
2581 Vector_Pop(&includes);
2583 if (includes.len == 0) {
2584 /* We've run out of input */
2585 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2586 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2587 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2588 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2592 curFile = CurFile();
2593 DEBUG2(PARSE, "ParseEOF: returning to file %s, line %d\n",
2594 curFile->fname, curFile->lineno);
2596 ParseSetParseFile(curFile->fname);
2600 typedef enum GetLineMode {
2607 ParseGetLine(GetLineMode mode)
2609 IFile *cf = CurFile();
2618 /* Loop through blank lines and comment lines */
2627 /* XXX: can buf_end ever be null? */
2628 if (cf->buf_end != NULL && ptr == cf->buf_end) {
2634 if (ch == '\0' || (ch == '\\' && ptr[1] == '\0')) {
2635 /* XXX: can buf_end ever be null? */
2636 if (cf->buf_end == NULL)
2637 /* End of string (aka for loop) data */
2639 /* see if there is more we can parse */
2640 while (ptr++ < cf->buf_end) {
2641 if ((ch = *ptr) == '\n') {
2642 if (ptr > line && ptr[-1] == '\\')
2644 Parse_Error(PARSE_WARNING,
2645 "Zero byte read from file, "
2646 "skipping rest of line.");
2650 /* XXX: Can cf->nextbuf ever be NULL? */
2651 if (cf->nextbuf != NULL) {
2653 * End of this buffer; return EOF and outer logic
2654 * will get the next one. (eww)
2658 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2663 /* Don't treat next character as special, remember first one */
2664 if (escaped == NULL)
2672 if (ch == '#' && comment == NULL) {
2673 /* Remember first '#' for comment stripping */
2674 /* Unless previous char was '[', as in modifier :[#] */
2675 if (!(ptr > line && ptr[-1] == '['))
2681 if (!ch_isspace(ch))
2682 /* We are not interested in trailing whitespace */
2686 /* Save next 'to be processed' location */
2689 /* Check we have a non-comment, non-blank line */
2690 if (line_end == line || comment == line) {
2692 /* At end of file */
2694 /* Parse another line */
2698 /* We now have a line of data */
2701 if (mode == PARSE_RAW) {
2702 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2706 if (mode == PARSE_SKIP) {
2707 /* Completely ignore non-directives */
2710 /* We could do more of the .else/.elif/.endif checks here */
2715 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2716 if (comment != NULL && line[0] != '\t') {
2721 /* If we didn't see a '\\' then the in-situ data is fine */
2722 if (escaped == NULL)
2725 /* Remove escapes from '\n' and '#' */
2728 for (; ; *tp++ = ch) {
2738 /* Delete '\\' at end of buffer */
2743 if (ch == '#' && line[0] != '\t')
2744 /* Delete '\\' from before '#' on non-command lines */
2748 /* Leave '\\' in buffer for later */
2750 /* Make sure we don't delete an escaped ' ' from the line end */
2755 /* Escaped '\n' -- replace following whitespace with a single ' '. */
2756 pp_skip_hspace(&ptr);
2760 /* Delete any trailing spaces - eg from empty continuations */
2761 while (tp > escaped && ch_isspace(tp[-1]))
2768 /* Read an entire line from the input file. Called only by Parse_File.
2771 * A line without its newline and without any trailing whitespace.
2776 char *line; /* Result */
2777 int lineno; /* Saved line # */
2781 line = ParseGetLine(PARSE_NORMAL);
2789 * The line might be a conditional. Ask the conditional module
2790 * about it and act accordingly
2792 switch (Cond_EvalLine(line)) {
2794 /* Skip to next conditional that evaluates to COND_PARSE. */
2796 line = ParseGetLine(PARSE_SKIP);
2797 } while (line && Cond_EvalLine(line) != COND_PARSE);
2803 case COND_INVALID: /* Not a conditional line */
2804 /* Check for .for loops */
2805 rval = For_Eval(line);
2807 /* Not a .for line */
2810 /* Syntax error - error printed, ignore line */
2812 /* Start of a .for loop */
2813 lineno = CurFile()->lineno;
2814 /* Accumulate loop lines until matching .endfor */
2816 line = ParseGetLine(PARSE_RAW);
2818 Parse_Error(PARSE_FATAL,
2819 "Unexpected end of file in for loop.");
2822 } while (For_Accum(line));
2823 /* Stash each iteration as a new 'input file' */
2825 /* Read next line from for-loop buffer */
2833 FinishDependencyGroup(void)
2837 if (targets == NULL)
2840 for (ln = targets->first; ln != NULL; ln = ln->next) {
2841 GNode *gn = ln->datum;
2843 Suff_EndTransform(gn);
2845 /* Mark the target as already having commands if it does, to
2846 * keep from having shell commands on multiple dependency lines. */
2847 if (!Lst_IsEmpty(gn->commands))
2848 gn->type |= OP_HAS_COMMANDS;
2855 /* Add the command to each target from the current dependency spec. */
2857 ParseLine_ShellCommand(const char *p)
2859 cpp_skip_whitespace(&p);
2861 return; /* skip empty commands */
2863 if (targets == NULL) {
2864 Parse_Error(PARSE_FATAL, "Unassociated shell command \"%s\"", p);
2869 char *cmd = bmake_strdup(p);
2872 for (ln = targets->first; ln != NULL; ln = ln->next) {
2873 GNode *gn = ln->datum;
2874 ParseAddCmd(gn, cmd);
2877 Lst_Append(targCmds, cmd);
2883 ParseDirective(char *line)
2889 * Lines that begin with '.' can be pretty much anything:
2890 * - directives like '.include' or '.if',
2891 * - suffix rules like '.c.o:',
2892 * - dependencies for filenames that start with '.',
2893 * - variable assignments like '.tmp=value'.
2896 pp_skip_whitespace(&cp);
2897 if (IsInclude(cp, FALSE)) {
2901 if (strncmp(cp, "undef", 5) == 0) {
2902 const char *varname;
2904 pp_skip_whitespace(&cp);
2906 for (; !ch_isspace(*cp) && *cp != '\0'; cp++)
2909 Var_Delete(varname, VAR_GLOBAL);
2910 /* TODO: undefine all variables, not only the first */
2911 /* TODO: use Str_Words, like everywhere else */
2913 } else if (strncmp(cp, "export", 6) == 0) {
2915 pp_skip_whitespace(&cp);
2916 Var_Export(cp, TRUE);
2918 } else if (strncmp(cp, "unexport", 8) == 0) {
2921 } else if (strncmp(cp, "info", 4) == 0 ||
2922 strncmp(cp, "error", 5) == 0 ||
2923 strncmp(cp, "warning", 7) == 0) {
2924 if (ParseMessage(cp))
2932 ParseVarassign(const char *line)
2936 if (!Parse_IsVar(line, &var))
2939 FinishDependencyGroup();
2940 Parse_DoVar(&var, VAR_GLOBAL);
2945 FindSemicolon(char *p)
2949 for (; *p != '\0'; p++) {
2950 if (*p == '\\' && p[1] != '\0') {
2955 if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2957 else if (level > 0 && (*p == ')' || *p == '}'))
2959 else if (level == 0 && *p == ';')
2965 /* dependency -> target... op [source...]
2966 * op -> ':' | '::' | '!' */
2968 ParseDependency(char *line)
2970 VarEvalFlags eflags;
2971 char *expanded_line;
2972 const char *shellcmd = NULL;
2975 * For some reason - probably to make the parser impossible -
2976 * a ';' can be used to separate commands from dependencies.
2977 * Attempt to avoid ';' inside substitution patterns.
2980 char *semicolon = FindSemicolon(line);
2981 if (*semicolon != '\0') {
2982 /* Terminate the dependency list at the ';' */
2984 shellcmd = semicolon + 1;
2989 * We now know it's a dependency line so it needs to have all
2990 * variables expanded before being parsed.
2992 * XXX: Ideally the dependency line would first be split into
2993 * its left-hand side, dependency operator and right-hand side,
2994 * and then each side would be expanded on its own. This would
2995 * allow for the left-hand side to allow only defined variables
2996 * and to allow variables on the right-hand side to be undefined
2999 * Parsing the line first would also prevent that targets
3000 * generated from variable expressions are interpreted as the
3001 * dependency operator, such as in "target${:U\:} middle: source",
3002 * in which the middle is interpreted as a source, not a target.
3005 /* In lint mode, allow undefined variables to appear in
3008 * Ideally, only the right-hand side would allow undefined
3009 * variables since it is common to have optional dependencies.
3010 * Having undefined variables on the left-hand side is more
3011 * unusual though. Since both sides are expanded in a single
3012 * pass, there is not much choice what to do here.
3014 * In normal mode, it does not matter whether undefined
3015 * variables are allowed or not since as of 2020-09-14,
3016 * Var_Parse does not print any parse errors in such a case.
3017 * It simply returns the special empty string var_Error,
3018 * which cannot be detected in the result of Var_Subst. */
3019 eflags = opts.lint ? VARE_WANTRES : VARE_WANTRES | VARE_UNDEFERR;
3020 (void)Var_Subst(line, VAR_CMDLINE, eflags, &expanded_line);
3021 /* TODO: handle errors */
3023 /* Need a fresh list for the target nodes */
3024 if (targets != NULL)
3026 targets = Lst_New();
3028 ParseDoDependency(expanded_line);
3029 free(expanded_line);
3031 if (shellcmd != NULL)
3032 ParseLine_ShellCommand(shellcmd);
3036 ParseLine(char *line)
3038 if (ParseDirective(line))
3041 if (*line == '\t') {
3042 ParseLine_ShellCommand(line + 1);
3047 if (IsSysVInclude(line)) {
3049 * It's an S3/S5-style "include".
3051 ParseTraditionalInclude(line);
3057 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
3058 strchr(line, ':') == NULL) {
3060 * It's a Gmake "export".
3062 ParseGmakeExport(line);
3067 if (ParseVarassign(line))
3070 FinishDependencyGroup();
3072 ParseDependency(line);
3075 /* Parse a top-level makefile, incorporating its content into the global
3079 * name The name of the file being read
3080 * fd The open file to parse; will be closed at the end
3083 Parse_File(const char *name, int fd)
3085 char *line; /* the line we're working on */
3086 struct loadedfile *lf;
3088 lf = loadfile(name, fd);
3090 assert(targets == NULL);
3095 Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
3099 while ((line = ParseReadLine()) != NULL) {
3100 DEBUG2(PARSE, "ParseReadLine (%d): '%s'\n",
3101 CurFile()->lineno, line);
3105 * Reached EOF, but it may be just EOF of an include file...
3107 } while (ParseEOF());
3109 FinishDependencyGroup();
3112 (void)fflush(stdout);
3113 (void)fprintf(stderr,
3114 "%s: Fatal errors encountered -- cannot continue",
3116 PrintOnError(NULL, NULL);
3121 /* Initialize the parsing module. */
3126 parseIncPath = Lst_New();
3127 sysIncPath = Lst_New();
3128 defSysIncPath = Lst_New();
3129 Vector_Init(&includes, sizeof(IFile));
3131 targCmds = Lst_New();
3135 /* Clean up the parsing module. */
3140 Lst_Destroy(targCmds, free);
3141 assert(targets == NULL);
3142 Lst_Destroy(defSysIncPath, Dir_Destroy);
3143 Lst_Destroy(sysIncPath, Dir_Destroy);
3144 Lst_Destroy(parseIncPath, Dir_Destroy);
3145 assert(includes.len == 0);
3146 Vector_Done(&includes);
3152 * Return a list containing the single main target to create.
3153 * If no such target exists, we Punt with an obnoxious error message.
3156 Parse_MainName(void)
3158 GNodeList *mainList;
3160 mainList = Lst_New();
3162 if (mainNode == NULL)
3163 Punt("no target to make.");
3165 if (mainNode->type & OP_DOUBLEDEP) {
3166 Lst_Append(mainList, mainNode);
3167 Lst_AppendAll(mainList, mainNode->cohorts);
3169 Lst_Append(mainList, mainNode);
3171 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3177 Parse_GetFatals(void)