drop the minix_ prefixes for mmap and munmap
[minix3.git] / usr.bin / make / parse.c
blob593549b0b56558214f5e8e196805f473a186f297
1 /* $NetBSD: parse.c,v 1.185 2012/06/12 19:21:51 joerg Exp $ */
3 /*
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
8 * Adam de Boor.
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. 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
32 * SUCH DAMAGE.
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
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
68 * SUCH DAMAGE.
72 #ifdef __minix
73 #ifndef MAP_COPY
74 #define MAP_COPY MAP_PRIVATE
75 #endif
76 #endif
78 #ifndef MAKE_NATIVE
79 static char rcsid[] = "$NetBSD: parse.c,v 1.185 2012/06/12 19:21:51 joerg Exp $";
80 #else
81 #include <sys/cdefs.h>
82 #ifndef lint
83 #if 0
84 static char sccsid[] = "@(#)parse.c 8.3 (Berkeley) 3/19/94";
85 #else
86 __RCSID("$NetBSD: parse.c,v 1.185 2012/06/12 19:21:51 joerg Exp $");
87 #endif
88 #endif /* not lint */
89 #endif
91 /*-
92 * parse.c --
93 * Functions to parse a makefile.
95 * One function, Parse_Init, must be called before any functions
96 * in this module are used. After that, the function Parse_File is the
97 * main entry point and controls most of the other functions in this
98 * module.
100 * Most important structures are kept in Lsts. Directories for
101 * the .include "..." function are kept in the 'parseIncPath' Lst, while
102 * those for the .include <...> are kept in the 'sysIncPath' Lst. The
103 * targets currently being defined are kept in the 'targets' Lst.
105 * The variables 'fname' and 'lineno' are used to track the name
106 * of the current file and the line number in that file so that error
107 * messages can be more meaningful.
109 * Interface:
110 * Parse_Init Initialization function which must be
111 * called before anything else in this module
112 * is used.
114 * Parse_End Cleanup the module
116 * Parse_File Function used to parse a makefile. It must
117 * be given the name of the file, which should
118 * already have been opened, and a function
119 * to call to read a character from the file.
121 * Parse_IsVar Returns TRUE if the given line is a
122 * variable assignment. Used by MainParseArgs
123 * to determine if an argument is a target
124 * or a variable assignment. Used internally
125 * for pretty much the same thing...
127 * Parse_Error Function called when an error occurs in
128 * parsing. Used by the variable and
129 * conditional modules.
130 * Parse_MainName Returns a Lst of the main target to create.
133 #include <sys/types.h>
134 #include <sys/mman.h>
135 #include <sys/stat.h>
136 #include <assert.h>
137 #include <ctype.h>
138 #include <errno.h>
139 #include <fcntl.h>
140 #include <stdarg.h>
141 #include <stdio.h>
143 #ifndef MAP_COPY
144 #define MAP_COPY MAP_PRIVATE
145 #endif
147 #include "make.h"
148 #include "hash.h"
149 #include "dir.h"
150 #include "job.h"
151 #include "buf.h"
152 #include "pathnames.h"
154 ////////////////////////////////////////////////////////////
155 // types and constants
158 * Structure for a file being read ("included file")
160 typedef struct IFile {
161 const char *fname; /* name of file */
162 int lineno; /* current line number in file */
163 int first_lineno; /* line number of start of text */
164 int cond_depth; /* 'if' nesting when file opened */
165 char *P_str; /* point to base of string buffer */
166 char *P_ptr; /* point to next char of string buffer */
167 char *P_end; /* point to the end of string buffer */
168 char *(*nextbuf)(void *, size_t *); /* Function to get more data */
169 void *nextbuf_arg; /* Opaque arg for nextbuf() */
170 struct loadedfile *lf; /* loadedfile object, if any */
171 } IFile;
175 * These values are returned by ParseEOF to tell Parse_File whether to
176 * CONTINUE parsing, i.e. it had only reached the end of an include file,
177 * or if it's DONE.
179 #define CONTINUE 1
180 #define DONE 0
183 * Tokens for target attributes
185 typedef enum {
186 Begin, /* .BEGIN */
187 Default, /* .DEFAULT */
188 End, /* .END */
189 dotError, /* .ERROR */
190 Ignore, /* .IGNORE */
191 Includes, /* .INCLUDES */
192 Interrupt, /* .INTERRUPT */
193 Libs, /* .LIBS */
194 Meta, /* .META */
195 MFlags, /* .MFLAGS or .MAKEFLAGS */
196 Main, /* .MAIN and we don't have anything user-specified to
197 * make */
198 NoExport, /* .NOEXPORT */
199 NoMeta, /* .NOMETA */
200 NoMetaCmp, /* .NOMETA_CMP */
201 NoPath, /* .NOPATH */
202 Not, /* Not special */
203 NotParallel, /* .NOTPARALLEL */
204 Null, /* .NULL */
205 ExObjdir, /* .OBJDIR */
206 Order, /* .ORDER */
207 Parallel, /* .PARALLEL */
208 ExPath, /* .PATH */
209 Phony, /* .PHONY */
210 #ifdef POSIX
211 Posix, /* .POSIX */
212 #endif
213 Precious, /* .PRECIOUS */
214 ExShell, /* .SHELL */
215 Silent, /* .SILENT */
216 SingleShell, /* .SINGLESHELL */
217 Suffixes, /* .SUFFIXES */
218 Wait, /* .WAIT */
219 Attribute /* Generic attribute */
220 } ParseSpecial;
223 * Other tokens
225 #define LPAREN '('
226 #define RPAREN ')'
229 ////////////////////////////////////////////////////////////
230 // result data
233 * The main target to create. This is the first target on the first
234 * dependency line in the first makefile.
236 static GNode *mainNode;
238 ////////////////////////////////////////////////////////////
239 // eval state
241 /* targets we're working on */
242 static Lst targets;
244 #ifdef CLEANUP
245 /* command lines for targets */
246 static Lst targCmds;
247 #endif
250 * specType contains the SPECial TYPE of the current target. It is
251 * Not if the target is unspecial. If it *is* special, however, the children
252 * are linked as children of the parent but not vice versa. This variable is
253 * set in ParseDoDependency
255 static ParseSpecial specType;
258 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
259 * seen, then set to each successive source on the line.
261 static GNode *predecessor;
263 ////////////////////////////////////////////////////////////
264 // parser state
266 /* true if currently in a dependency line or its commands */
267 static Boolean inLine;
269 /* number of fatal errors */
270 static int fatals = 0;
273 * Variables for doing includes
276 /* current file being read */
277 static IFile *curFile;
279 /* stack of IFiles generated by .includes */
280 static Lst includes;
282 /* include paths (lists of directories) */
283 Lst parseIncPath; /* dirs for "..." includes */
284 Lst sysIncPath; /* dirs for <...> includes */
285 Lst defIncPath; /* default for sysIncPath */
287 ////////////////////////////////////////////////////////////
288 // parser tables
291 * The parseKeywords table is searched using binary search when deciding
292 * if a target or source is special. The 'spec' field is the ParseSpecial
293 * type of the keyword ("Not" if the keyword isn't special as a target) while
294 * the 'op' field is the operator to apply to the list of targets if the
295 * keyword is used as a source ("0" if the keyword isn't special as a source)
297 static const struct {
298 const char *name; /* Name of keyword */
299 ParseSpecial spec; /* Type when used as a target */
300 int op; /* Operator when used as a source */
301 } parseKeywords[] = {
302 { ".BEGIN", Begin, 0 },
303 { ".DEFAULT", Default, 0 },
304 { ".END", End, 0 },
305 { ".ERROR", dotError, 0 },
306 { ".EXEC", Attribute, OP_EXEC },
307 { ".IGNORE", Ignore, OP_IGNORE },
308 { ".INCLUDES", Includes, 0 },
309 { ".INTERRUPT", Interrupt, 0 },
310 { ".INVISIBLE", Attribute, OP_INVISIBLE },
311 { ".JOIN", Attribute, OP_JOIN },
312 { ".LIBS", Libs, 0 },
313 { ".MADE", Attribute, OP_MADE },
314 { ".MAIN", Main, 0 },
315 { ".MAKE", Attribute, OP_MAKE },
316 { ".MAKEFLAGS", MFlags, 0 },
317 { ".META", Meta, OP_META },
318 { ".MFLAGS", MFlags, 0 },
319 { ".NOMETA", NoMeta, OP_NOMETA },
320 { ".NOMETA_CMP", NoMetaCmp, OP_NOMETA_CMP },
321 { ".NOPATH", NoPath, OP_NOPATH },
322 { ".NOTMAIN", Attribute, OP_NOTMAIN },
323 { ".NOTPARALLEL", NotParallel, 0 },
324 { ".NO_PARALLEL", NotParallel, 0 },
325 { ".NULL", Null, 0 },
326 { ".OBJDIR", ExObjdir, 0 },
327 { ".OPTIONAL", Attribute, OP_OPTIONAL },
328 { ".ORDER", Order, 0 },
329 { ".PARALLEL", Parallel, 0 },
330 { ".PATH", ExPath, 0 },
331 { ".PHONY", Phony, OP_PHONY },
332 #ifdef POSIX
333 { ".POSIX", Posix, 0 },
334 #endif
335 { ".PRECIOUS", Precious, OP_PRECIOUS },
336 { ".RECURSIVE", Attribute, OP_MAKE },
337 { ".SHELL", ExShell, 0 },
338 { ".SILENT", Silent, OP_SILENT },
339 { ".SINGLESHELL", SingleShell, 0 },
340 { ".SUFFIXES", Suffixes, 0 },
341 { ".USE", Attribute, OP_USE },
342 { ".USEBEFORE", Attribute, OP_USEBEFORE },
343 { ".WAIT", Wait, 0 },
346 ////////////////////////////////////////////////////////////
347 // local functions
349 static int ParseIsEscaped(const char *, const char *);
350 static void ParseErrorInternal(const char *, size_t, int, const char *, ...)
351 MAKE_ATTR_PRINTFLIKE(4,5);
352 static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list)
353 MAKE_ATTR_PRINTFLIKE(5, 0);
354 static int ParseFindKeyword(const char *);
355 static int ParseLinkSrc(void *, void *);
356 static int ParseDoOp(void *, void *);
357 static void ParseDoSrc(int, const char *);
358 static int ParseFindMain(void *, void *);
359 static int ParseAddDir(void *, void *);
360 static int ParseClearPath(void *, void *);
361 static void ParseDoDependency(char *);
362 static int ParseAddCmd(void *, void *);
363 static void ParseHasCommands(void *);
364 static void ParseDoInclude(char *);
365 static void ParseSetParseFile(const char *);
366 #ifdef SYSVINCLUDE
367 static void ParseTraditionalInclude(char *);
368 #endif
369 #ifdef GMAKEEXPORT
370 static void ParseGmakeExport(char *);
371 #endif
372 static int ParseEOF(void);
373 static char *ParseReadLine(void);
374 static void ParseFinishLine(void);
375 static void ParseMark(GNode *);
377 ////////////////////////////////////////////////////////////
378 // file loader
380 struct loadedfile {
381 const char *path; /* name, for error reports */
382 char *buf; /* contents buffer */
383 size_t len; /* length of contents */
384 size_t maplen; /* length of mmap area, or 0 */
385 Boolean used; /* XXX: have we used the data yet */
389 * Constructor/destructor for loadedfile
391 static struct loadedfile *
392 loadedfile_create(const char *path)
394 struct loadedfile *lf;
396 lf = bmake_malloc(sizeof(*lf));
397 lf->path = (path == NULL ? "(stdin)" : path);
398 lf->buf = NULL;
399 lf->len = 0;
400 lf->maplen = 0;
401 lf->used = FALSE;
402 return lf;
405 static void
406 loadedfile_destroy(struct loadedfile *lf)
408 if (lf->buf != NULL) {
409 if (lf->maplen > 0) {
410 munmap(lf->buf, lf->maplen);
411 } else {
412 free(lf->buf);
415 free(lf);
419 * nextbuf() operation for loadedfile, as needed by the weird and twisted
420 * logic below. Once that's cleaned up, we can get rid of lf->used...
422 static char *
423 loadedfile_nextbuf(void *x, size_t *len)
425 struct loadedfile *lf = x;
427 if (lf->used) {
428 return NULL;
430 lf->used = TRUE;
431 *len = lf->len;
432 return lf->buf;
436 * Try to get the size of a file.
438 static ReturnStatus
439 load_getsize(int fd, size_t *ret)
441 struct stat st;
443 if (fstat(fd, &st) < 0) {
444 return FAILURE;
447 if (!S_ISREG(st.st_mode)) {
448 return FAILURE;
452 * st_size is an off_t, which is 64 bits signed; *ret is
453 * size_t, which might be 32 bits unsigned or 64 bits
454 * unsigned. Rather than being elaborate, just punt on
455 * files that are more than 2^31 bytes. We should never
456 * see a makefile that size in practice...
458 * While we're at it reject negative sizes too, just in case.
460 if (st.st_size < 0 || st.st_size > 0x7fffffff) {
461 return FAILURE;
464 *ret = (size_t) st.st_size;
465 return SUCCESS;
469 * Read in a file.
471 * Until the path search logic can be moved under here instead of
472 * being in the caller in another source file, we need to have the fd
473 * passed in already open. Bleh.
475 * If the path is NULL use stdin and (to insure against fd leaks)
476 * assert that the caller passed in -1.
478 static struct loadedfile *
479 loadfile(const char *path, int fd)
481 struct loadedfile *lf;
482 long pagesize;
483 ssize_t result;
484 size_t bufpos;
486 lf = loadedfile_create(path);
488 if (path == NULL) {
489 assert(fd == -1);
490 fd = STDIN_FILENO;
491 } else {
492 #if 0 /* notyet */
493 fd = open(path, O_RDONLY);
494 if (fd < 0) {
496 Error("%s: %s", path, strerror(errno));
497 exit(1);
499 #endif
502 if (load_getsize(fd, &lf->len) == SUCCESS) {
503 /* found a size, try mmap */
504 pagesize = sysconf(_SC_PAGESIZE);
505 if (pagesize <= 0) {
506 pagesize = 0x1000;
508 /* round size up to a page */
509 lf->maplen = pagesize * ((lf->len + pagesize - 1)/pagesize);
512 * XXX hack for dealing with empty files; remove when
513 * we're no longer limited by interfacing to the old
514 * logic elsewhere in this file.
516 if (lf->maplen == 0) {
517 lf->maplen = pagesize;
521 * FUTURE: remove PROT_WRITE when the parser no longer
522 * needs to scribble on the input.
525 lf->buf = mmap(NULL, lf->maplen, PROT_READ|PROT_WRITE,
526 MAP_FILE|MAP_COPY, fd, 0);
527 if (lf->buf != MAP_FAILED) {
528 /* succeeded */
529 if (lf->len == lf->maplen && lf->buf[lf->len - 1] != '\n') {
530 char *b = malloc(lf->len + 1);
531 b[lf->len] = '\n';
532 memcpy(b, lf->buf, lf->len++);
533 munmap(lf->buf, lf->maplen);
534 lf->maplen = 0;
535 lf->buf = b;
537 goto done;
541 /* cannot mmap; load the traditional way */
543 lf->maplen = 0;
544 lf->len = 1024;
545 lf->buf = bmake_malloc(lf->len);
547 bufpos = 0;
548 while (1) {
549 assert(bufpos <= lf->len);
550 if (bufpos == lf->len) {
551 lf->len *= 2;
552 lf->buf = bmake_realloc(lf->buf, lf->len);
554 result = read(fd, lf->buf + bufpos, lf->len - bufpos);
555 if (result < 0) {
556 Error("%s: read error: %s", path, strerror(errno));
557 exit(1);
559 if (result == 0) {
560 break;
562 bufpos += result;
564 assert(bufpos <= lf->len);
565 lf->len = bufpos;
567 /* truncate malloc region to actual length (maybe not useful) */
568 if (lf->len > 0) {
569 lf->buf = bmake_realloc(lf->buf, lf->len);
572 done:
573 if (path != NULL) {
574 close(fd);
576 return lf;
579 ////////////////////////////////////////////////////////////
580 // old code
583 *----------------------------------------------------------------------
584 * ParseIsEscaped --
585 * Check if the current character is escaped on the current line
587 * Results:
588 * 0 if the character is not backslash escaped, 1 otherwise
590 * Side Effects:
591 * None
592 *----------------------------------------------------------------------
594 static int
595 ParseIsEscaped(const char *line, const char *c)
597 int active = 0;
598 for (;;) {
599 if (line == c)
600 return active;
601 if (*--c != '\\')
602 return active;
603 active = !active;
608 *----------------------------------------------------------------------
609 * ParseFindKeyword --
610 * Look in the table of keywords for one matching the given string.
612 * Input:
613 * str String to find
615 * Results:
616 * The index of the keyword, or -1 if it isn't there.
618 * Side Effects:
619 * None
620 *----------------------------------------------------------------------
622 static int
623 ParseFindKeyword(const char *str)
625 int start, end, cur;
626 int diff;
628 start = 0;
629 end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
631 do {
632 cur = start + ((end - start) / 2);
633 diff = strcmp(str, parseKeywords[cur].name);
635 if (diff == 0) {
636 return (cur);
637 } else if (diff < 0) {
638 end = cur - 1;
639 } else {
640 start = cur + 1;
642 } while (start <= end);
643 return (-1);
647 * ParseVErrorInternal --
648 * Error message abort function for parsing. Prints out the context
649 * of the error (line number and file) as well as the message with
650 * two optional arguments.
652 * Results:
653 * None
655 * Side Effects:
656 * "fatals" is incremented if the level is PARSE_FATAL.
658 /* VARARGS */
659 static void
660 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
661 const char *fmt, va_list ap)
663 static Boolean fatal_warning_error_printed = FALSE;
665 (void)fprintf(f, "%s: ", progname);
667 if (cfname != NULL) {
668 (void)fprintf(f, "\"");
669 if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) {
670 char *cp;
671 const char *dir;
674 * Nothing is more annoying than not knowing
675 * which Makefile is the culprit.
677 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
678 if (dir == NULL || *dir == '\0' ||
679 (*dir == '.' && dir[1] == '\0'))
680 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
681 if (dir == NULL)
682 dir = ".";
684 (void)fprintf(f, "%s/%s", dir, cfname);
685 } else
686 (void)fprintf(f, "%s", cfname);
688 (void)fprintf(f, "\" line %d: ", (int)clineno);
690 if (type == PARSE_WARNING)
691 (void)fprintf(f, "warning: ");
692 (void)vfprintf(f, fmt, ap);
693 (void)fprintf(f, "\n");
694 (void)fflush(f);
695 if (type == PARSE_FATAL || parseWarnFatal)
696 fatals += 1;
697 if (parseWarnFatal && !fatal_warning_error_printed) {
698 Error("parsing warnings being treated as errors");
699 fatal_warning_error_printed = TRUE;
704 * ParseErrorInternal --
705 * Error function
707 * Results:
708 * None
710 * Side Effects:
711 * None
713 /* VARARGS */
714 static void
715 ParseErrorInternal(const char *cfname, size_t clineno, int type,
716 const char *fmt, ...)
718 va_list ap;
720 va_start(ap, fmt);
721 (void)fflush(stdout);
722 ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
723 va_end(ap);
725 if (debug_file != stderr && debug_file != stdout) {
726 va_start(ap, fmt);
727 ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
728 va_end(ap);
733 * Parse_Error --
734 * External interface to ParseErrorInternal; uses the default filename
735 * Line number.
737 * Results:
738 * None
740 * Side Effects:
741 * None
743 /* VARARGS */
744 void
745 Parse_Error(int type, const char *fmt, ...)
747 va_list ap;
748 const char *fname;
749 size_t lineno;
751 if (curFile == NULL) {
752 fname = NULL;
753 lineno = 0;
754 } else {
755 fname = curFile->fname;
756 lineno = curFile->lineno;
759 va_start(ap, fmt);
760 (void)fflush(stdout);
761 ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
762 va_end(ap);
764 if (debug_file != stderr && debug_file != stdout) {
765 va_start(ap, fmt);
766 ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap);
767 va_end(ap);
773 * ParseMessage
774 * Parse a .info .warning or .error directive
776 * The input is the line minus the ".". We substitute
777 * variables, print the message and exit(1) (for .error) or just print
778 * a warning if the directive is malformed.
780 static Boolean
781 ParseMessage(char *line)
783 int mtype;
785 switch(*line) {
786 case 'i':
787 mtype = 0;
788 break;
789 case 'w':
790 mtype = PARSE_WARNING;
791 break;
792 case 'e':
793 mtype = PARSE_FATAL;
794 break;
795 default:
796 Parse_Error(PARSE_WARNING, "invalid syntax: \".%s\"", line);
797 return FALSE;
800 while (isalpha((u_char)*line))
801 line++;
802 if (!isspace((u_char)*line))
803 return FALSE; /* not for us */
804 while (isspace((u_char)*line))
805 line++;
807 line = Var_Subst(NULL, line, VAR_CMD, 0);
808 Parse_Error(mtype, "%s", line);
809 free(line);
811 if (mtype == PARSE_FATAL) {
812 /* Terminate immediately. */
813 exit(1);
815 return TRUE;
819 *---------------------------------------------------------------------
820 * ParseLinkSrc --
821 * Link the parent node to its new child. Used in a Lst_ForEach by
822 * ParseDoDependency. If the specType isn't 'Not', the parent
823 * isn't linked as a parent of the child.
825 * Input:
826 * pgnp The parent node
827 * cgpn The child node
829 * Results:
830 * Always = 0
832 * Side Effects:
833 * New elements are added to the parents list of cgn and the
834 * children list of cgn. the unmade field of pgn is updated
835 * to reflect the additional child.
836 *---------------------------------------------------------------------
838 static int
839 ParseLinkSrc(void *pgnp, void *cgnp)
841 GNode *pgn = (GNode *)pgnp;
842 GNode *cgn = (GNode *)cgnp;
844 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
845 pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
846 (void)Lst_AtEnd(pgn->children, cgn);
847 if (specType == Not)
848 (void)Lst_AtEnd(cgn->parents, pgn);
849 pgn->unmade += 1;
850 if (DEBUG(PARSE)) {
851 fprintf(debug_file, "# ParseLinkSrc: added child %s - %s\n", pgn->name, cgn->name);
852 Targ_PrintNode(pgn, 0);
853 Targ_PrintNode(cgn, 0);
855 return (0);
859 *---------------------------------------------------------------------
860 * ParseDoOp --
861 * Apply the parsed operator to the given target node. Used in a
862 * Lst_ForEach call by ParseDoDependency once all targets have
863 * been found and their operator parsed. If the previous and new
864 * operators are incompatible, a major error is taken.
866 * Input:
867 * gnp The node to which the operator is to be applied
868 * opp The operator to apply
870 * Results:
871 * Always 0
873 * Side Effects:
874 * The type field of the node is altered to reflect any new bits in
875 * the op.
876 *---------------------------------------------------------------------
878 static int
879 ParseDoOp(void *gnp, void *opp)
881 GNode *gn = (GNode *)gnp;
882 int op = *(int *)opp;
884 * If the dependency mask of the operator and the node don't match and
885 * the node has actually had an operator applied to it before, and
886 * the operator actually has some dependency information in it, complain.
888 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
889 !OP_NOP(gn->type) && !OP_NOP(op))
891 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
892 return (1);
895 if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
897 * If the node was the object of a :: operator, we need to create a
898 * new instance of it for the children and commands on this dependency
899 * line. The new instance is placed on the 'cohorts' list of the
900 * initial one (note the initial one is not on its own cohorts list)
901 * and the new instance is linked to all parents of the initial
902 * instance.
904 GNode *cohort;
907 * Propagate copied bits to the initial node. They'll be propagated
908 * back to the rest of the cohorts later.
910 gn->type |= op & ~OP_OPMASK;
912 cohort = Targ_FindNode(gn->name, TARG_NOHASH);
914 * Make the cohort invisible as well to avoid duplicating it into
915 * other variables. True, parents of this target won't tend to do
916 * anything with their local variables, but better safe than
917 * sorry. (I think this is pointless now, since the relevant list
918 * traversals will no longer see this node anyway. -mycroft)
920 cohort->type = op | OP_INVISIBLE;
921 (void)Lst_AtEnd(gn->cohorts, cohort);
922 cohort->centurion = gn;
923 gn->unmade_cohorts += 1;
924 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
925 gn->unmade_cohorts);
926 } else {
928 * We don't want to nuke any previous flags (whatever they were) so we
929 * just OR the new operator into the old
931 gn->type |= op;
934 return (0);
938 *---------------------------------------------------------------------
939 * ParseDoSrc --
940 * Given the name of a source, figure out if it is an attribute
941 * and apply it to the targets if it is. Else decide if there is
942 * some attribute which should be applied *to* the source because
943 * of some special target and apply it if so. Otherwise, make the
944 * source be a child of the targets in the list 'targets'
946 * Input:
947 * tOp operator (if any) from special targets
948 * src name of the source to handle
950 * Results:
951 * None
953 * Side Effects:
954 * Operator bits may be added to the list of targets or to the source.
955 * The targets may have a new source added to their lists of children.
956 *---------------------------------------------------------------------
958 static void
959 ParseDoSrc(int tOp, const char *src)
961 GNode *gn = NULL;
962 static int wait_number = 0;
963 char wait_src[16];
965 if (*src == '.' && isupper ((unsigned char)src[1])) {
966 int keywd = ParseFindKeyword(src);
967 if (keywd != -1) {
968 int op = parseKeywords[keywd].op;
969 if (op != 0) {
970 Lst_ForEach(targets, ParseDoOp, &op);
971 return;
973 if (parseKeywords[keywd].spec == Wait) {
975 * We add a .WAIT node in the dependency list.
976 * After any dynamic dependencies (and filename globbing)
977 * have happened, it is given a dependency on the each
978 * previous child back to and previous .WAIT node.
979 * The next child won't be scheduled until the .WAIT node
980 * is built.
981 * We give each .WAIT node a unique name (mainly for diag).
983 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
984 gn = Targ_FindNode(wait_src, TARG_NOHASH);
985 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
986 Lst_ForEach(targets, ParseLinkSrc, gn);
987 return;
992 switch (specType) {
993 case Main:
995 * If we have noted the existence of a .MAIN, it means we need
996 * to add the sources of said target to the list of things
997 * to create. The string 'src' is likely to be free, so we
998 * must make a new copy of it. Note that this will only be
999 * invoked if the user didn't specify a target on the command
1000 * line. This is to allow #ifmake's to succeed, or something...
1002 (void)Lst_AtEnd(create, bmake_strdup(src));
1004 * Add the name to the .TARGETS variable as well, so the user can
1005 * employ that, if desired.
1007 Var_Append(".TARGETS", src, VAR_GLOBAL);
1008 return;
1010 case Order:
1012 * Create proper predecessor/successor links between the previous
1013 * source and the current one.
1015 gn = Targ_FindNode(src, TARG_CREATE);
1016 if (predecessor != NULL) {
1017 (void)Lst_AtEnd(predecessor->order_succ, gn);
1018 (void)Lst_AtEnd(gn->order_pred, predecessor);
1019 if (DEBUG(PARSE)) {
1020 fprintf(debug_file, "# ParseDoSrc: added Order dependency %s - %s\n",
1021 predecessor->name, gn->name);
1022 Targ_PrintNode(predecessor, 0);
1023 Targ_PrintNode(gn, 0);
1027 * The current source now becomes the predecessor for the next one.
1029 predecessor = gn;
1030 break;
1032 default:
1034 * If the source is not an attribute, we need to find/create
1035 * a node for it. After that we can apply any operator to it
1036 * from a special target or link it to its parents, as
1037 * appropriate.
1039 * In the case of a source that was the object of a :: operator,
1040 * the attribute is applied to all of its instances (as kept in
1041 * the 'cohorts' list of the node) or all the cohorts are linked
1042 * to all the targets.
1045 /* Find/create the 'src' node and attach to all targets */
1046 gn = Targ_FindNode(src, TARG_CREATE);
1047 if (tOp) {
1048 gn->type |= tOp;
1049 } else {
1050 Lst_ForEach(targets, ParseLinkSrc, gn);
1052 break;
1057 *-----------------------------------------------------------------------
1058 * ParseFindMain --
1059 * Find a real target in the list and set it to be the main one.
1060 * Called by ParseDoDependency when a main target hasn't been found
1061 * yet.
1063 * Input:
1064 * gnp Node to examine
1066 * Results:
1067 * 0 if main not found yet, 1 if it is.
1069 * Side Effects:
1070 * mainNode is changed and Targ_SetMain is called.
1072 *-----------------------------------------------------------------------
1074 static int
1075 ParseFindMain(void *gnp, void *dummy)
1077 GNode *gn = (GNode *)gnp;
1078 if ((gn->type & OP_NOTARGET) == 0) {
1079 mainNode = gn;
1080 Targ_SetMain(gn);
1081 return (dummy ? 1 : 1);
1082 } else {
1083 return (dummy ? 0 : 0);
1088 *-----------------------------------------------------------------------
1089 * ParseAddDir --
1090 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
1092 * Results:
1093 * === 0
1095 * Side Effects:
1096 * See Dir_AddDir.
1098 *-----------------------------------------------------------------------
1100 static int
1101 ParseAddDir(void *path, void *name)
1103 (void)Dir_AddDir((Lst) path, (char *)name);
1104 return(0);
1108 *-----------------------------------------------------------------------
1109 * ParseClearPath --
1110 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
1112 * Results:
1113 * === 0
1115 * Side Effects:
1116 * See Dir_ClearPath
1118 *-----------------------------------------------------------------------
1120 static int
1121 ParseClearPath(void *path, void *dummy)
1123 Dir_ClearPath((Lst) path);
1124 return(dummy ? 0 : 0);
1128 *---------------------------------------------------------------------
1129 * ParseDoDependency --
1130 * Parse the dependency line in line.
1132 * Input:
1133 * line the line to parse
1135 * Results:
1136 * None
1138 * Side Effects:
1139 * The nodes of the sources are linked as children to the nodes of the
1140 * targets. Some nodes may be created.
1142 * We parse a dependency line by first extracting words from the line and
1143 * finding nodes in the list of all targets with that name. This is done
1144 * until a character is encountered which is an operator character. Currently
1145 * these are only ! and :. At this point the operator is parsed and the
1146 * pointer into the line advanced until the first source is encountered.
1147 * The parsed operator is applied to each node in the 'targets' list,
1148 * which is where the nodes found for the targets are kept, by means of
1149 * the ParseDoOp function.
1150 * The sources are read in much the same way as the targets were except
1151 * that now they are expanded using the wildcarding scheme of the C-Shell
1152 * and all instances of the resulting words in the list of all targets
1153 * are found. Each of the resulting nodes is then linked to each of the
1154 * targets as one of its children.
1155 * Certain targets are handled specially. These are the ones detailed
1156 * by the specType variable.
1157 * The storing of transformation rules is also taken care of here.
1158 * A target is recognized as a transformation rule by calling
1159 * Suff_IsTransform. If it is a transformation rule, its node is gotten
1160 * from the suffix module via Suff_AddTransform rather than the standard
1161 * Targ_FindNode in the target module.
1162 *---------------------------------------------------------------------
1164 static void
1165 ParseDoDependency(char *line)
1167 char *cp; /* our current position */
1168 GNode *gn = NULL; /* a general purpose temporary node */
1169 int op; /* the operator on the line */
1170 char savec; /* a place to save a character */
1171 Lst paths; /* List of search paths to alter when parsing
1172 * a list of .PATH targets */
1173 int tOp; /* operator from special target */
1174 Lst sources; /* list of archive source names after
1175 * expansion */
1176 Lst curTargs; /* list of target names to be found and added
1177 * to the targets list */
1178 char *lstart = line;
1180 if (DEBUG(PARSE))
1181 fprintf(debug_file, "ParseDoDependency(%s)\n", line);
1182 tOp = 0;
1184 specType = Not;
1185 paths = NULL;
1187 curTargs = Lst_Init(FALSE);
1189 do {
1190 for (cp = line; *cp && (ParseIsEscaped(lstart, cp) ||
1191 !(isspace((unsigned char)*cp) ||
1192 *cp == '!' || *cp == ':' || *cp == LPAREN));
1193 cp++) {
1194 if (*cp == '$') {
1196 * Must be a dynamic source (would have been expanded
1197 * otherwise), so call the Var module to parse the puppy
1198 * so we can safely advance beyond it...There should be
1199 * no errors in this, as they would have been discovered
1200 * in the initial Var_Subst and we wouldn't be here.
1202 int length;
1203 void *freeIt;
1204 char *result;
1206 result = Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
1207 if (freeIt)
1208 free(freeIt);
1209 cp += length-1;
1213 if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
1215 * Archives must be handled specially to make sure the OP_ARCHV
1216 * flag is set in their 'type' field, for one thing, and because
1217 * things like "archive(file1.o file2.o file3.o)" are permissible.
1218 * Arch_ParseArchive will set 'line' to be the first non-blank
1219 * after the archive-spec. It creates/finds nodes for the members
1220 * and places them on the given list, returning SUCCESS if all
1221 * went well and FAILURE if there was an error in the
1222 * specification. On error, line should remain untouched.
1224 if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
1225 Parse_Error(PARSE_FATAL,
1226 "Error in archive specification: \"%s\"", line);
1227 goto out;
1228 } else {
1229 continue;
1232 savec = *cp;
1234 if (!*cp) {
1236 * Ending a dependency line without an operator is a Bozo
1237 * no-no. As a heuristic, this is also often triggered by
1238 * undetected conflicts from cvs/rcs merges.
1240 if ((strncmp(line, "<<<<<<", 6) == 0) ||
1241 (strncmp(line, "======", 6) == 0) ||
1242 (strncmp(line, ">>>>>>", 6) == 0))
1243 Parse_Error(PARSE_FATAL,
1244 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1245 else
1246 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1247 : "Need an operator");
1248 goto out;
1250 *cp = '\0';
1253 * Have a word in line. See if it's a special target and set
1254 * specType to match it.
1256 if (*line == '.' && isupper ((unsigned char)line[1])) {
1258 * See if the target is a special target that must have it
1259 * or its sources handled specially.
1261 int keywd = ParseFindKeyword(line);
1262 if (keywd != -1) {
1263 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1264 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1265 goto out;
1268 specType = parseKeywords[keywd].spec;
1269 tOp = parseKeywords[keywd].op;
1272 * Certain special targets have special semantics:
1273 * .PATH Have to set the dirSearchPath
1274 * variable too
1275 * .MAIN Its sources are only used if
1276 * nothing has been specified to
1277 * create.
1278 * .DEFAULT Need to create a node to hang
1279 * commands on, but we don't want
1280 * it in the graph, nor do we want
1281 * it to be the Main Target, so we
1282 * create it, set OP_NOTMAIN and
1283 * add it to the list, setting
1284 * DEFAULT to the new node for
1285 * later use. We claim the node is
1286 * A transformation rule to make
1287 * life easier later, when we'll
1288 * use Make_HandleUse to actually
1289 * apply the .DEFAULT commands.
1290 * .PHONY The list of targets
1291 * .NOPATH Don't search for file in the path
1292 * .BEGIN
1293 * .END
1294 * .ERROR
1295 * .INTERRUPT Are not to be considered the
1296 * main target.
1297 * .NOTPARALLEL Make only one target at a time.
1298 * .SINGLESHELL Create a shell for each command.
1299 * .ORDER Must set initial predecessor to NULL
1301 switch (specType) {
1302 case ExPath:
1303 if (paths == NULL) {
1304 paths = Lst_Init(FALSE);
1306 (void)Lst_AtEnd(paths, dirSearchPath);
1307 break;
1308 case Main:
1309 if (!Lst_IsEmpty(create)) {
1310 specType = Not;
1312 break;
1313 case Begin:
1314 case End:
1315 case dotError:
1316 case Interrupt:
1317 gn = Targ_FindNode(line, TARG_CREATE);
1318 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1319 (void)Lst_AtEnd(targets, gn);
1320 break;
1321 case Default:
1322 gn = Targ_NewGN(".DEFAULT");
1323 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1324 (void)Lst_AtEnd(targets, gn);
1325 DEFAULT = gn;
1326 break;
1327 case NotParallel:
1328 maxJobs = 1;
1329 break;
1330 case SingleShell:
1331 compatMake = TRUE;
1332 break;
1333 case Order:
1334 predecessor = NULL;
1335 break;
1336 default:
1337 break;
1339 } else if (strncmp(line, ".PATH", 5) == 0) {
1341 * .PATH<suffix> has to be handled specially.
1342 * Call on the suffix module to give us a path to
1343 * modify.
1345 Lst path;
1347 specType = ExPath;
1348 path = Suff_GetPath(&line[5]);
1349 if (path == NULL) {
1350 Parse_Error(PARSE_FATAL,
1351 "Suffix '%s' not defined (yet)",
1352 &line[5]);
1353 goto out;
1354 } else {
1355 if (paths == NULL) {
1356 paths = Lst_Init(FALSE);
1358 (void)Lst_AtEnd(paths, path);
1364 * Have word in line. Get or create its node and stick it at
1365 * the end of the targets list
1367 if ((specType == Not) && (*line != '\0')) {
1368 if (Dir_HasWildcards(line)) {
1370 * Targets are to be sought only in the current directory,
1371 * so create an empty path for the thing. Note we need to
1372 * use Dir_Destroy in the destruction of the path as the
1373 * Dir module could have added a directory to the path...
1375 Lst emptyPath = Lst_Init(FALSE);
1377 Dir_Expand(line, emptyPath, curTargs);
1379 Lst_Destroy(emptyPath, Dir_Destroy);
1380 } else {
1382 * No wildcards, but we want to avoid code duplication,
1383 * so create a list with the word on it.
1385 (void)Lst_AtEnd(curTargs, line);
1388 while(!Lst_IsEmpty(curTargs)) {
1389 char *targName = (char *)Lst_DeQueue(curTargs);
1391 if (!Suff_IsTransform (targName)) {
1392 gn = Targ_FindNode(targName, TARG_CREATE);
1393 } else {
1394 gn = Suff_AddTransform(targName);
1397 (void)Lst_AtEnd(targets, gn);
1399 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1400 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1403 *cp = savec;
1405 * If it is a special type and not .PATH, it's the only target we
1406 * allow on this line...
1408 if (specType != Not && specType != ExPath) {
1409 Boolean warning = FALSE;
1411 while (*cp && (ParseIsEscaped(lstart, cp) ||
1412 ((*cp != '!') && (*cp != ':')))) {
1413 if (ParseIsEscaped(lstart, cp) ||
1414 (*cp != ' ' && *cp != '\t')) {
1415 warning = TRUE;
1417 cp++;
1419 if (warning) {
1420 Parse_Error(PARSE_WARNING, "Extra target ignored");
1422 } else {
1423 while (*cp && isspace ((unsigned char)*cp)) {
1424 cp++;
1427 line = cp;
1428 } while (*line && (ParseIsEscaped(lstart, line) ||
1429 ((*line != '!') && (*line != ':'))));
1432 * Don't need the list of target names anymore...
1434 Lst_Destroy(curTargs, NULL);
1435 curTargs = NULL;
1437 if (!Lst_IsEmpty(targets)) {
1438 switch(specType) {
1439 default:
1440 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1441 break;
1442 case Default:
1443 case Begin:
1444 case End:
1445 case dotError:
1446 case Interrupt:
1448 * These four create nodes on which to hang commands, so
1449 * targets shouldn't be empty...
1451 case Not:
1453 * Nothing special here -- targets can be empty if it wants.
1455 break;
1460 * Have now parsed all the target names. Must parse the operator next. The
1461 * result is left in op .
1463 if (*cp == '!') {
1464 op = OP_FORCE;
1465 } else if (*cp == ':') {
1466 if (cp[1] == ':') {
1467 op = OP_DOUBLEDEP;
1468 cp++;
1469 } else {
1470 op = OP_DEPENDS;
1472 } else {
1473 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1474 : "Missing dependency operator");
1475 goto out;
1478 cp++; /* Advance beyond operator */
1480 Lst_ForEach(targets, ParseDoOp, &op);
1483 * Get to the first source
1485 while (*cp && isspace ((unsigned char)*cp)) {
1486 cp++;
1488 line = cp;
1491 * Several special targets take different actions if present with no
1492 * sources:
1493 * a .SUFFIXES line with no sources clears out all old suffixes
1494 * a .PRECIOUS line makes all targets precious
1495 * a .IGNORE line ignores errors for all targets
1496 * a .SILENT line creates silence when making all targets
1497 * a .PATH removes all directories from the search path(s).
1499 if (!*line) {
1500 switch (specType) {
1501 case Suffixes:
1502 Suff_ClearSuffixes();
1503 break;
1504 case Precious:
1505 allPrecious = TRUE;
1506 break;
1507 case Ignore:
1508 ignoreErrors = TRUE;
1509 break;
1510 case Silent:
1511 beSilent = TRUE;
1512 break;
1513 case ExPath:
1514 Lst_ForEach(paths, ParseClearPath, NULL);
1515 Dir_SetPATH();
1516 break;
1517 #ifdef POSIX
1518 case Posix:
1519 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1520 break;
1521 #endif
1522 default:
1523 break;
1525 } else if (specType == MFlags) {
1527 * Call on functions in main.c to deal with these arguments and
1528 * set the initial character to a null-character so the loop to
1529 * get sources won't get anything
1531 Main_ParseArgLine(line);
1532 *line = '\0';
1533 } else if (specType == ExShell) {
1534 if (Job_ParseShell(line) != SUCCESS) {
1535 Parse_Error(PARSE_FATAL, "improper shell specification");
1536 goto out;
1538 *line = '\0';
1539 } else if ((specType == NotParallel) || (specType == SingleShell)) {
1540 *line = '\0';
1544 * NOW GO FOR THE SOURCES
1546 if ((specType == Suffixes) || (specType == ExPath) ||
1547 (specType == Includes) || (specType == Libs) ||
1548 (specType == Null) || (specType == ExObjdir))
1550 while (*line) {
1552 * If the target was one that doesn't take files as its sources
1553 * but takes something like suffixes, we take each
1554 * space-separated word on the line as a something and deal
1555 * with it accordingly.
1557 * If the target was .SUFFIXES, we take each source as a
1558 * suffix and add it to the list of suffixes maintained by the
1559 * Suff module.
1561 * If the target was a .PATH, we add the source as a directory
1562 * to search on the search path.
1564 * If it was .INCLUDES, the source is taken to be the suffix of
1565 * files which will be #included and whose search path should
1566 * be present in the .INCLUDES variable.
1568 * If it was .LIBS, the source is taken to be the suffix of
1569 * files which are considered libraries and whose search path
1570 * should be present in the .LIBS variable.
1572 * If it was .NULL, the source is the suffix to use when a file
1573 * has no valid suffix.
1575 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1576 * and will cause make to do a new chdir to that path.
1578 while (*cp && !isspace ((unsigned char)*cp)) {
1579 cp++;
1581 savec = *cp;
1582 *cp = '\0';
1583 switch (specType) {
1584 case Suffixes:
1585 Suff_AddSuffix(line, &mainNode);
1586 break;
1587 case ExPath:
1588 Lst_ForEach(paths, ParseAddDir, line);
1589 break;
1590 case Includes:
1591 Suff_AddInclude(line);
1592 break;
1593 case Libs:
1594 Suff_AddLib(line);
1595 break;
1596 case Null:
1597 Suff_SetNull(line);
1598 break;
1599 case ExObjdir:
1600 Main_SetObjdir(line);
1601 break;
1602 default:
1603 break;
1605 *cp = savec;
1606 if (savec != '\0') {
1607 cp++;
1609 while (*cp && isspace ((unsigned char)*cp)) {
1610 cp++;
1612 line = cp;
1614 if (paths) {
1615 Lst_Destroy(paths, NULL);
1617 if (specType == ExPath)
1618 Dir_SetPATH();
1619 } else {
1620 while (*line) {
1622 * The targets take real sources, so we must beware of archive
1623 * specifications (i.e. things with left parentheses in them)
1624 * and handle them accordingly.
1626 for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1627 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1629 * Only stop for a left parenthesis if it isn't at the
1630 * start of a word (that'll be for variable changes
1631 * later) and isn't preceded by a dollar sign (a dynamic
1632 * source).
1634 break;
1638 if (*cp == LPAREN) {
1639 sources = Lst_Init(FALSE);
1640 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1641 Parse_Error(PARSE_FATAL,
1642 "Error in source archive spec \"%s\"", line);
1643 goto out;
1646 while (!Lst_IsEmpty (sources)) {
1647 gn = (GNode *)Lst_DeQueue(sources);
1648 ParseDoSrc(tOp, gn->name);
1650 Lst_Destroy(sources, NULL);
1651 cp = line;
1652 } else {
1653 if (*cp) {
1654 *cp = '\0';
1655 cp += 1;
1658 ParseDoSrc(tOp, line);
1660 while (*cp && isspace ((unsigned char)*cp)) {
1661 cp++;
1663 line = cp;
1667 if (mainNode == NULL) {
1669 * If we have yet to decide on a main target to make, in the
1670 * absence of any user input, we want the first target on
1671 * the first dependency line that is actually a real target
1672 * (i.e. isn't a .USE or .EXEC rule) to be made.
1674 Lst_ForEach(targets, ParseFindMain, NULL);
1677 out:
1678 if (curTargs)
1679 Lst_Destroy(curTargs, NULL);
1683 *---------------------------------------------------------------------
1684 * Parse_IsVar --
1685 * Return TRUE if the passed line is a variable assignment. A variable
1686 * assignment consists of a single word followed by optional whitespace
1687 * followed by either a += or an = operator.
1688 * This function is used both by the Parse_File function and main when
1689 * parsing the command-line arguments.
1691 * Input:
1692 * line the line to check
1694 * Results:
1695 * TRUE if it is. FALSE if it ain't
1697 * Side Effects:
1698 * none
1699 *---------------------------------------------------------------------
1701 Boolean
1702 Parse_IsVar(char *line)
1704 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1705 char ch;
1706 int level = 0;
1707 #define ISEQOPERATOR(c) \
1708 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1711 * Skip to variable name
1713 for (;(*line == ' ') || (*line == '\t'); line++)
1714 continue;
1716 /* Scan for one of the assignment operators outside a variable expansion */
1717 while ((ch = *line++) != 0) {
1718 if (ch == '(' || ch == '{') {
1719 level++;
1720 continue;
1722 if (ch == ')' || ch == '}') {
1723 level--;
1724 continue;
1726 if (level != 0)
1727 continue;
1728 while (ch == ' ' || ch == '\t') {
1729 ch = *line++;
1730 wasSpace = TRUE;
1732 if (ch == '=')
1733 return TRUE;
1734 if (*line == '=' && ISEQOPERATOR(ch))
1735 return TRUE;
1736 if (wasSpace)
1737 return FALSE;
1740 return FALSE;
1744 *---------------------------------------------------------------------
1745 * Parse_DoVar --
1746 * Take the variable assignment in the passed line and do it in the
1747 * global context.
1749 * Note: There is a lexical ambiguity with assignment modifier characters
1750 * in variable names. This routine interprets the character before the =
1751 * as a modifier. Therefore, an assignment like
1752 * C++=/usr/bin/CC
1753 * is interpreted as "C+ +=" instead of "C++ =".
1755 * Input:
1756 * line a line guaranteed to be a variable assignment.
1757 * This reduces error checks
1758 * ctxt Context in which to do the assignment
1760 * Results:
1761 * none
1763 * Side Effects:
1764 * the variable structure of the given variable name is altered in the
1765 * global context.
1766 *---------------------------------------------------------------------
1768 void
1769 Parse_DoVar(char *line, GNode *ctxt)
1771 char *cp; /* pointer into line */
1772 enum {
1773 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1774 } type; /* Type of assignment */
1775 char *opc; /* ptr to operator character to
1776 * null-terminate the variable name */
1777 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1778 * i.e. if any variable expansion was
1779 * performed */
1780 int depth;
1783 * Skip to variable name
1785 while ((*line == ' ') || (*line == '\t')) {
1786 line++;
1790 * Skip to operator character, nulling out whitespace as we go
1791 * XXX Rather than counting () and {} we should look for $ and
1792 * then expand the variable.
1794 for (depth = 0, cp = line + 1; depth != 0 || *cp != '='; cp++) {
1795 if (*cp == '(' || *cp == '{') {
1796 depth++;
1797 continue;
1799 if (*cp == ')' || *cp == '}') {
1800 depth--;
1801 continue;
1803 if (depth == 0 && isspace ((unsigned char)*cp)) {
1804 *cp = '\0';
1807 opc = cp-1; /* operator is the previous character */
1808 *cp++ = '\0'; /* nuke the = */
1811 * Check operator type
1813 switch (*opc) {
1814 case '+':
1815 type = VAR_APPEND;
1816 *opc = '\0';
1817 break;
1819 case '?':
1821 * If the variable already has a value, we don't do anything.
1823 *opc = '\0';
1824 if (Var_Exists(line, ctxt)) {
1825 return;
1826 } else {
1827 type = VAR_NORMAL;
1829 break;
1831 case ':':
1832 type = VAR_SUBST;
1833 *opc = '\0';
1834 break;
1836 case '!':
1837 type = VAR_SHELL;
1838 *opc = '\0';
1839 break;
1841 default:
1842 #ifdef SUNSHCMD
1843 while (opc > line && *opc != ':')
1844 opc--;
1846 if (strncmp(opc, ":sh", 3) == 0) {
1847 type = VAR_SHELL;
1848 *opc = '\0';
1849 break;
1851 #endif
1852 type = VAR_NORMAL;
1853 break;
1856 while (isspace ((unsigned char)*cp)) {
1857 cp++;
1860 if (type == VAR_APPEND) {
1861 Var_Append(line, cp, ctxt);
1862 } else if (type == VAR_SUBST) {
1864 * Allow variables in the old value to be undefined, but leave their
1865 * invocation alone -- this is done by forcing oldVars to be false.
1866 * XXX: This can cause recursive variables, but that's not hard to do,
1867 * and this allows someone to do something like
1869 * CFLAGS = $(.INCLUDES)
1870 * CFLAGS := -I.. $(CFLAGS)
1872 * And not get an error.
1874 Boolean oldOldVars = oldVars;
1876 oldVars = FALSE;
1879 * make sure that we set the variable the first time to nothing
1880 * so that it gets substituted!
1882 if (!Var_Exists(line, ctxt))
1883 Var_Set(line, "", ctxt, 0);
1885 cp = Var_Subst(NULL, cp, ctxt, FALSE);
1886 oldVars = oldOldVars;
1887 freeCp = TRUE;
1889 Var_Set(line, cp, ctxt, 0);
1890 } else if (type == VAR_SHELL) {
1891 char *res;
1892 const char *error;
1894 if (strchr(cp, '$') != NULL) {
1896 * There's a dollar sign in the command, so perform variable
1897 * expansion on the whole thing. The resulting string will need
1898 * freeing when we're done, so set freeCmd to TRUE.
1900 cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1901 freeCp = TRUE;
1904 res = Cmd_Exec(cp, &error);
1905 Var_Set(line, res, ctxt, 0);
1906 free(res);
1908 if (error)
1909 Parse_Error(PARSE_WARNING, error, cp);
1910 } else {
1912 * Normal assignment -- just do it.
1914 Var_Set(line, cp, ctxt, 0);
1916 if (strcmp(line, MAKEOVERRIDES) == 0)
1917 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1918 else if (strcmp(line, ".CURDIR") == 0) {
1920 * Somone is being (too?) clever...
1921 * Let's pretend they know what they are doing and
1922 * re-initialize the 'cur' Path.
1924 Dir_InitCur(cp);
1925 Dir_SetPATH();
1926 } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1927 Job_SetPrefix();
1928 } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1929 Var_Export(cp, 0);
1931 if (freeCp)
1932 free(cp);
1937 * ParseAddCmd --
1938 * Lst_ForEach function to add a command line to all targets
1940 * Input:
1941 * gnp the node to which the command is to be added
1942 * cmd the command to add
1944 * Results:
1945 * Always 0
1947 * Side Effects:
1948 * A new element is added to the commands list of the node.
1950 static int
1951 ParseAddCmd(void *gnp, void *cmd)
1953 GNode *gn = (GNode *)gnp;
1955 /* Add to last (ie current) cohort for :: targets */
1956 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1957 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1959 /* if target already supplied, ignore commands */
1960 if (!(gn->type & OP_HAS_COMMANDS)) {
1961 (void)Lst_AtEnd(gn->commands, cmd);
1962 ParseMark(gn);
1963 } else {
1964 #ifdef notyet
1965 /* XXX: We cannot do this until we fix the tree */
1966 (void)Lst_AtEnd(gn->commands, cmd);
1967 Parse_Error(PARSE_WARNING,
1968 "overriding commands for target \"%s\"; "
1969 "previous commands defined at %s: %d ignored",
1970 gn->name, gn->fname, gn->lineno);
1971 #else
1972 Parse_Error(PARSE_WARNING,
1973 "duplicate script for target \"%s\" ignored",
1974 gn->name);
1975 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1976 "using previous script for \"%s\" defined here",
1977 gn->name);
1978 #endif
1980 return(0);
1984 *-----------------------------------------------------------------------
1985 * ParseHasCommands --
1986 * Callback procedure for Parse_File when destroying the list of
1987 * targets on the last dependency line. Marks a target as already
1988 * having commands if it does, to keep from having shell commands
1989 * on multiple dependency lines.
1991 * Input:
1992 * gnp Node to examine
1994 * Results:
1995 * None
1997 * Side Effects:
1998 * OP_HAS_COMMANDS may be set for the target.
2000 *-----------------------------------------------------------------------
2002 static void
2003 ParseHasCommands(void *gnp)
2005 GNode *gn = (GNode *)gnp;
2006 if (!Lst_IsEmpty(gn->commands)) {
2007 gn->type |= OP_HAS_COMMANDS;
2012 *-----------------------------------------------------------------------
2013 * Parse_AddIncludeDir --
2014 * Add a directory to the path searched for included makefiles
2015 * bracketed by double-quotes. Used by functions in main.c
2017 * Input:
2018 * dir The name of the directory to add
2020 * Results:
2021 * None.
2023 * Side Effects:
2024 * The directory is appended to the list.
2026 *-----------------------------------------------------------------------
2028 void
2029 Parse_AddIncludeDir(char *dir)
2031 (void)Dir_AddDir(parseIncPath, dir);
2035 *---------------------------------------------------------------------
2036 * ParseDoInclude --
2037 * Push to another file.
2039 * The input is the line minus the `.'. A file spec is a string
2040 * enclosed in <> or "". The former is looked for only in sysIncPath.
2041 * The latter in . and the directories specified by -I command line
2042 * options
2044 * Results:
2045 * None
2047 * Side Effects:
2048 * A structure is added to the includes Lst and readProc, lineno,
2049 * fname and curFILE are altered for the new file
2050 *---------------------------------------------------------------------
2053 static void
2054 Parse_include_file(char *file, Boolean isSystem, int silent)
2056 struct loadedfile *lf;
2057 char *fullname; /* full pathname of file */
2058 char *newName;
2059 char *prefEnd, *incdir;
2060 int fd;
2061 int i;
2064 * Now we know the file's name and its search path, we attempt to
2065 * find the durn thing. A return of NULL indicates the file don't
2066 * exist.
2068 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2070 if (fullname == NULL && !isSystem) {
2072 * Include files contained in double-quotes are first searched for
2073 * relative to the including file's location. We don't want to
2074 * cd there, of course, so we just tack on the old file's
2075 * leading path components and call Dir_FindFile to see if
2076 * we can locate the beast.
2079 incdir = bmake_strdup(curFile->fname);
2080 prefEnd = strrchr(incdir, '/');
2081 if (prefEnd != NULL) {
2082 *prefEnd = '\0';
2083 /* Now do lexical processing of leading "../" on the filename */
2084 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2085 prefEnd = strrchr(incdir + 1, '/');
2086 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
2087 break;
2088 *prefEnd = '\0';
2090 newName = str_concat(incdir, file + i, STR_ADDSLASH);
2091 fullname = Dir_FindFile(newName, parseIncPath);
2092 if (fullname == NULL)
2093 fullname = Dir_FindFile(newName, dirSearchPath);
2094 free(newName);
2096 free(incdir);
2098 if (fullname == NULL) {
2100 * Makefile wasn't found in same directory as included makefile.
2101 * Search for it first on the -I search path,
2102 * then on the .PATH search path, if not found in a -I directory.
2103 * If we have a suffix specific path we should use that.
2105 char *suff;
2106 Lst suffPath = NULL;
2108 if ((suff = strrchr(file, '.'))) {
2109 suffPath = Suff_GetPath(suff);
2110 if (suffPath != NULL) {
2111 fullname = Dir_FindFile(file, suffPath);
2114 if (fullname == NULL) {
2115 fullname = Dir_FindFile(file, parseIncPath);
2116 if (fullname == NULL) {
2117 fullname = Dir_FindFile(file, dirSearchPath);
2123 /* Looking for a system file or file still not found */
2124 if (fullname == NULL) {
2126 * Look for it on the system path
2128 fullname = Dir_FindFile(file,
2129 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2132 if (fullname == NULL) {
2133 if (!silent)
2134 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2135 return;
2138 /* Actually open the file... */
2139 fd = open(fullname, O_RDONLY);
2140 if (fd == -1) {
2141 if (!silent)
2142 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2143 free(fullname);
2144 return;
2147 /* load it */
2148 lf = loadfile(fullname, fd);
2150 /* Start reading from this file next */
2151 Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2152 curFile->lf = lf;
2155 static void
2156 ParseDoInclude(char *line)
2158 char endc; /* the character which ends the file spec */
2159 char *cp; /* current position in file spec */
2160 int silent = (*line != 'i') ? 1 : 0;
2161 char *file = &line[7 + silent];
2163 /* Skip to delimiter character so we know where to look */
2164 while (*file == ' ' || *file == '\t')
2165 file++;
2167 if (*file != '"' && *file != '<') {
2168 Parse_Error(PARSE_FATAL,
2169 ".include filename must be delimited by '\"' or '<'");
2170 return;
2174 * Set the search path on which to find the include file based on the
2175 * characters which bracket its name. Angle-brackets imply it's
2176 * a system Makefile while double-quotes imply it's a user makefile
2178 if (*file == '<') {
2179 endc = '>';
2180 } else {
2181 endc = '"';
2184 /* Skip to matching delimiter */
2185 for (cp = ++file; *cp && *cp != endc; cp++)
2186 continue;
2188 if (*cp != endc) {
2189 Parse_Error(PARSE_FATAL,
2190 "Unclosed %cinclude filename. '%c' expected",
2191 '.', endc);
2192 return;
2194 *cp = '\0';
2197 * Substitute for any variables in the file name before trying to
2198 * find the thing.
2200 file = Var_Subst(NULL, file, VAR_CMD, FALSE);
2202 Parse_include_file(file, endc == '>', silent);
2203 free(file);
2208 *---------------------------------------------------------------------
2209 * ParseSetParseFile --
2210 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2211 * basename of the given filename
2213 * Results:
2214 * None
2216 * Side Effects:
2217 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
2218 * dirname and basename of the given filename.
2219 *---------------------------------------------------------------------
2221 static void
2222 ParseSetParseFile(const char *filename)
2224 char *slash, *dirname;
2225 const char *pd, *pf;
2226 int len;
2228 slash = strrchr(filename, '/');
2229 if (slash == NULL) {
2230 Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL, 0);
2231 Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL, 0);
2232 dirname= NULL;
2233 } else {
2234 len = slash - filename;
2235 dirname = bmake_malloc(len + 1);
2236 memcpy(dirname, filename, len);
2237 dirname[len] = '\0';
2238 Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL, 0);
2239 Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL, 0);
2241 if (DEBUG(PARSE))
2242 fprintf(debug_file, "ParseSetParseFile: ${.PARSEDIR} = `%s' "
2243 "${.PARSEFILE} = `%s'\n", pd, pf);
2244 free(dirname);
2248 * Track the makefiles we read - so makefiles can
2249 * set dependencies on them.
2250 * Avoid adding anything more than once.
2253 static void
2254 ParseTrackInput(const char *name)
2256 char *old;
2257 char *fp = NULL;
2258 size_t name_len = strlen(name);
2260 old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2261 if (old) {
2262 /* does it contain name? */
2263 for (; old != NULL; old = strchr(old, ' ')) {
2264 if (*old == ' ')
2265 old++;
2266 if (memcmp(old, name, name_len) == 0
2267 && (old[name_len] == 0 || old[name_len] == ' '))
2268 goto cleanup;
2271 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2272 cleanup:
2273 if (fp) {
2274 free(fp);
2280 *---------------------------------------------------------------------
2281 * Parse_setInput --
2282 * Start Parsing from the given source
2284 * Results:
2285 * None
2287 * Side Effects:
2288 * A structure is added to the includes Lst and readProc, lineno,
2289 * fname and curFile are altered for the new file
2290 *---------------------------------------------------------------------
2292 void
2293 Parse_SetInput(const char *name, int line, int fd,
2294 char *(*nextbuf)(void *, size_t *), void *arg)
2296 char *buf;
2297 size_t len;
2299 if (name == NULL)
2300 name = curFile->fname;
2301 else
2302 ParseTrackInput(name);
2304 if (DEBUG(PARSE))
2305 fprintf(debug_file, "Parse_SetInput: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2306 name, line, fd, nextbuf, arg);
2308 if (fd == -1 && nextbuf == NULL)
2309 /* sanity */
2310 return;
2312 if (curFile != NULL)
2313 /* Save exiting file info */
2314 Lst_AtFront(includes, curFile);
2316 /* Allocate and fill in new structure */
2317 curFile = bmake_malloc(sizeof *curFile);
2320 * Once the previous state has been saved, we can get down to reading
2321 * the new file. We set up the name of the file to be the absolute
2322 * name of the include file so error messages refer to the right
2323 * place.
2325 curFile->fname = name;
2326 curFile->lineno = line;
2327 curFile->first_lineno = line;
2328 curFile->nextbuf = nextbuf;
2329 curFile->nextbuf_arg = arg;
2330 curFile->lf = NULL;
2332 assert(nextbuf != NULL);
2334 /* Get first block of input data */
2335 buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2336 if (buf == NULL) {
2337 /* Was all a waste of time ... */
2338 free(curFile);
2339 return;
2341 curFile->P_str = buf;
2342 curFile->P_ptr = buf;
2343 curFile->P_end = buf+len;
2345 curFile->cond_depth = Cond_save_depth();
2346 ParseSetParseFile(name);
2349 #ifdef SYSVINCLUDE
2351 *---------------------------------------------------------------------
2352 * ParseTraditionalInclude --
2353 * Push to another file.
2355 * The input is the current line. The file name(s) are
2356 * following the "include".
2358 * Results:
2359 * None
2361 * Side Effects:
2362 * A structure is added to the includes Lst and readProc, lineno,
2363 * fname and curFILE are altered for the new file
2364 *---------------------------------------------------------------------
2366 static void
2367 ParseTraditionalInclude(char *line)
2369 char *cp; /* current position in file spec */
2370 int done = 0;
2371 int silent = (line[0] != 'i') ? 1 : 0;
2372 char *file = &line[silent + 7];
2373 char *all_files;
2375 if (DEBUG(PARSE)) {
2376 fprintf(debug_file, "ParseTraditionalInclude: %s\n", file);
2380 * Skip over whitespace
2382 while (isspace((unsigned char)*file))
2383 file++;
2386 * Substitute for any variables in the file name before trying to
2387 * find the thing.
2389 all_files = Var_Subst(NULL, file, VAR_CMD, FALSE);
2391 if (*file == '\0') {
2392 Parse_Error(PARSE_FATAL,
2393 "Filename missing from \"include\"");
2394 return;
2397 for (file = all_files; !done; file = cp + 1) {
2398 /* Skip to end of line or next whitespace */
2399 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2400 continue;
2402 if (*cp)
2403 *cp = '\0';
2404 else
2405 done = 1;
2407 Parse_include_file(file, FALSE, silent);
2409 free(all_files);
2411 #endif
2413 #ifdef GMAKEEXPORT
2415 *---------------------------------------------------------------------
2416 * ParseGmakeExport --
2417 * Parse export <variable>=<value>
2419 * And set the environment with it.
2421 * Results:
2422 * None
2424 * Side Effects:
2425 * None
2426 *---------------------------------------------------------------------
2428 static void
2429 ParseGmakeExport(char *line)
2431 char *variable = &line[6];
2432 char *value;
2434 if (DEBUG(PARSE)) {
2435 fprintf(debug_file, "ParseGmakeExport: %s\n", variable);
2439 * Skip over whitespace
2441 while (isspace((unsigned char)*variable))
2442 variable++;
2444 for (value = variable; *value && *value != '='; value++)
2445 continue;
2447 if (*value != '=') {
2448 Parse_Error(PARSE_FATAL,
2449 "Variable/Value missing from \"export\"");
2450 return;
2454 * Expand the value before putting it in the environment.
2456 value = Var_Subst(NULL, value, VAR_CMD, FALSE);
2457 setenv(variable, value, 1);
2459 #endif
2462 *---------------------------------------------------------------------
2463 * ParseEOF --
2464 * Called when EOF is reached in the current file. If we were reading
2465 * an include file, the includes stack is popped and things set up
2466 * to go back to reading the previous file at the previous location.
2468 * Results:
2469 * CONTINUE if there's more to do. DONE if not.
2471 * Side Effects:
2472 * The old curFILE, is closed. The includes list is shortened.
2473 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2474 *---------------------------------------------------------------------
2476 static int
2477 ParseEOF(void)
2479 char *ptr;
2480 size_t len;
2482 assert(curFile->nextbuf != NULL);
2484 /* get next input buffer, if any */
2485 ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2486 curFile->P_ptr = ptr;
2487 curFile->P_str = ptr;
2488 curFile->P_end = ptr + len;
2489 curFile->lineno = curFile->first_lineno;
2490 if (ptr != NULL) {
2491 /* Iterate again */
2492 return CONTINUE;
2495 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2496 Cond_restore_depth(curFile->cond_depth);
2498 if (curFile->lf != NULL) {
2499 loadedfile_destroy(curFile->lf);
2500 curFile->lf = NULL;
2503 /* Dispose of curFile info */
2504 /* Leak curFile->fname because all the gnodes have pointers to it */
2505 free(curFile->P_str);
2506 free(curFile);
2508 curFile = Lst_DeQueue(includes);
2510 if (curFile == NULL) {
2511 /* We've run out of input */
2512 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2513 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2514 return DONE;
2517 if (DEBUG(PARSE))
2518 fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2519 curFile->fname, curFile->lineno);
2521 /* Restore the PARSEDIR/PARSEFILE variables */
2522 ParseSetParseFile(curFile->fname);
2523 return (CONTINUE);
2526 #define PARSE_RAW 1
2527 #define PARSE_SKIP 2
2529 static char *
2530 ParseGetLine(int flags, int *length)
2532 IFile *cf = curFile;
2533 char *ptr;
2534 char ch;
2535 char *line;
2536 char *line_end;
2537 char *escaped;
2538 char *comment;
2539 char *tp;
2541 /* Loop through blank lines and comment lines */
2542 for (;;) {
2543 cf->lineno++;
2544 line = cf->P_ptr;
2545 ptr = line;
2546 line_end = line;
2547 escaped = NULL;
2548 comment = NULL;
2549 for (;;) {
2550 if (cf->P_end != NULL && ptr == cf->P_end) {
2551 /* end of buffer */
2552 ch = 0;
2553 break;
2555 ch = *ptr;
2556 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2557 if (cf->P_end == NULL)
2558 /* End of string (aka for loop) data */
2559 break;
2560 if (cf->nextbuf != NULL) {
2562 * End of this buffer; return EOF and outer logic
2563 * will get the next one. (eww)
2565 break;
2567 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2568 return NULL;
2571 if (ch == '\\') {
2572 /* Don't treat next character as special, remember first one */
2573 if (escaped == NULL)
2574 escaped = ptr;
2575 if (ptr[1] == '\n')
2576 cf->lineno++;
2577 ptr += 2;
2578 line_end = ptr;
2579 continue;
2581 if (ch == '#' && comment == NULL) {
2582 /* Remember first '#' for comment stripping */
2583 /* Unless previous char was '[', as in modifier :[#] */
2584 if (!(ptr > line && ptr[-1] == '['))
2585 comment = line_end;
2587 ptr++;
2588 if (ch == '\n')
2589 break;
2590 if (!isspace((unsigned char)ch))
2591 /* We are not interested in trailing whitespace */
2592 line_end = ptr;
2595 /* Save next 'to be processed' location */
2596 cf->P_ptr = ptr;
2598 /* Check we have a non-comment, non-blank line */
2599 if (line_end == line || comment == line) {
2600 if (ch == 0)
2601 /* At end of file */
2602 return NULL;
2603 /* Parse another line */
2604 continue;
2607 /* We now have a line of data */
2608 *line_end = 0;
2610 if (flags & PARSE_RAW) {
2611 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2612 *length = line_end - line;
2613 return line;
2616 if (flags & PARSE_SKIP) {
2617 /* Completely ignore non-directives */
2618 if (line[0] != '.')
2619 continue;
2620 /* We could do more of the .else/.elif/.endif checks here */
2622 break;
2625 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2626 if (comment != NULL && line[0] != '\t') {
2627 line_end = comment;
2628 *line_end = 0;
2631 /* If we didn't see a '\\' then the in-situ data is fine */
2632 if (escaped == NULL) {
2633 *length = line_end - line;
2634 return line;
2637 /* Remove escapes from '\n' and '#' */
2638 tp = ptr = escaped;
2639 escaped = line;
2640 for (; ; *tp++ = ch) {
2641 ch = *ptr++;
2642 if (ch != '\\') {
2643 if (ch == 0)
2644 break;
2645 continue;
2648 ch = *ptr++;
2649 if (ch == 0) {
2650 /* Delete '\\' at end of buffer */
2651 tp--;
2652 break;
2655 if (ch == '#' && line[0] != '\t')
2656 /* Delete '\\' from before '#' on non-command lines */
2657 continue;
2659 if (ch != '\n') {
2660 /* Leave '\\' in buffer for later */
2661 *tp++ = '\\';
2662 /* Make sure we don't delete an escaped ' ' from the line end */
2663 escaped = tp + 1;
2664 continue;
2667 /* Escaped '\n' replace following whitespace with a single ' ' */
2668 while (ptr[0] == ' ' || ptr[0] == '\t')
2669 ptr++;
2670 ch = ' ';
2673 /* Delete any trailing spaces - eg from empty continuations */
2674 while (tp > escaped && isspace((unsigned char)tp[-1]))
2675 tp--;
2677 *tp = 0;
2678 *length = tp - line;
2679 return line;
2683 *---------------------------------------------------------------------
2684 * ParseReadLine --
2685 * Read an entire line from the input file. Called only by Parse_File.
2687 * Results:
2688 * A line w/o its newline
2690 * Side Effects:
2691 * Only those associated with reading a character
2692 *---------------------------------------------------------------------
2694 static char *
2695 ParseReadLine(void)
2697 char *line; /* Result */
2698 int lineLength; /* Length of result */
2699 int lineno; /* Saved line # */
2700 int rval;
2702 for (;;) {
2703 line = ParseGetLine(0, &lineLength);
2704 if (line == NULL)
2705 return NULL;
2707 if (line[0] != '.')
2708 return line;
2711 * The line might be a conditional. Ask the conditional module
2712 * about it and act accordingly
2714 switch (Cond_Eval(line)) {
2715 case COND_SKIP:
2716 /* Skip to next conditional that evaluates to COND_PARSE. */
2717 do {
2718 line = ParseGetLine(PARSE_SKIP, &lineLength);
2719 } while (line && Cond_Eval(line) != COND_PARSE);
2720 if (line == NULL)
2721 break;
2722 continue;
2723 case COND_PARSE:
2724 continue;
2725 case COND_INVALID: /* Not a conditional line */
2726 /* Check for .for loops */
2727 rval = For_Eval(line);
2728 if (rval == 0)
2729 /* Not a .for line */
2730 break;
2731 if (rval < 0)
2732 /* Syntax error - error printed, ignore line */
2733 continue;
2734 /* Start of a .for loop */
2735 lineno = curFile->lineno;
2736 /* Accumulate loop lines until matching .endfor */
2737 do {
2738 line = ParseGetLine(PARSE_RAW, &lineLength);
2739 if (line == NULL) {
2740 Parse_Error(PARSE_FATAL,
2741 "Unexpected end of file in for loop.");
2742 break;
2744 } while (For_Accum(line));
2745 /* Stash each iteration as a new 'input file' */
2746 For_Run(lineno);
2747 /* Read next line from for-loop buffer */
2748 continue;
2750 return (line);
2755 *-----------------------------------------------------------------------
2756 * ParseFinishLine --
2757 * Handle the end of a dependency group.
2759 * Results:
2760 * Nothing.
2762 * Side Effects:
2763 * inLine set FALSE. 'targets' list destroyed.
2765 *-----------------------------------------------------------------------
2767 static void
2768 ParseFinishLine(void)
2770 if (inLine) {
2771 Lst_ForEach(targets, Suff_EndTransform, NULL);
2772 Lst_Destroy(targets, ParseHasCommands);
2773 targets = NULL;
2774 inLine = FALSE;
2780 *---------------------------------------------------------------------
2781 * Parse_File --
2782 * Parse a file into its component parts, incorporating it into the
2783 * current dependency graph. This is the main function and controls
2784 * almost every other function in this module
2786 * Input:
2787 * name the name of the file being read
2788 * fd Open file to makefile to parse
2790 * Results:
2791 * None
2793 * Side Effects:
2794 * closes fd.
2795 * Loads. Nodes are added to the list of all targets, nodes and links
2796 * are added to the dependency graph. etc. etc. etc.
2797 *---------------------------------------------------------------------
2799 void
2800 Parse_File(const char *name, int fd)
2802 char *cp; /* pointer into the line */
2803 char *line; /* the line we're working on */
2804 struct loadedfile *lf;
2806 lf = loadfile(name, fd);
2808 inLine = FALSE;
2809 fatals = 0;
2811 if (name == NULL) {
2812 name = "(stdin)";
2815 Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
2816 curFile->lf = lf;
2818 do {
2819 for (; (line = ParseReadLine()) != NULL; ) {
2820 if (DEBUG(PARSE))
2821 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2822 curFile->lineno, line);
2823 if (*line == '.') {
2825 * Lines that begin with the special character may be
2826 * include or undef directives.
2827 * On the other hand they can be suffix rules (.c.o: ...)
2828 * or just dependencies for filenames that start '.'.
2830 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2831 continue;
2833 if (strncmp(cp, "include", 7) == 0 ||
2834 ((cp[0] == 's' || cp[0] == '-') &&
2835 strncmp(&cp[1], "include", 7) == 0)) {
2836 ParseDoInclude(cp);
2837 continue;
2839 if (strncmp(cp, "undef", 5) == 0) {
2840 char *cp2;
2841 for (cp += 5; isspace((unsigned char) *cp); cp++)
2842 continue;
2843 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2844 (*cp2 != '\0'); cp2++)
2845 continue;
2846 *cp2 = '\0';
2847 Var_Delete(cp, VAR_GLOBAL);
2848 continue;
2849 } else if (strncmp(cp, "export", 6) == 0) {
2850 for (cp += 6; isspace((unsigned char) *cp); cp++)
2851 continue;
2852 Var_Export(cp, 1);
2853 continue;
2854 } else if (strncmp(cp, "unexport", 8) == 0) {
2855 Var_UnExport(cp);
2856 continue;
2857 } else if (strncmp(cp, "info", 4) == 0 ||
2858 strncmp(cp, "error", 5) == 0 ||
2859 strncmp(cp, "warning", 7) == 0) {
2860 if (ParseMessage(cp))
2861 continue;
2865 if (*line == '\t') {
2867 * If a line starts with a tab, it can only hope to be
2868 * a creation command.
2870 cp = line + 1;
2871 shellCommand:
2872 for (; isspace ((unsigned char)*cp); cp++) {
2873 continue;
2875 if (*cp) {
2876 if (!inLine)
2877 Parse_Error(PARSE_FATAL,
2878 "Unassociated shell command \"%s\"",
2879 cp);
2881 * So long as it's not a blank line and we're actually
2882 * in a dependency spec, add the command to the list of
2883 * commands of all targets in the dependency spec
2885 if (targets) {
2886 cp = bmake_strdup(cp);
2887 Lst_ForEach(targets, ParseAddCmd, cp);
2888 #ifdef CLEANUP
2889 Lst_AtEnd(targCmds, cp);
2890 #endif
2893 continue;
2896 #ifdef SYSVINCLUDE
2897 if (((strncmp(line, "include", 7) == 0 &&
2898 isspace((unsigned char) line[7])) ||
2899 ((line[0] == 's' || line[0] == '-') &&
2900 strncmp(&line[1], "include", 7) == 0 &&
2901 isspace((unsigned char) line[8]))) &&
2902 strchr(line, ':') == NULL) {
2904 * It's an S3/S5-style "include".
2906 ParseTraditionalInclude(line);
2907 continue;
2909 #endif
2910 #ifdef GMAKEEXPORT
2911 if (strncmp(line, "export", 6) == 0 &&
2912 isspace((unsigned char) line[6]) &&
2913 strchr(line, ':') == NULL) {
2915 * It's a Gmake "export".
2917 ParseGmakeExport(line);
2918 continue;
2920 #endif
2921 if (Parse_IsVar(line)) {
2922 ParseFinishLine();
2923 Parse_DoVar(line, VAR_GLOBAL);
2924 continue;
2927 #ifndef POSIX
2929 * To make life easier on novices, if the line is indented we
2930 * first make sure the line has a dependency operator in it.
2931 * If it doesn't have an operator and we're in a dependency
2932 * line's script, we assume it's actually a shell command
2933 * and add it to the current list of targets.
2935 cp = line;
2936 if (isspace((unsigned char) line[0])) {
2937 while ((*cp != '\0') && isspace((unsigned char) *cp))
2938 cp++;
2939 while (*cp && (ParseIsEscaped(line, cp) ||
2940 (*cp != ':') && (*cp != '!'))) {
2941 cp++;
2943 if (*cp == '\0') {
2944 if (inLine) {
2945 Parse_Error(PARSE_WARNING,
2946 "Shell command needs a leading tab");
2947 goto shellCommand;
2951 #endif
2952 ParseFinishLine();
2955 * For some reason - probably to make the parser impossible -
2956 * a ';' can be used to separate commands from dependencies.
2957 * Attempt to avoid ';' inside substitution patterns.
2960 int level = 0;
2962 for (cp = line; *cp != 0; cp++) {
2963 if (*cp == '\\' && cp[1] != 0) {
2964 cp++;
2965 continue;
2967 if (*cp == '$' &&
2968 (cp[1] == '(' || cp[1] == '{')) {
2969 level++;
2970 continue;
2972 if (level > 0) {
2973 if (*cp == ')' || *cp == '}') {
2974 level--;
2975 continue;
2977 } else if (*cp == ';') {
2978 break;
2982 if (*cp != 0)
2983 /* Terminate the dependency list at the ';' */
2984 *cp++ = 0;
2985 else
2986 cp = NULL;
2989 * We now know it's a dependency line so it needs to have all
2990 * variables expanded before being parsed. Tell the variable
2991 * module to complain if some variable is undefined...
2993 line = Var_Subst(NULL, line, VAR_CMD, TRUE);
2996 * Need a non-circular list for the target nodes
2998 if (targets)
2999 Lst_Destroy(targets, NULL);
3001 targets = Lst_Init(FALSE);
3002 inLine = TRUE;
3004 ParseDoDependency(line);
3005 free(line);
3007 /* If there were commands after a ';', add them now */
3008 if (cp != NULL) {
3009 goto shellCommand;
3013 * Reached EOF, but it may be just EOF of an include file...
3015 } while (ParseEOF() == CONTINUE);
3017 if (fatals) {
3018 (void)fflush(stdout);
3019 (void)fprintf(stderr,
3020 "%s: Fatal errors encountered -- cannot continue",
3021 progname);
3022 PrintOnError(NULL, NULL);
3023 exit(1);
3028 *---------------------------------------------------------------------
3029 * Parse_Init --
3030 * initialize the parsing module
3032 * Results:
3033 * none
3035 * Side Effects:
3036 * the parseIncPath list is initialized...
3037 *---------------------------------------------------------------------
3039 void
3040 Parse_Init(void)
3042 mainNode = NULL;
3043 parseIncPath = Lst_Init(FALSE);
3044 sysIncPath = Lst_Init(FALSE);
3045 defIncPath = Lst_Init(FALSE);
3046 includes = Lst_Init(FALSE);
3047 #ifdef CLEANUP
3048 targCmds = Lst_Init(FALSE);
3049 #endif
3052 void
3053 Parse_End(void)
3055 #ifdef CLEANUP
3056 Lst_Destroy(targCmds, (FreeProc *)free);
3057 if (targets)
3058 Lst_Destroy(targets, NULL);
3059 Lst_Destroy(defIncPath, Dir_Destroy);
3060 Lst_Destroy(sysIncPath, Dir_Destroy);
3061 Lst_Destroy(parseIncPath, Dir_Destroy);
3062 Lst_Destroy(includes, NULL); /* Should be empty now */
3063 #endif
3068 *-----------------------------------------------------------------------
3069 * Parse_MainName --
3070 * Return a Lst of the main target to create for main()'s sake. If
3071 * no such target exists, we Punt with an obnoxious error message.
3073 * Results:
3074 * A Lst of the single node to create.
3076 * Side Effects:
3077 * None.
3079 *-----------------------------------------------------------------------
3082 Parse_MainName(void)
3084 Lst mainList; /* result list */
3086 mainList = Lst_Init(FALSE);
3088 if (mainNode == NULL) {
3089 Punt("no target to make.");
3090 /*NOTREACHED*/
3091 } else if (mainNode->type & OP_DOUBLEDEP) {
3092 (void)Lst_AtEnd(mainList, mainNode);
3093 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3095 else
3096 (void)Lst_AtEnd(mainList, mainNode);
3097 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3098 return (mainList);
3102 *-----------------------------------------------------------------------
3103 * ParseMark --
3104 * Add the filename and lineno to the GNode so that we remember
3105 * where it was first defined.
3107 * Side Effects:
3108 * None.
3110 *-----------------------------------------------------------------------
3112 static void
3113 ParseMark(GNode *gn)
3115 gn->fname = curFile->fname;
3116 gn->lineno = curFile->lineno;