parse.c revision 1.218 1 /* $NetBSD: parse.c,v 1.218 2017/03/01 16:39:49 sjg Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. 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.
21 *
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.
33 */
34
35 /*
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
38 *
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
41 *
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.
57 *
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.
69 */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: parse.c,v 1.218 2017/03/01 16:39:49 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)parse.c 8.3 (Berkeley) 3/19/94";
78 #else
79 __RCSID("$NetBSD: parse.c,v 1.218 2017/03/01 16:39:49 sjg Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83
84 /*-
85 * parse.c --
86 * Functions to parse a makefile.
87 *
88 * One function, Parse_Init, must be called before any functions
89 * in this module are used. After that, the function Parse_File is the
90 * main entry point and controls most of the other functions in this
91 * module.
92 *
93 * Most important structures are kept in Lsts. Directories for
94 * the .include "..." function are kept in the 'parseIncPath' Lst, while
95 * those for the .include <...> are kept in the 'sysIncPath' Lst. The
96 * targets currently being defined are kept in the 'targets' Lst.
97 *
98 * The variables 'fname' and 'lineno' are used to track the name
99 * of the current file and the line number in that file so that error
100 * messages can be more meaningful.
101 *
102 * Interface:
103 * Parse_Init Initialization function which must be
104 * called before anything else in this module
105 * is used.
106 *
107 * Parse_End Cleanup the module
108 *
109 * Parse_File Function used to parse a makefile. It must
110 * be given the name of the file, which should
111 * already have been opened, and a function
112 * to call to read a character from the file.
113 *
114 * Parse_IsVar Returns TRUE if the given line is a
115 * variable assignment. Used by MainParseArgs
116 * to determine if an argument is a target
117 * or a variable assignment. Used internally
118 * for pretty much the same thing...
119 *
120 * Parse_Error Function called when an error occurs in
121 * parsing. Used by the variable and
122 * conditional modules.
123 * Parse_MainName Returns a Lst of the main target to create.
124 */
125
126 #include <sys/types.h>
127 #include <sys/mman.h>
128 #include <sys/stat.h>
129 #include <assert.h>
130 #include <ctype.h>
131 #include <errno.h>
132 #include <stdarg.h>
133 #include <stdio.h>
134
135 #ifndef MAP_FILE
136 #define MAP_FILE 0
137 #endif
138 #ifndef MAP_COPY
139 #define MAP_COPY MAP_PRIVATE
140 #endif
141
142 #include "make.h"
143 #include "hash.h"
144 #include "dir.h"
145 #include "job.h"
146 #include "buf.h"
147 #include "pathnames.h"
148
149 ////////////////////////////////////////////////////////////
150 // types and constants
151
152 /*
153 * Structure for a file being read ("included file")
154 */
155 typedef struct IFile {
156 char *fname; /* name of file */
157 int lineno; /* current line number in file */
158 int first_lineno; /* line number of start of text */
159 int cond_depth; /* 'if' nesting when file opened */
160 Boolean depending; /* state of doing_depend on EOF */
161 char *P_str; /* point to base of string buffer */
162 char *P_ptr; /* point to next char of string buffer */
163 char *P_end; /* point to the end of string buffer */
164 char *(*nextbuf)(void *, size_t *); /* Function to get more data */
165 void *nextbuf_arg; /* Opaque arg for nextbuf() */
166 struct loadedfile *lf; /* loadedfile object, if any */
167 } IFile;
168
169
170 /*
171 * These values are returned by ParseEOF to tell Parse_File whether to
172 * CONTINUE parsing, i.e. it had only reached the end of an include file,
173 * or if it's DONE.
174 */
175 #define CONTINUE 1
176 #define DONE 0
177
178 /*
179 * Tokens for target attributes
180 */
181 typedef enum {
182 Begin, /* .BEGIN */
183 Default, /* .DEFAULT */
184 DeleteOnError, /* .DELETE_ON_ERROR */
185 End, /* .END */
186 dotError, /* .ERROR */
187 Ignore, /* .IGNORE */
188 Includes, /* .INCLUDES */
189 Interrupt, /* .INTERRUPT */
190 Libs, /* .LIBS */
191 Meta, /* .META */
192 MFlags, /* .MFLAGS or .MAKEFLAGS */
193 Main, /* .MAIN and we don't have anything user-specified to
194 * make */
195 NoExport, /* .NOEXPORT */
196 NoMeta, /* .NOMETA */
197 NoMetaCmp, /* .NOMETA_CMP */
198 NoPath, /* .NOPATH */
199 Not, /* Not special */
200 NotParallel, /* .NOTPARALLEL */
201 Null, /* .NULL */
202 ExObjdir, /* .OBJDIR */
203 Order, /* .ORDER */
204 Parallel, /* .PARALLEL */
205 ExPath, /* .PATH */
206 Phony, /* .PHONY */
207 #ifdef POSIX
208 Posix, /* .POSIX */
209 #endif
210 Precious, /* .PRECIOUS */
211 ExShell, /* .SHELL */
212 Silent, /* .SILENT */
213 SingleShell, /* .SINGLESHELL */
214 Stale, /* .STALE */
215 Suffixes, /* .SUFFIXES */
216 Wait, /* .WAIT */
217 Attribute /* Generic attribute */
218 } ParseSpecial;
219
220 /*
221 * Other tokens
222 */
223 #define LPAREN '('
224 #define RPAREN ')'
225
226
227 ////////////////////////////////////////////////////////////
228 // result data
229
230 /*
231 * The main target to create. This is the first target on the first
232 * dependency line in the first makefile.
233 */
234 static GNode *mainNode;
235
236 ////////////////////////////////////////////////////////////
237 // eval state
238
239 /* targets we're working on */
240 static Lst targets;
241
242 #ifdef CLEANUP
243 /* command lines for targets */
244 static Lst targCmds;
245 #endif
246
247 /*
248 * specType contains the SPECial TYPE of the current target. It is
249 * Not if the target is unspecial. If it *is* special, however, the children
250 * are linked as children of the parent but not vice versa. This variable is
251 * set in ParseDoDependency
252 */
253 static ParseSpecial specType;
254
255 /*
256 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
257 * seen, then set to each successive source on the line.
258 */
259 static GNode *predecessor;
260
261 ////////////////////////////////////////////////////////////
262 // parser state
263
264 /* true if currently in a dependency line or its commands */
265 static Boolean inLine;
266
267 /* number of fatal errors */
268 static int fatals = 0;
269
270 /*
271 * Variables for doing includes
272 */
273
274 /* current file being read */
275 static IFile *curFile;
276
277 /* stack of IFiles generated by .includes */
278 static Lst includes;
279
280 /* include paths (lists of directories) */
281 Lst parseIncPath; /* dirs for "..." includes */
282 Lst sysIncPath; /* dirs for <...> includes */
283 Lst defIncPath; /* default for sysIncPath */
284
285 ////////////////////////////////////////////////////////////
286 // parser tables
287
288 /*
289 * The parseKeywords table is searched using binary search when deciding
290 * if a target or source is special. The 'spec' field is the ParseSpecial
291 * type of the keyword ("Not" if the keyword isn't special as a target) while
292 * the 'op' field is the operator to apply to the list of targets if the
293 * keyword is used as a source ("0" if the keyword isn't special as a source)
294 */
295 static const struct {
296 const char *name; /* Name of keyword */
297 ParseSpecial spec; /* Type when used as a target */
298 int op; /* Operator when used as a source */
299 } parseKeywords[] = {
300 { ".BEGIN", Begin, 0 },
301 { ".DEFAULT", Default, 0 },
302 { ".DELETE_ON_ERROR", DeleteOnError, 0 },
303 { ".END", End, 0 },
304 { ".ERROR", dotError, 0 },
305 { ".EXEC", Attribute, OP_EXEC },
306 { ".IGNORE", Ignore, OP_IGNORE },
307 { ".INCLUDES", Includes, 0 },
308 { ".INTERRUPT", Interrupt, 0 },
309 { ".INVISIBLE", Attribute, OP_INVISIBLE },
310 { ".JOIN", Attribute, OP_JOIN },
311 { ".LIBS", Libs, 0 },
312 { ".MADE", Attribute, OP_MADE },
313 { ".MAIN", Main, 0 },
314 { ".MAKE", Attribute, OP_MAKE },
315 { ".MAKEFLAGS", MFlags, 0 },
316 { ".META", Meta, OP_META },
317 { ".MFLAGS", MFlags, 0 },
318 { ".NOMETA", NoMeta, OP_NOMETA },
319 { ".NOMETA_CMP", NoMetaCmp, OP_NOMETA_CMP },
320 { ".NOPATH", NoPath, OP_NOPATH },
321 { ".NOTMAIN", Attribute, OP_NOTMAIN },
322 { ".NOTPARALLEL", NotParallel, 0 },
323 { ".NO_PARALLEL", NotParallel, 0 },
324 { ".NULL", Null, 0 },
325 { ".OBJDIR", ExObjdir, 0 },
326 { ".OPTIONAL", Attribute, OP_OPTIONAL },
327 { ".ORDER", Order, 0 },
328 { ".PARALLEL", Parallel, 0 },
329 { ".PATH", ExPath, 0 },
330 { ".PHONY", Phony, OP_PHONY },
331 #ifdef POSIX
332 { ".POSIX", Posix, 0 },
333 #endif
334 { ".PRECIOUS", Precious, OP_PRECIOUS },
335 { ".RECURSIVE", Attribute, OP_MAKE },
336 { ".SHELL", ExShell, 0 },
337 { ".SILENT", Silent, OP_SILENT },
338 { ".SINGLESHELL", SingleShell, 0 },
339 { ".STALE", Stale, 0 },
340 { ".SUFFIXES", Suffixes, 0 },
341 { ".USE", Attribute, OP_USE },
342 { ".USEBEFORE", Attribute, OP_USEBEFORE },
343 { ".WAIT", Wait, 0 },
344 };
345
346 ////////////////////////////////////////////////////////////
347 // local functions
348
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 static void ParseSetIncludedFile(void);
367 #ifdef SYSVINCLUDE
368 static void ParseTraditionalInclude(char *);
369 #endif
370 #ifdef GMAKEEXPORT
371 static void ParseGmakeExport(char *);
372 #endif
373 static int ParseEOF(void);
374 static char *ParseReadLine(void);
375 static void ParseFinishLine(void);
376 static void ParseMark(GNode *);
377
378 ////////////////////////////////////////////////////////////
379 // file loader
380
381 struct loadedfile {
382 const char *path; /* name, for error reports */
383 char *buf; /* contents buffer */
384 size_t len; /* length of contents */
385 size_t maplen; /* length of mmap area, or 0 */
386 Boolean used; /* XXX: have we used the data yet */
387 };
388
389 /*
390 * Constructor/destructor for loadedfile
391 */
392 static struct loadedfile *
393 loadedfile_create(const char *path)
394 {
395 struct loadedfile *lf;
396
397 lf = bmake_malloc(sizeof(*lf));
398 lf->path = (path == NULL ? "(stdin)" : path);
399 lf->buf = NULL;
400 lf->len = 0;
401 lf->maplen = 0;
402 lf->used = FALSE;
403 return lf;
404 }
405
406 static void
407 loadedfile_destroy(struct loadedfile *lf)
408 {
409 if (lf->buf != NULL) {
410 if (lf->maplen > 0) {
411 munmap(lf->buf, lf->maplen);
412 } else {
413 free(lf->buf);
414 }
415 }
416 free(lf);
417 }
418
419 /*
420 * nextbuf() operation for loadedfile, as needed by the weird and twisted
421 * logic below. Once that's cleaned up, we can get rid of lf->used...
422 */
423 static char *
424 loadedfile_nextbuf(void *x, size_t *len)
425 {
426 struct loadedfile *lf = x;
427
428 if (lf->used) {
429 return NULL;
430 }
431 lf->used = TRUE;
432 *len = lf->len;
433 return lf->buf;
434 }
435
436 /*
437 * Try to get the size of a file.
438 */
439 static ReturnStatus
440 load_getsize(int fd, size_t *ret)
441 {
442 struct stat st;
443
444 if (fstat(fd, &st) < 0) {
445 return FAILURE;
446 }
447
448 if (!S_ISREG(st.st_mode)) {
449 return FAILURE;
450 }
451
452 /*
453 * st_size is an off_t, which is 64 bits signed; *ret is
454 * size_t, which might be 32 bits unsigned or 64 bits
455 * unsigned. Rather than being elaborate, just punt on
456 * files that are more than 2^31 bytes. We should never
457 * see a makefile that size in practice...
458 *
459 * While we're at it reject negative sizes too, just in case.
460 */
461 if (st.st_size < 0 || st.st_size > 0x7fffffff) {
462 return FAILURE;
463 }
464
465 *ret = (size_t) st.st_size;
466 return SUCCESS;
467 }
468
469 /*
470 * Read in a file.
471 *
472 * Until the path search logic can be moved under here instead of
473 * being in the caller in another source file, we need to have the fd
474 * passed in already open. Bleh.
475 *
476 * If the path is NULL use stdin and (to insure against fd leaks)
477 * assert that the caller passed in -1.
478 */
479 static struct loadedfile *
480 loadfile(const char *path, int fd)
481 {
482 struct loadedfile *lf;
483 long pagesize;
484 ssize_t result;
485 size_t bufpos;
486
487 lf = loadedfile_create(path);
488
489 if (path == NULL) {
490 assert(fd == -1);
491 fd = STDIN_FILENO;
492 } else {
493 #if 0 /* notyet */
494 fd = open(path, O_RDONLY);
495 if (fd < 0) {
496 ...
497 Error("%s: %s", path, strerror(errno));
498 exit(1);
499 }
500 #endif
501 }
502
503 if (load_getsize(fd, &lf->len) == SUCCESS) {
504 /* found a size, try mmap */
505 pagesize = sysconf(_SC_PAGESIZE);
506 if (pagesize <= 0) {
507 pagesize = 0x1000;
508 }
509 /* round size up to a page */
510 lf->maplen = pagesize * ((lf->len + pagesize - 1)/pagesize);
511
512 /*
513 * XXX hack for dealing with empty files; remove when
514 * we're no longer limited by interfacing to the old
515 * logic elsewhere in this file.
516 */
517 if (lf->maplen == 0) {
518 lf->maplen = pagesize;
519 }
520
521 /*
522 * FUTURE: remove PROT_WRITE when the parser no longer
523 * needs to scribble on the input.
524 */
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;
536 }
537 goto done;
538 }
539 }
540
541 /* cannot mmap; load the traditional way */
542
543 lf->maplen = 0;
544 lf->len = 1024;
545 lf->buf = bmake_malloc(lf->len);
546
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);
553 }
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);
558 }
559 if (result == 0) {
560 break;
561 }
562 bufpos += result;
563 }
564 assert(bufpos <= lf->len);
565 lf->len = bufpos;
566
567 /* truncate malloc region to actual length (maybe not useful) */
568 if (lf->len > 0) {
569 /* as for mmap case, ensure trailing \n */
570 if (lf->buf[lf->len - 1] != '\n')
571 lf->len++;
572 lf->buf = bmake_realloc(lf->buf, lf->len);
573 lf->buf[lf->len - 1] = '\n';
574 }
575
576 done:
577 if (path != NULL) {
578 close(fd);
579 }
580 return lf;
581 }
582
583 ////////////////////////////////////////////////////////////
584 // old code
585
586 /*-
587 *----------------------------------------------------------------------
588 * ParseIsEscaped --
589 * Check if the current character is escaped on the current line
590 *
591 * Results:
592 * 0 if the character is not backslash escaped, 1 otherwise
593 *
594 * Side Effects:
595 * None
596 *----------------------------------------------------------------------
597 */
598 static int
599 ParseIsEscaped(const char *line, const char *c)
600 {
601 int active = 0;
602 for (;;) {
603 if (line == c)
604 return active;
605 if (*--c != '\\')
606 return active;
607 active = !active;
608 }
609 }
610
611 /*-
612 *----------------------------------------------------------------------
613 * ParseFindKeyword --
614 * Look in the table of keywords for one matching the given string.
615 *
616 * Input:
617 * str String to find
618 *
619 * Results:
620 * The index of the keyword, or -1 if it isn't there.
621 *
622 * Side Effects:
623 * None
624 *----------------------------------------------------------------------
625 */
626 static int
627 ParseFindKeyword(const char *str)
628 {
629 int start, end, cur;
630 int diff;
631
632 start = 0;
633 end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
634
635 do {
636 cur = start + ((end - start) / 2);
637 diff = strcmp(str, parseKeywords[cur].name);
638
639 if (diff == 0) {
640 return (cur);
641 } else if (diff < 0) {
642 end = cur - 1;
643 } else {
644 start = cur + 1;
645 }
646 } while (start <= end);
647 return (-1);
648 }
649
650 /*-
651 * ParseVErrorInternal --
652 * Error message abort function for parsing. Prints out the context
653 * of the error (line number and file) as well as the message with
654 * two optional arguments.
655 *
656 * Results:
657 * None
658 *
659 * Side Effects:
660 * "fatals" is incremented if the level is PARSE_FATAL.
661 */
662 /* VARARGS */
663 static void
664 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
665 const char *fmt, va_list ap)
666 {
667 static Boolean fatal_warning_error_printed = FALSE;
668
669 (void)fprintf(f, "%s: ", progname);
670
671 if (cfname != NULL) {
672 (void)fprintf(f, "\"");
673 if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) {
674 char *cp;
675 const char *dir;
676
677 /*
678 * Nothing is more annoying than not knowing
679 * which Makefile is the culprit.
680 */
681 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
682 if (dir == NULL || *dir == '\0' ||
683 (*dir == '.' && dir[1] == '\0'))
684 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
685 if (dir == NULL)
686 dir = ".";
687
688 (void)fprintf(f, "%s/%s", dir, cfname);
689 } else
690 (void)fprintf(f, "%s", cfname);
691
692 (void)fprintf(f, "\" line %d: ", (int)clineno);
693 }
694 if (type == PARSE_WARNING)
695 (void)fprintf(f, "warning: ");
696 (void)vfprintf(f, fmt, ap);
697 (void)fprintf(f, "\n");
698 (void)fflush(f);
699 if (type == PARSE_FATAL || parseWarnFatal)
700 fatals += 1;
701 if (parseWarnFatal && !fatal_warning_error_printed) {
702 Error("parsing warnings being treated as errors");
703 fatal_warning_error_printed = TRUE;
704 }
705 }
706
707 /*-
708 * ParseErrorInternal --
709 * Error function
710 *
711 * Results:
712 * None
713 *
714 * Side Effects:
715 * None
716 */
717 /* VARARGS */
718 static void
719 ParseErrorInternal(const char *cfname, size_t clineno, int type,
720 const char *fmt, ...)
721 {
722 va_list ap;
723
724 va_start(ap, fmt);
725 (void)fflush(stdout);
726 ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
727 va_end(ap);
728
729 if (debug_file != stderr && debug_file != stdout) {
730 va_start(ap, fmt);
731 ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
732 va_end(ap);
733 }
734 }
735
736 /*-
737 * Parse_Error --
738 * External interface to ParseErrorInternal; uses the default filename
739 * Line number.
740 *
741 * Results:
742 * None
743 *
744 * Side Effects:
745 * None
746 */
747 /* VARARGS */
748 void
749 Parse_Error(int type, const char *fmt, ...)
750 {
751 va_list ap;
752 const char *fname;
753 size_t lineno;
754
755 if (curFile == NULL) {
756 fname = NULL;
757 lineno = 0;
758 } else {
759 fname = curFile->fname;
760 lineno = curFile->lineno;
761 }
762
763 va_start(ap, fmt);
764 (void)fflush(stdout);
765 ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
766 va_end(ap);
767
768 if (debug_file != stderr && debug_file != stdout) {
769 va_start(ap, fmt);
770 ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap);
771 va_end(ap);
772 }
773 }
774
775
776 /*
777 * ParseMessage
778 * Parse a .info .warning or .error directive
779 *
780 * The input is the line minus the ".". We substitute
781 * variables, print the message and exit(1) (for .error) or just print
782 * a warning if the directive is malformed.
783 */
784 static Boolean
785 ParseMessage(char *line)
786 {
787 int mtype;
788
789 switch(*line) {
790 case 'i':
791 mtype = 0;
792 break;
793 case 'w':
794 mtype = PARSE_WARNING;
795 break;
796 case 'e':
797 mtype = PARSE_FATAL;
798 break;
799 default:
800 Parse_Error(PARSE_WARNING, "invalid syntax: \".%s\"", line);
801 return FALSE;
802 }
803
804 while (isalpha((unsigned char)*line))
805 line++;
806 if (!isspace((unsigned char)*line))
807 return FALSE; /* not for us */
808 while (isspace((unsigned char)*line))
809 line++;
810
811 line = Var_Subst(NULL, line, VAR_CMD, VARF_WANTRES);
812 Parse_Error(mtype, "%s", line);
813 free(line);
814
815 if (mtype == PARSE_FATAL) {
816 /* Terminate immediately. */
817 exit(1);
818 }
819 return TRUE;
820 }
821
822 /*-
823 *---------------------------------------------------------------------
824 * ParseLinkSrc --
825 * Link the parent node to its new child. Used in a Lst_ForEach by
826 * ParseDoDependency. If the specType isn't 'Not', the parent
827 * isn't linked as a parent of the child.
828 *
829 * Input:
830 * pgnp The parent node
831 * cgpn The child node
832 *
833 * Results:
834 * Always = 0
835 *
836 * Side Effects:
837 * New elements are added to the parents list of cgn and the
838 * children list of cgn. the unmade field of pgn is updated
839 * to reflect the additional child.
840 *---------------------------------------------------------------------
841 */
842 static int
843 ParseLinkSrc(void *pgnp, void *cgnp)
844 {
845 GNode *pgn = (GNode *)pgnp;
846 GNode *cgn = (GNode *)cgnp;
847
848 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
849 pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
850 (void)Lst_AtEnd(pgn->children, cgn);
851 if (specType == Not)
852 (void)Lst_AtEnd(cgn->parents, pgn);
853 pgn->unmade += 1;
854 if (DEBUG(PARSE)) {
855 fprintf(debug_file, "# %s: added child %s - %s\n", __func__,
856 pgn->name, cgn->name);
857 Targ_PrintNode(pgn, 0);
858 Targ_PrintNode(cgn, 0);
859 }
860 return (0);
861 }
862
863 /*-
864 *---------------------------------------------------------------------
865 * ParseDoOp --
866 * Apply the parsed operator to the given target node. Used in a
867 * Lst_ForEach call by ParseDoDependency once all targets have
868 * been found and their operator parsed. If the previous and new
869 * operators are incompatible, a major error is taken.
870 *
871 * Input:
872 * gnp The node to which the operator is to be applied
873 * opp The operator to apply
874 *
875 * Results:
876 * Always 0
877 *
878 * Side Effects:
879 * The type field of the node is altered to reflect any new bits in
880 * the op.
881 *---------------------------------------------------------------------
882 */
883 static int
884 ParseDoOp(void *gnp, void *opp)
885 {
886 GNode *gn = (GNode *)gnp;
887 int op = *(int *)opp;
888 /*
889 * If the dependency mask of the operator and the node don't match and
890 * the node has actually had an operator applied to it before, and
891 * the operator actually has some dependency information in it, complain.
892 */
893 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
894 !OP_NOP(gn->type) && !OP_NOP(op))
895 {
896 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
897 return (1);
898 }
899
900 if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
901 /*
902 * If the node was the object of a :: operator, we need to create a
903 * new instance of it for the children and commands on this dependency
904 * line. The new instance is placed on the 'cohorts' list of the
905 * initial one (note the initial one is not on its own cohorts list)
906 * and the new instance is linked to all parents of the initial
907 * instance.
908 */
909 GNode *cohort;
910
911 /*
912 * Propagate copied bits to the initial node. They'll be propagated
913 * back to the rest of the cohorts later.
914 */
915 gn->type |= op & ~OP_OPMASK;
916
917 cohort = Targ_FindNode(gn->name, TARG_NOHASH);
918 if (doing_depend)
919 ParseMark(cohort);
920 /*
921 * Make the cohort invisible as well to avoid duplicating it into
922 * other variables. True, parents of this target won't tend to do
923 * anything with their local variables, but better safe than
924 * sorry. (I think this is pointless now, since the relevant list
925 * traversals will no longer see this node anyway. -mycroft)
926 */
927 cohort->type = op | OP_INVISIBLE;
928 (void)Lst_AtEnd(gn->cohorts, cohort);
929 cohort->centurion = gn;
930 gn->unmade_cohorts += 1;
931 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
932 gn->unmade_cohorts);
933 } else {
934 /*
935 * We don't want to nuke any previous flags (whatever they were) so we
936 * just OR the new operator into the old
937 */
938 gn->type |= op;
939 }
940
941 return (0);
942 }
943
944 /*-
945 *---------------------------------------------------------------------
946 * ParseDoSrc --
947 * Given the name of a source, figure out if it is an attribute
948 * and apply it to the targets if it is. Else decide if there is
949 * some attribute which should be applied *to* the source because
950 * of some special target and apply it if so. Otherwise, make the
951 * source be a child of the targets in the list 'targets'
952 *
953 * Input:
954 * tOp operator (if any) from special targets
955 * src name of the source to handle
956 *
957 * Results:
958 * None
959 *
960 * Side Effects:
961 * Operator bits may be added to the list of targets or to the source.
962 * The targets may have a new source added to their lists of children.
963 *---------------------------------------------------------------------
964 */
965 static void
966 ParseDoSrc(int tOp, const char *src)
967 {
968 GNode *gn = NULL;
969 static int wait_number = 0;
970 char wait_src[16];
971
972 if (*src == '.' && isupper ((unsigned char)src[1])) {
973 int keywd = ParseFindKeyword(src);
974 if (keywd != -1) {
975 int op = parseKeywords[keywd].op;
976 if (op != 0) {
977 Lst_ForEach(targets, ParseDoOp, &op);
978 return;
979 }
980 if (parseKeywords[keywd].spec == Wait) {
981 /*
982 * We add a .WAIT node in the dependency list.
983 * After any dynamic dependencies (and filename globbing)
984 * have happened, it is given a dependency on the each
985 * previous child back to and previous .WAIT node.
986 * The next child won't be scheduled until the .WAIT node
987 * is built.
988 * We give each .WAIT node a unique name (mainly for diag).
989 */
990 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
991 gn = Targ_FindNode(wait_src, TARG_NOHASH);
992 if (doing_depend)
993 ParseMark(gn);
994 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
995 Lst_ForEach(targets, ParseLinkSrc, gn);
996 return;
997 }
998 }
999 }
1000
1001 switch (specType) {
1002 case Main:
1003 /*
1004 * If we have noted the existence of a .MAIN, it means we need
1005 * to add the sources of said target to the list of things
1006 * to create. The string 'src' is likely to be free, so we
1007 * must make a new copy of it. Note that this will only be
1008 * invoked if the user didn't specify a target on the command
1009 * line. This is to allow #ifmake's to succeed, or something...
1010 */
1011 (void)Lst_AtEnd(create, bmake_strdup(src));
1012 /*
1013 * Add the name to the .TARGETS variable as well, so the user can
1014 * employ that, if desired.
1015 */
1016 Var_Append(".TARGETS", src, VAR_GLOBAL);
1017 return;
1018
1019 case Order:
1020 /*
1021 * Create proper predecessor/successor links between the previous
1022 * source and the current one.
1023 */
1024 gn = Targ_FindNode(src, TARG_CREATE);
1025 if (doing_depend)
1026 ParseMark(gn);
1027 if (predecessor != NULL) {
1028 (void)Lst_AtEnd(predecessor->order_succ, gn);
1029 (void)Lst_AtEnd(gn->order_pred, predecessor);
1030 if (DEBUG(PARSE)) {
1031 fprintf(debug_file, "# %s: added Order dependency %s - %s\n",
1032 __func__, predecessor->name, gn->name);
1033 Targ_PrintNode(predecessor, 0);
1034 Targ_PrintNode(gn, 0);
1035 }
1036 }
1037 /*
1038 * The current source now becomes the predecessor for the next one.
1039 */
1040 predecessor = gn;
1041 break;
1042
1043 default:
1044 /*
1045 * If the source is not an attribute, we need to find/create
1046 * a node for it. After that we can apply any operator to it
1047 * from a special target or link it to its parents, as
1048 * appropriate.
1049 *
1050 * In the case of a source that was the object of a :: operator,
1051 * the attribute is applied to all of its instances (as kept in
1052 * the 'cohorts' list of the node) or all the cohorts are linked
1053 * to all the targets.
1054 */
1055
1056 /* Find/create the 'src' node and attach to all targets */
1057 gn = Targ_FindNode(src, TARG_CREATE);
1058 if (doing_depend)
1059 ParseMark(gn);
1060 if (tOp) {
1061 gn->type |= tOp;
1062 } else {
1063 Lst_ForEach(targets, ParseLinkSrc, gn);
1064 }
1065 break;
1066 }
1067 }
1068
1069 /*-
1070 *-----------------------------------------------------------------------
1071 * ParseFindMain --
1072 * Find a real target in the list and set it to be the main one.
1073 * Called by ParseDoDependency when a main target hasn't been found
1074 * yet.
1075 *
1076 * Input:
1077 * gnp Node to examine
1078 *
1079 * Results:
1080 * 0 if main not found yet, 1 if it is.
1081 *
1082 * Side Effects:
1083 * mainNode is changed and Targ_SetMain is called.
1084 *
1085 *-----------------------------------------------------------------------
1086 */
1087 static int
1088 ParseFindMain(void *gnp, void *dummy)
1089 {
1090 GNode *gn = (GNode *)gnp;
1091 if ((gn->type & OP_NOTARGET) == 0) {
1092 mainNode = gn;
1093 Targ_SetMain(gn);
1094 return (dummy ? 1 : 1);
1095 } else {
1096 return (dummy ? 0 : 0);
1097 }
1098 }
1099
1100 /*-
1101 *-----------------------------------------------------------------------
1102 * ParseAddDir --
1103 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
1104 *
1105 * Results:
1106 * === 0
1107 *
1108 * Side Effects:
1109 * See Dir_AddDir.
1110 *
1111 *-----------------------------------------------------------------------
1112 */
1113 static int
1114 ParseAddDir(void *path, void *name)
1115 {
1116 (void)Dir_AddDir((Lst) path, (char *)name);
1117 return(0);
1118 }
1119
1120 /*-
1121 *-----------------------------------------------------------------------
1122 * ParseClearPath --
1123 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
1124 *
1125 * Results:
1126 * === 0
1127 *
1128 * Side Effects:
1129 * See Dir_ClearPath
1130 *
1131 *-----------------------------------------------------------------------
1132 */
1133 static int
1134 ParseClearPath(void *path, void *dummy)
1135 {
1136 Dir_ClearPath((Lst) path);
1137 return(dummy ? 0 : 0);
1138 }
1139
1140 /*-
1141 *---------------------------------------------------------------------
1142 * ParseDoDependency --
1143 * Parse the dependency line in line.
1144 *
1145 * Input:
1146 * line the line to parse
1147 *
1148 * Results:
1149 * None
1150 *
1151 * Side Effects:
1152 * The nodes of the sources are linked as children to the nodes of the
1153 * targets. Some nodes may be created.
1154 *
1155 * We parse a dependency line by first extracting words from the line and
1156 * finding nodes in the list of all targets with that name. This is done
1157 * until a character is encountered which is an operator character. Currently
1158 * these are only ! and :. At this point the operator is parsed and the
1159 * pointer into the line advanced until the first source is encountered.
1160 * The parsed operator is applied to each node in the 'targets' list,
1161 * which is where the nodes found for the targets are kept, by means of
1162 * the ParseDoOp function.
1163 * The sources are read in much the same way as the targets were except
1164 * that now they are expanded using the wildcarding scheme of the C-Shell
1165 * and all instances of the resulting words in the list of all targets
1166 * are found. Each of the resulting nodes is then linked to each of the
1167 * targets as one of its children.
1168 * Certain targets are handled specially. These are the ones detailed
1169 * by the specType variable.
1170 * The storing of transformation rules is also taken care of here.
1171 * A target is recognized as a transformation rule by calling
1172 * Suff_IsTransform. If it is a transformation rule, its node is gotten
1173 * from the suffix module via Suff_AddTransform rather than the standard
1174 * Targ_FindNode in the target module.
1175 *---------------------------------------------------------------------
1176 */
1177 static void
1178 ParseDoDependency(char *line)
1179 {
1180 char *cp; /* our current position */
1181 GNode *gn = NULL; /* a general purpose temporary node */
1182 int op; /* the operator on the line */
1183 char savec; /* a place to save a character */
1184 Lst paths; /* List of search paths to alter when parsing
1185 * a list of .PATH targets */
1186 int tOp; /* operator from special target */
1187 Lst sources; /* list of archive source names after
1188 * expansion */
1189 Lst curTargs; /* list of target names to be found and added
1190 * to the targets list */
1191 char *lstart = line;
1192
1193 if (DEBUG(PARSE))
1194 fprintf(debug_file, "ParseDoDependency(%s)\n", line);
1195 tOp = 0;
1196
1197 specType = Not;
1198 paths = NULL;
1199
1200 curTargs = Lst_Init(FALSE);
1201
1202 /*
1203 * First, grind through the targets.
1204 */
1205
1206 do {
1207 /*
1208 * Here LINE points to the beginning of the next word, and
1209 * LSTART points to the actual beginning of the line.
1210 */
1211
1212 /* Find the end of the next word. */
1213 for (cp = line; *cp && (ParseIsEscaped(lstart, cp) ||
1214 !(isspace((unsigned char)*cp) ||
1215 *cp == '!' || *cp == ':' || *cp == LPAREN));
1216 cp++) {
1217 if (*cp == '$') {
1218 /*
1219 * Must be a dynamic source (would have been expanded
1220 * otherwise), so call the Var module to parse the puppy
1221 * so we can safely advance beyond it...There should be
1222 * no errors in this, as they would have been discovered
1223 * in the initial Var_Subst and we wouldn't be here.
1224 */
1225 int length;
1226 void *freeIt;
1227
1228 (void)Var_Parse(cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES,
1229 &length, &freeIt);
1230 free(freeIt);
1231 cp += length-1;
1232 }
1233 }
1234
1235 /*
1236 * If the word is followed by a left parenthesis, it's the
1237 * name of an object file inside an archive (ar file).
1238 */
1239 if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
1240 /*
1241 * Archives must be handled specially to make sure the OP_ARCHV
1242 * flag is set in their 'type' field, for one thing, and because
1243 * things like "archive(file1.o file2.o file3.o)" are permissible.
1244 * Arch_ParseArchive will set 'line' to be the first non-blank
1245 * after the archive-spec. It creates/finds nodes for the members
1246 * and places them on the given list, returning SUCCESS if all
1247 * went well and FAILURE if there was an error in the
1248 * specification. On error, line should remain untouched.
1249 */
1250 if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
1251 Parse_Error(PARSE_FATAL,
1252 "Error in archive specification: \"%s\"", line);
1253 goto out;
1254 } else {
1255 /* Done with this word; on to the next. */
1256 cp = line;
1257 continue;
1258 }
1259 }
1260
1261 if (!*cp) {
1262 /*
1263 * We got to the end of the line while we were still
1264 * looking at targets.
1265 *
1266 * Ending a dependency line without an operator is a Bozo
1267 * no-no. As a heuristic, this is also often triggered by
1268 * undetected conflicts from cvs/rcs merges.
1269 */
1270 if ((strncmp(line, "<<<<<<", 6) == 0) ||
1271 (strncmp(line, "======", 6) == 0) ||
1272 (strncmp(line, ">>>>>>", 6) == 0))
1273 Parse_Error(PARSE_FATAL,
1274 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1275 else
1276 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1277 : "Need an operator");
1278 goto out;
1279 }
1280
1281 /* Insert a null terminator. */
1282 savec = *cp;
1283 *cp = '\0';
1284
1285 /*
1286 * Got the word. See if it's a special target and if so set
1287 * specType to match it.
1288 */
1289 if (*line == '.' && isupper ((unsigned char)line[1])) {
1290 /*
1291 * See if the target is a special target that must have it
1292 * or its sources handled specially.
1293 */
1294 int keywd = ParseFindKeyword(line);
1295 if (keywd != -1) {
1296 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1297 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1298 goto out;
1299 }
1300
1301 specType = parseKeywords[keywd].spec;
1302 tOp = parseKeywords[keywd].op;
1303
1304 /*
1305 * Certain special targets have special semantics:
1306 * .PATH Have to set the dirSearchPath
1307 * variable too
1308 * .MAIN Its sources are only used if
1309 * nothing has been specified to
1310 * create.
1311 * .DEFAULT Need to create a node to hang
1312 * commands on, but we don't want
1313 * it in the graph, nor do we want
1314 * it to be the Main Target, so we
1315 * create it, set OP_NOTMAIN and
1316 * add it to the list, setting
1317 * DEFAULT to the new node for
1318 * later use. We claim the node is
1319 * A transformation rule to make
1320 * life easier later, when we'll
1321 * use Make_HandleUse to actually
1322 * apply the .DEFAULT commands.
1323 * .PHONY The list of targets
1324 * .NOPATH Don't search for file in the path
1325 * .STALE
1326 * .BEGIN
1327 * .END
1328 * .ERROR
1329 * .DELETE_ON_ERROR
1330 * .INTERRUPT Are not to be considered the
1331 * main target.
1332 * .NOTPARALLEL Make only one target at a time.
1333 * .SINGLESHELL Create a shell for each command.
1334 * .ORDER Must set initial predecessor to NULL
1335 */
1336 switch (specType) {
1337 case ExPath:
1338 if (paths == NULL) {
1339 paths = Lst_Init(FALSE);
1340 }
1341 (void)Lst_AtEnd(paths, dirSearchPath);
1342 break;
1343 case Main:
1344 if (!Lst_IsEmpty(create)) {
1345 specType = Not;
1346 }
1347 break;
1348 case Begin:
1349 case End:
1350 case Stale:
1351 case dotError:
1352 case Interrupt:
1353 gn = Targ_FindNode(line, TARG_CREATE);
1354 if (doing_depend)
1355 ParseMark(gn);
1356 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1357 (void)Lst_AtEnd(targets, gn);
1358 break;
1359 case Default:
1360 gn = Targ_NewGN(".DEFAULT");
1361 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1362 (void)Lst_AtEnd(targets, gn);
1363 DEFAULT = gn;
1364 break;
1365 case DeleteOnError:
1366 deleteOnError = TRUE;
1367 break;
1368 case NotParallel:
1369 maxJobs = 1;
1370 break;
1371 case SingleShell:
1372 compatMake = TRUE;
1373 break;
1374 case Order:
1375 predecessor = NULL;
1376 break;
1377 default:
1378 break;
1379 }
1380 } else if (strncmp(line, ".PATH", 5) == 0) {
1381 /*
1382 * .PATH<suffix> has to be handled specially.
1383 * Call on the suffix module to give us a path to
1384 * modify.
1385 */
1386 Lst path;
1387
1388 specType = ExPath;
1389 path = Suff_GetPath(&line[5]);
1390 if (path == NULL) {
1391 Parse_Error(PARSE_FATAL,
1392 "Suffix '%s' not defined (yet)",
1393 &line[5]);
1394 goto out;
1395 } else {
1396 if (paths == NULL) {
1397 paths = Lst_Init(FALSE);
1398 }
1399 (void)Lst_AtEnd(paths, path);
1400 }
1401 }
1402 }
1403
1404 /*
1405 * Have word in line. Get or create its node and stick it at
1406 * the end of the targets list
1407 */
1408 if ((specType == Not) && (*line != '\0')) {
1409 if (Dir_HasWildcards(line)) {
1410 /*
1411 * Targets are to be sought only in the current directory,
1412 * so create an empty path for the thing. Note we need to
1413 * use Dir_Destroy in the destruction of the path as the
1414 * Dir module could have added a directory to the path...
1415 */
1416 Lst emptyPath = Lst_Init(FALSE);
1417
1418 Dir_Expand(line, emptyPath, curTargs);
1419
1420 Lst_Destroy(emptyPath, Dir_Destroy);
1421 } else {
1422 /*
1423 * No wildcards, but we want to avoid code duplication,
1424 * so create a list with the word on it.
1425 */
1426 (void)Lst_AtEnd(curTargs, line);
1427 }
1428
1429 /* Apply the targets. */
1430
1431 while(!Lst_IsEmpty(curTargs)) {
1432 char *targName = (char *)Lst_DeQueue(curTargs);
1433
1434 if (!Suff_IsTransform (targName)) {
1435 gn = Targ_FindNode(targName, TARG_CREATE);
1436 } else {
1437 gn = Suff_AddTransform(targName);
1438 }
1439 if (doing_depend)
1440 ParseMark(gn);
1441
1442 (void)Lst_AtEnd(targets, gn);
1443 }
1444 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1445 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1446 }
1447
1448 /* Don't need the inserted null terminator any more. */
1449 *cp = savec;
1450
1451 /*
1452 * If it is a special type and not .PATH, it's the only target we
1453 * allow on this line...
1454 */
1455 if (specType != Not && specType != ExPath) {
1456 Boolean warning = FALSE;
1457
1458 while (*cp && (ParseIsEscaped(lstart, cp) ||
1459 ((*cp != '!') && (*cp != ':')))) {
1460 if (ParseIsEscaped(lstart, cp) ||
1461 (*cp != ' ' && *cp != '\t')) {
1462 warning = TRUE;
1463 }
1464 cp++;
1465 }
1466 if (warning) {
1467 Parse_Error(PARSE_WARNING, "Extra target ignored");
1468 }
1469 } else {
1470 while (*cp && isspace ((unsigned char)*cp)) {
1471 cp++;
1472 }
1473 }
1474 line = cp;
1475 } while (*line && (ParseIsEscaped(lstart, line) ||
1476 ((*line != '!') && (*line != ':'))));
1477
1478 /*
1479 * Don't need the list of target names anymore...
1480 */
1481 Lst_Destroy(curTargs, NULL);
1482 curTargs = NULL;
1483
1484 if (!Lst_IsEmpty(targets)) {
1485 switch(specType) {
1486 default:
1487 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1488 break;
1489 case Default:
1490 case Stale:
1491 case Begin:
1492 case End:
1493 case dotError:
1494 case Interrupt:
1495 /*
1496 * These four create nodes on which to hang commands, so
1497 * targets shouldn't be empty...
1498 */
1499 case Not:
1500 /*
1501 * Nothing special here -- targets can be empty if it wants.
1502 */
1503 break;
1504 }
1505 }
1506
1507 /*
1508 * Have now parsed all the target names. Must parse the operator next. The
1509 * result is left in op .
1510 */
1511 if (*cp == '!') {
1512 op = OP_FORCE;
1513 } else if (*cp == ':') {
1514 if (cp[1] == ':') {
1515 op = OP_DOUBLEDEP;
1516 cp++;
1517 } else {
1518 op = OP_DEPENDS;
1519 }
1520 } else {
1521 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1522 : "Missing dependency operator");
1523 goto out;
1524 }
1525
1526 /* Advance beyond the operator */
1527 cp++;
1528
1529 /*
1530 * Apply the operator to the target. This is how we remember which
1531 * operator a target was defined with. It fails if the operator
1532 * used isn't consistent across all references.
1533 */
1534 Lst_ForEach(targets, ParseDoOp, &op);
1535
1536 /*
1537 * Onward to the sources.
1538 *
1539 * LINE will now point to the first source word, if any, or the
1540 * end of the string if not.
1541 */
1542 while (*cp && isspace ((unsigned char)*cp)) {
1543 cp++;
1544 }
1545 line = cp;
1546
1547 /*
1548 * Several special targets take different actions if present with no
1549 * sources:
1550 * a .SUFFIXES line with no sources clears out all old suffixes
1551 * a .PRECIOUS line makes all targets precious
1552 * a .IGNORE line ignores errors for all targets
1553 * a .SILENT line creates silence when making all targets
1554 * a .PATH removes all directories from the search path(s).
1555 */
1556 if (!*line) {
1557 switch (specType) {
1558 case Suffixes:
1559 Suff_ClearSuffixes();
1560 break;
1561 case Precious:
1562 allPrecious = TRUE;
1563 break;
1564 case Ignore:
1565 ignoreErrors = TRUE;
1566 break;
1567 case Silent:
1568 beSilent = TRUE;
1569 break;
1570 case ExPath:
1571 Lst_ForEach(paths, ParseClearPath, NULL);
1572 Dir_SetPATH();
1573 break;
1574 #ifdef POSIX
1575 case Posix:
1576 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1577 break;
1578 #endif
1579 default:
1580 break;
1581 }
1582 } else if (specType == MFlags) {
1583 /*
1584 * Call on functions in main.c to deal with these arguments and
1585 * set the initial character to a null-character so the loop to
1586 * get sources won't get anything
1587 */
1588 Main_ParseArgLine(line);
1589 *line = '\0';
1590 } else if (specType == ExShell) {
1591 if (Job_ParseShell(line) != SUCCESS) {
1592 Parse_Error(PARSE_FATAL, "improper shell specification");
1593 goto out;
1594 }
1595 *line = '\0';
1596 } else if ((specType == NotParallel) || (specType == SingleShell) ||
1597 (specType == DeleteOnError)) {
1598 *line = '\0';
1599 }
1600
1601 /*
1602 * NOW GO FOR THE SOURCES
1603 */
1604 if ((specType == Suffixes) || (specType == ExPath) ||
1605 (specType == Includes) || (specType == Libs) ||
1606 (specType == Null) || (specType == ExObjdir))
1607 {
1608 while (*line) {
1609 /*
1610 * If the target was one that doesn't take files as its sources
1611 * but takes something like suffixes, we take each
1612 * space-separated word on the line as a something and deal
1613 * with it accordingly.
1614 *
1615 * If the target was .SUFFIXES, we take each source as a
1616 * suffix and add it to the list of suffixes maintained by the
1617 * Suff module.
1618 *
1619 * If the target was a .PATH, we add the source as a directory
1620 * to search on the search path.
1621 *
1622 * If it was .INCLUDES, the source is taken to be the suffix of
1623 * files which will be #included and whose search path should
1624 * be present in the .INCLUDES variable.
1625 *
1626 * If it was .LIBS, the source is taken to be the suffix of
1627 * files which are considered libraries and whose search path
1628 * should be present in the .LIBS variable.
1629 *
1630 * If it was .NULL, the source is the suffix to use when a file
1631 * has no valid suffix.
1632 *
1633 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1634 * and will cause make to do a new chdir to that path.
1635 */
1636 while (*cp && !isspace ((unsigned char)*cp)) {
1637 cp++;
1638 }
1639 savec = *cp;
1640 *cp = '\0';
1641 switch (specType) {
1642 case Suffixes:
1643 Suff_AddSuffix(line, &mainNode);
1644 break;
1645 case ExPath:
1646 Lst_ForEach(paths, ParseAddDir, line);
1647 break;
1648 case Includes:
1649 Suff_AddInclude(line);
1650 break;
1651 case Libs:
1652 Suff_AddLib(line);
1653 break;
1654 case Null:
1655 Suff_SetNull(line);
1656 break;
1657 case ExObjdir:
1658 Main_SetObjdir("%s", line);
1659 break;
1660 default:
1661 break;
1662 }
1663 *cp = savec;
1664 if (savec != '\0') {
1665 cp++;
1666 }
1667 while (*cp && isspace ((unsigned char)*cp)) {
1668 cp++;
1669 }
1670 line = cp;
1671 }
1672 if (paths) {
1673 Lst_Destroy(paths, NULL);
1674 }
1675 if (specType == ExPath)
1676 Dir_SetPATH();
1677 } else {
1678 while (*line) {
1679 /*
1680 * The targets take real sources, so we must beware of archive
1681 * specifications (i.e. things with left parentheses in them)
1682 * and handle them accordingly.
1683 */
1684 for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1685 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1686 /*
1687 * Only stop for a left parenthesis if it isn't at the
1688 * start of a word (that'll be for variable changes
1689 * later) and isn't preceded by a dollar sign (a dynamic
1690 * source).
1691 */
1692 break;
1693 }
1694 }
1695
1696 if (*cp == LPAREN) {
1697 sources = Lst_Init(FALSE);
1698 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1699 Parse_Error(PARSE_FATAL,
1700 "Error in source archive spec \"%s\"", line);
1701 goto out;
1702 }
1703
1704 while (!Lst_IsEmpty (sources)) {
1705 gn = (GNode *)Lst_DeQueue(sources);
1706 ParseDoSrc(tOp, gn->name);
1707 }
1708 Lst_Destroy(sources, NULL);
1709 cp = line;
1710 } else {
1711 if (*cp) {
1712 *cp = '\0';
1713 cp += 1;
1714 }
1715
1716 ParseDoSrc(tOp, line);
1717 }
1718 while (*cp && isspace ((unsigned char)*cp)) {
1719 cp++;
1720 }
1721 line = cp;
1722 }
1723 }
1724
1725 if (mainNode == NULL) {
1726 /*
1727 * If we have yet to decide on a main target to make, in the
1728 * absence of any user input, we want the first target on
1729 * the first dependency line that is actually a real target
1730 * (i.e. isn't a .USE or .EXEC rule) to be made.
1731 */
1732 Lst_ForEach(targets, ParseFindMain, NULL);
1733 }
1734
1735 out:
1736 if (curTargs)
1737 Lst_Destroy(curTargs, NULL);
1738 }
1739
1740 /*-
1741 *---------------------------------------------------------------------
1742 * Parse_IsVar --
1743 * Return TRUE if the passed line is a variable assignment. A variable
1744 * assignment consists of a single word followed by optional whitespace
1745 * followed by either a += or an = operator.
1746 * This function is used both by the Parse_File function and main when
1747 * parsing the command-line arguments.
1748 *
1749 * Input:
1750 * line the line to check
1751 *
1752 * Results:
1753 * TRUE if it is. FALSE if it ain't
1754 *
1755 * Side Effects:
1756 * none
1757 *---------------------------------------------------------------------
1758 */
1759 Boolean
1760 Parse_IsVar(char *line)
1761 {
1762 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1763 char ch;
1764 int level = 0;
1765 #define ISEQOPERATOR(c) \
1766 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1767
1768 /*
1769 * Skip to variable name
1770 */
1771 for (;(*line == ' ') || (*line == '\t'); line++)
1772 continue;
1773
1774 /* Scan for one of the assignment operators outside a variable expansion */
1775 while ((ch = *line++) != 0) {
1776 if (ch == '(' || ch == '{') {
1777 level++;
1778 continue;
1779 }
1780 if (ch == ')' || ch == '}') {
1781 level--;
1782 continue;
1783 }
1784 if (level != 0)
1785 continue;
1786 while (ch == ' ' || ch == '\t') {
1787 ch = *line++;
1788 wasSpace = TRUE;
1789 }
1790 #ifdef SUNSHCMD
1791 if (ch == ':' && strncmp(line, "sh", 2) == 0) {
1792 line += 2;
1793 continue;
1794 }
1795 #endif
1796 if (ch == '=')
1797 return TRUE;
1798 if (*line == '=' && ISEQOPERATOR(ch))
1799 return TRUE;
1800 if (wasSpace)
1801 return FALSE;
1802 }
1803
1804 return FALSE;
1805 }
1806
1807 /*-
1808 *---------------------------------------------------------------------
1809 * Parse_DoVar --
1810 * Take the variable assignment in the passed line and do it in the
1811 * global context.
1812 *
1813 * Note: There is a lexical ambiguity with assignment modifier characters
1814 * in variable names. This routine interprets the character before the =
1815 * as a modifier. Therefore, an assignment like
1816 * C++=/usr/bin/CC
1817 * is interpreted as "C+ +=" instead of "C++ =".
1818 *
1819 * Input:
1820 * line a line guaranteed to be a variable assignment.
1821 * This reduces error checks
1822 * ctxt Context in which to do the assignment
1823 *
1824 * Results:
1825 * none
1826 *
1827 * Side Effects:
1828 * the variable structure of the given variable name is altered in the
1829 * global context.
1830 *---------------------------------------------------------------------
1831 */
1832 void
1833 Parse_DoVar(char *line, GNode *ctxt)
1834 {
1835 char *cp; /* pointer into line */
1836 enum {
1837 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1838 } type; /* Type of assignment */
1839 char *opc; /* ptr to operator character to
1840 * null-terminate the variable name */
1841 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1842 * i.e. if any variable expansion was
1843 * performed */
1844 int depth;
1845
1846 /*
1847 * Skip to variable name
1848 */
1849 while ((*line == ' ') || (*line == '\t')) {
1850 line++;
1851 }
1852
1853 /*
1854 * Skip to operator character, nulling out whitespace as we go
1855 * XXX Rather than counting () and {} we should look for $ and
1856 * then expand the variable.
1857 */
1858 for (depth = 0, cp = line + 1; depth > 0 || *cp != '='; cp++) {
1859 if (*cp == '(' || *cp == '{') {
1860 depth++;
1861 continue;
1862 }
1863 if (*cp == ')' || *cp == '}') {
1864 depth--;
1865 continue;
1866 }
1867 if (depth == 0 && isspace ((unsigned char)*cp)) {
1868 *cp = '\0';
1869 }
1870 }
1871 opc = cp-1; /* operator is the previous character */
1872 *cp++ = '\0'; /* nuke the = */
1873
1874 /*
1875 * Check operator type
1876 */
1877 switch (*opc) {
1878 case '+':
1879 type = VAR_APPEND;
1880 *opc = '\0';
1881 break;
1882
1883 case '?':
1884 /*
1885 * If the variable already has a value, we don't do anything.
1886 */
1887 *opc = '\0';
1888 if (Var_Exists(line, ctxt)) {
1889 return;
1890 } else {
1891 type = VAR_NORMAL;
1892 }
1893 break;
1894
1895 case ':':
1896 type = VAR_SUBST;
1897 *opc = '\0';
1898 break;
1899
1900 case '!':
1901 type = VAR_SHELL;
1902 *opc = '\0';
1903 break;
1904
1905 default:
1906 #ifdef SUNSHCMD
1907 while (opc > line && *opc != ':')
1908 opc--;
1909
1910 if (strncmp(opc, ":sh", 3) == 0) {
1911 type = VAR_SHELL;
1912 *opc = '\0';
1913 break;
1914 }
1915 #endif
1916 type = VAR_NORMAL;
1917 break;
1918 }
1919
1920 while (isspace ((unsigned char)*cp)) {
1921 cp++;
1922 }
1923
1924 if (type == VAR_APPEND) {
1925 Var_Append(line, cp, ctxt);
1926 } else if (type == VAR_SUBST) {
1927 /*
1928 * Allow variables in the old value to be undefined, but leave their
1929 * invocation alone -- this is done by forcing oldVars to be false.
1930 * XXX: This can cause recursive variables, but that's not hard to do,
1931 * and this allows someone to do something like
1932 *
1933 * CFLAGS = $(.INCLUDES)
1934 * CFLAGS := -I.. $(CFLAGS)
1935 *
1936 * And not get an error.
1937 */
1938 Boolean oldOldVars = oldVars;
1939
1940 oldVars = FALSE;
1941
1942 /*
1943 * make sure that we set the variable the first time to nothing
1944 * so that it gets substituted!
1945 */
1946 if (!Var_Exists(line, ctxt))
1947 Var_Set(line, "", ctxt, 0);
1948
1949 cp = Var_Subst(NULL, cp, ctxt, VARF_WANTRES|VARF_ASSIGN);
1950 oldVars = oldOldVars;
1951 freeCp = TRUE;
1952
1953 Var_Set(line, cp, ctxt, 0);
1954 } else if (type == VAR_SHELL) {
1955 char *res;
1956 const char *error;
1957
1958 if (strchr(cp, '$') != NULL) {
1959 /*
1960 * There's a dollar sign in the command, so perform variable
1961 * expansion on the whole thing. The resulting string will need
1962 * freeing when we're done, so set freeCmd to TRUE.
1963 */
1964 cp = Var_Subst(NULL, cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES);
1965 freeCp = TRUE;
1966 }
1967
1968 res = Cmd_Exec(cp, &error);
1969 Var_Set(line, res, ctxt, 0);
1970 free(res);
1971
1972 if (error)
1973 Parse_Error(PARSE_WARNING, error, cp);
1974 } else {
1975 /*
1976 * Normal assignment -- just do it.
1977 */
1978 Var_Set(line, cp, ctxt, 0);
1979 }
1980 if (strcmp(line, MAKEOVERRIDES) == 0)
1981 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1982 else if (strcmp(line, ".CURDIR") == 0) {
1983 /*
1984 * Somone is being (too?) clever...
1985 * Let's pretend they know what they are doing and
1986 * re-initialize the 'cur' Path.
1987 */
1988 Dir_InitCur(cp);
1989 Dir_SetPATH();
1990 } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1991 Job_SetPrefix();
1992 } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1993 Var_Export(cp, 0);
1994 }
1995 if (freeCp)
1996 free(cp);
1997 }
1998
1999
2000 /*
2001 * ParseMaybeSubMake --
2002 * Scan the command string to see if it a possible submake node
2003 * Input:
2004 * cmd the command to scan
2005 * Results:
2006 * TRUE if the command is possibly a submake, FALSE if not.
2007 */
2008 static Boolean
2009 ParseMaybeSubMake(const char *cmd)
2010 {
2011 size_t i;
2012 static struct {
2013 const char *name;
2014 size_t len;
2015 } vals[] = {
2016 #define MKV(A) { A, sizeof(A) - 1 }
2017 MKV("${MAKE}"),
2018 MKV("${.MAKE}"),
2019 MKV("$(MAKE)"),
2020 MKV("$(.MAKE)"),
2021 MKV("make"),
2022 };
2023 for (i = 0; i < sizeof(vals)/sizeof(vals[0]); i++) {
2024 char *ptr;
2025 if ((ptr = strstr(cmd, vals[i].name)) == NULL)
2026 continue;
2027 if ((ptr == cmd || !isalnum((unsigned char)ptr[-1]))
2028 && !isalnum((unsigned char)ptr[vals[i].len]))
2029 return TRUE;
2030 }
2031 return FALSE;
2032 }
2033
2034 /*-
2035 * ParseAddCmd --
2036 * Lst_ForEach function to add a command line to all targets
2037 *
2038 * Input:
2039 * gnp the node to which the command is to be added
2040 * cmd the command to add
2041 *
2042 * Results:
2043 * Always 0
2044 *
2045 * Side Effects:
2046 * A new element is added to the commands list of the node,
2047 * and the node can be marked as a submake node if the command is
2048 * determined to be that.
2049 */
2050 static int
2051 ParseAddCmd(void *gnp, void *cmd)
2052 {
2053 GNode *gn = (GNode *)gnp;
2054
2055 /* Add to last (ie current) cohort for :: targets */
2056 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
2057 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
2058
2059 /* if target already supplied, ignore commands */
2060 if (!(gn->type & OP_HAS_COMMANDS)) {
2061 (void)Lst_AtEnd(gn->commands, cmd);
2062 if (ParseMaybeSubMake(cmd))
2063 gn->type |= OP_SUBMAKE;
2064 ParseMark(gn);
2065 } else {
2066 #ifdef notyet
2067 /* XXX: We cannot do this until we fix the tree */
2068 (void)Lst_AtEnd(gn->commands, cmd);
2069 Parse_Error(PARSE_WARNING,
2070 "overriding commands for target \"%s\"; "
2071 "previous commands defined at %s: %d ignored",
2072 gn->name, gn->fname, gn->lineno);
2073 #else
2074 Parse_Error(PARSE_WARNING,
2075 "duplicate script for target \"%s\" ignored",
2076 gn->name);
2077 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
2078 "using previous script for \"%s\" defined here",
2079 gn->name);
2080 #endif
2081 }
2082 return(0);
2083 }
2084
2085 /*-
2086 *-----------------------------------------------------------------------
2087 * ParseHasCommands --
2088 * Callback procedure for Parse_File when destroying the list of
2089 * targets on the last dependency line. Marks a target as already
2090 * having commands if it does, to keep from having shell commands
2091 * on multiple dependency lines.
2092 *
2093 * Input:
2094 * gnp Node to examine
2095 *
2096 * Results:
2097 * None
2098 *
2099 * Side Effects:
2100 * OP_HAS_COMMANDS may be set for the target.
2101 *
2102 *-----------------------------------------------------------------------
2103 */
2104 static void
2105 ParseHasCommands(void *gnp)
2106 {
2107 GNode *gn = (GNode *)gnp;
2108 if (!Lst_IsEmpty(gn->commands)) {
2109 gn->type |= OP_HAS_COMMANDS;
2110 }
2111 }
2112
2113 /*-
2114 *-----------------------------------------------------------------------
2115 * Parse_AddIncludeDir --
2116 * Add a directory to the path searched for included makefiles
2117 * bracketed by double-quotes. Used by functions in main.c
2118 *
2119 * Input:
2120 * dir The name of the directory to add
2121 *
2122 * Results:
2123 * None.
2124 *
2125 * Side Effects:
2126 * The directory is appended to the list.
2127 *
2128 *-----------------------------------------------------------------------
2129 */
2130 void
2131 Parse_AddIncludeDir(char *dir)
2132 {
2133 (void)Dir_AddDir(parseIncPath, dir);
2134 }
2135
2136 /*-
2137 *---------------------------------------------------------------------
2138 * ParseDoInclude --
2139 * Push to another file.
2140 *
2141 * The input is the line minus the `.'. A file spec is a string
2142 * enclosed in <> or "". The former is looked for only in sysIncPath.
2143 * The latter in . and the directories specified by -I command line
2144 * options
2145 *
2146 * Results:
2147 * None
2148 *
2149 * Side Effects:
2150 * A structure is added to the includes Lst and readProc, lineno,
2151 * fname and curFILE are altered for the new file
2152 *---------------------------------------------------------------------
2153 */
2154
2155 static void
2156 Parse_include_file(char *file, Boolean isSystem, Boolean depinc, int silent)
2157 {
2158 struct loadedfile *lf;
2159 char *fullname; /* full pathname of file */
2160 char *newName;
2161 char *prefEnd, *incdir;
2162 int fd;
2163 int i;
2164
2165 /*
2166 * Now we know the file's name and its search path, we attempt to
2167 * find the durn thing. A return of NULL indicates the file don't
2168 * exist.
2169 */
2170 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2171
2172 if (fullname == NULL && !isSystem) {
2173 /*
2174 * Include files contained in double-quotes are first searched for
2175 * relative to the including file's location. We don't want to
2176 * cd there, of course, so we just tack on the old file's
2177 * leading path components and call Dir_FindFile to see if
2178 * we can locate the beast.
2179 */
2180
2181 incdir = bmake_strdup(curFile->fname);
2182 prefEnd = strrchr(incdir, '/');
2183 if (prefEnd != NULL) {
2184 *prefEnd = '\0';
2185 /* Now do lexical processing of leading "../" on the filename */
2186 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2187 prefEnd = strrchr(incdir + 1, '/');
2188 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
2189 break;
2190 *prefEnd = '\0';
2191 }
2192 newName = str_concat(incdir, file + i, STR_ADDSLASH);
2193 fullname = Dir_FindFile(newName, parseIncPath);
2194 if (fullname == NULL)
2195 fullname = Dir_FindFile(newName, dirSearchPath);
2196 free(newName);
2197 }
2198 free(incdir);
2199
2200 if (fullname == NULL) {
2201 /*
2202 * Makefile wasn't found in same directory as included makefile.
2203 * Search for it first on the -I search path,
2204 * then on the .PATH search path, if not found in a -I directory.
2205 * If we have a suffix specific path we should use that.
2206 */
2207 char *suff;
2208 Lst suffPath = NULL;
2209
2210 if ((suff = strrchr(file, '.'))) {
2211 suffPath = Suff_GetPath(suff);
2212 if (suffPath != NULL) {
2213 fullname = Dir_FindFile(file, suffPath);
2214 }
2215 }
2216 if (fullname == NULL) {
2217 fullname = Dir_FindFile(file, parseIncPath);
2218 if (fullname == NULL) {
2219 fullname = Dir_FindFile(file, dirSearchPath);
2220 }
2221 }
2222 }
2223 }
2224
2225 /* Looking for a system file or file still not found */
2226 if (fullname == NULL) {
2227 /*
2228 * Look for it on the system path
2229 */
2230 fullname = Dir_FindFile(file,
2231 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2232 }
2233
2234 if (fullname == NULL) {
2235 if (!silent)
2236 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2237 return;
2238 }
2239
2240 /* Actually open the file... */
2241 fd = open(fullname, O_RDONLY);
2242 if (fd == -1) {
2243 if (!silent)
2244 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2245 free(fullname);
2246 return;
2247 }
2248
2249 /* load it */
2250 lf = loadfile(fullname, fd);
2251
2252 ParseSetIncludedFile();
2253 /* Start reading from this file next */
2254 Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2255 curFile->lf = lf;
2256 if (depinc)
2257 doing_depend = depinc; /* only turn it on */
2258 }
2259
2260 static void
2261 ParseDoInclude(char *line)
2262 {
2263 char endc; /* the character which ends the file spec */
2264 char *cp; /* current position in file spec */
2265 int silent = (*line != 'i') ? 1 : 0;
2266 char *file = &line[7 + silent];
2267
2268 /* Skip to delimiter character so we know where to look */
2269 while (*file == ' ' || *file == '\t')
2270 file++;
2271
2272 if (*file != '"' && *file != '<') {
2273 Parse_Error(PARSE_FATAL,
2274 ".include filename must be delimited by '\"' or '<'");
2275 return;
2276 }
2277
2278 /*
2279 * Set the search path on which to find the include file based on the
2280 * characters which bracket its name. Angle-brackets imply it's
2281 * a system Makefile while double-quotes imply it's a user makefile
2282 */
2283 if (*file == '<') {
2284 endc = '>';
2285 } else {
2286 endc = '"';
2287 }
2288
2289 /* Skip to matching delimiter */
2290 for (cp = ++file; *cp && *cp != endc; cp++)
2291 continue;
2292
2293 if (*cp != endc) {
2294 Parse_Error(PARSE_FATAL,
2295 "Unclosed %cinclude filename. '%c' expected",
2296 '.', endc);
2297 return;
2298 }
2299 *cp = '\0';
2300
2301 /*
2302 * Substitute for any variables in the file name before trying to
2303 * find the thing.
2304 */
2305 file = Var_Subst(NULL, file, VAR_CMD, VARF_WANTRES);
2306
2307 Parse_include_file(file, endc == '>', (*line == 'd'), silent);
2308 free(file);
2309 }
2310
2311
2312 /*-
2313 *---------------------------------------------------------------------
2314 * ParseSetIncludedFile --
2315 * Set the .INCLUDEDFROMFILE variable to the contents of .PARSEFILE
2316 * and the .INCLUDEDFROMDIR variable to the contents of .PARSEDIR
2317 *
2318 * Results:
2319 * None
2320 *
2321 * Side Effects:
2322 * The .INCLUDEDFROMFILE variable is overwritten by the contents
2323 * of .PARSEFILE and the .INCLUDEDFROMDIR variable is overwriten
2324 * by the contents of .PARSEDIR
2325 *---------------------------------------------------------------------
2326 */
2327 static void
2328 ParseSetIncludedFile(void)
2329 {
2330 char *pf, *fp = NULL;
2331 char *pd, *dp = NULL;
2332
2333 pf = Var_Value(".PARSEFILE", VAR_GLOBAL, &fp);
2334 Var_Set(".INCLUDEDFROMFILE", pf, VAR_GLOBAL, 0);
2335 pd = Var_Value(".PARSEDIR", VAR_GLOBAL, &dp);
2336 Var_Set(".INCLUDEDFROMDIR", pd, VAR_GLOBAL, 0);
2337
2338 if (DEBUG(PARSE))
2339 fprintf(debug_file, "%s: ${.INCLUDEDFROMDIR} = `%s' "
2340 "${.INCLUDEDFROMFILE} = `%s'\n", __func__, pd, pf);
2341
2342 free(fp);
2343 free(dp);
2344 }
2345 /*-
2346 *---------------------------------------------------------------------
2347 * ParseSetParseFile --
2348 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2349 * basename of the given filename
2350 *
2351 * Results:
2352 * None
2353 *
2354 * Side Effects:
2355 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
2356 * dirname and basename of the given filename.
2357 *---------------------------------------------------------------------
2358 */
2359 static void
2360 ParseSetParseFile(const char *filename)
2361 {
2362 char *slash, *dirname;
2363 const char *pd, *pf;
2364 int len;
2365
2366 slash = strrchr(filename, '/');
2367 if (slash == NULL) {
2368 Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL, 0);
2369 Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL, 0);
2370 dirname= NULL;
2371 } else {
2372 len = slash - filename;
2373 dirname = bmake_malloc(len + 1);
2374 memcpy(dirname, filename, len);
2375 dirname[len] = '\0';
2376 Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL, 0);
2377 Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL, 0);
2378 }
2379 if (DEBUG(PARSE))
2380 fprintf(debug_file, "%s: ${.PARSEDIR} = `%s' ${.PARSEFILE} = `%s'\n",
2381 __func__, pd, pf);
2382 free(dirname);
2383 }
2384
2385 /*
2386 * Track the makefiles we read - so makefiles can
2387 * set dependencies on them.
2388 * Avoid adding anything more than once.
2389 */
2390
2391 static void
2392 ParseTrackInput(const char *name)
2393 {
2394 char *old;
2395 char *ep;
2396 char *fp = NULL;
2397 size_t name_len = strlen(name);
2398
2399 old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2400 if (old) {
2401 ep = old + strlen(old) - name_len;
2402 /* does it contain name? */
2403 for (; old != NULL; old = strchr(old, ' ')) {
2404 if (*old == ' ')
2405 old++;
2406 if (old >= ep)
2407 break; /* cannot contain name */
2408 if (memcmp(old, name, name_len) == 0
2409 && (old[name_len] == 0 || old[name_len] == ' '))
2410 goto cleanup;
2411 }
2412 }
2413 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2414 cleanup:
2415 if (fp) {
2416 free(fp);
2417 }
2418 }
2419
2420
2421 /*-
2422 *---------------------------------------------------------------------
2423 * Parse_setInput --
2424 * Start Parsing from the given source
2425 *
2426 * Results:
2427 * None
2428 *
2429 * Side Effects:
2430 * A structure is added to the includes Lst and readProc, lineno,
2431 * fname and curFile are altered for the new file
2432 *---------------------------------------------------------------------
2433 */
2434 void
2435 Parse_SetInput(const char *name, int line, int fd,
2436 char *(*nextbuf)(void *, size_t *), void *arg)
2437 {
2438 char *buf;
2439 size_t len;
2440
2441 if (name == NULL)
2442 name = curFile->fname;
2443 else
2444 ParseTrackInput(name);
2445
2446 if (DEBUG(PARSE))
2447 fprintf(debug_file, "%s: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2448 __func__, name, line, fd, nextbuf, arg);
2449
2450 if (fd == -1 && nextbuf == NULL)
2451 /* sanity */
2452 return;
2453
2454 if (curFile != NULL)
2455 /* Save exiting file info */
2456 Lst_AtFront(includes, curFile);
2457
2458 /* Allocate and fill in new structure */
2459 curFile = bmake_malloc(sizeof *curFile);
2460
2461 /*
2462 * Once the previous state has been saved, we can get down to reading
2463 * the new file. We set up the name of the file to be the absolute
2464 * name of the include file so error messages refer to the right
2465 * place.
2466 */
2467 curFile->fname = bmake_strdup(name);
2468 curFile->lineno = line;
2469 curFile->first_lineno = line;
2470 curFile->nextbuf = nextbuf;
2471 curFile->nextbuf_arg = arg;
2472 curFile->lf = NULL;
2473 curFile->depending = doing_depend; /* restore this on EOF */
2474
2475 assert(nextbuf != NULL);
2476
2477 /* Get first block of input data */
2478 buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2479 if (buf == NULL) {
2480 /* Was all a waste of time ... */
2481 if (curFile->fname)
2482 free(curFile->fname);
2483 free(curFile);
2484 return;
2485 }
2486 curFile->P_str = buf;
2487 curFile->P_ptr = buf;
2488 curFile->P_end = buf+len;
2489
2490 curFile->cond_depth = Cond_save_depth();
2491 ParseSetParseFile(name);
2492 }
2493
2494 #ifdef SYSVINCLUDE
2495 /*-
2496 *---------------------------------------------------------------------
2497 * ParseTraditionalInclude --
2498 * Push to another file.
2499 *
2500 * The input is the current line. The file name(s) are
2501 * following the "include".
2502 *
2503 * Results:
2504 * None
2505 *
2506 * Side Effects:
2507 * A structure is added to the includes Lst and readProc, lineno,
2508 * fname and curFILE are altered for the new file
2509 *---------------------------------------------------------------------
2510 */
2511 static void
2512 ParseTraditionalInclude(char *line)
2513 {
2514 char *cp; /* current position in file spec */
2515 int done = 0;
2516 int silent = (line[0] != 'i') ? 1 : 0;
2517 char *file = &line[silent + 7];
2518 char *all_files;
2519
2520 if (DEBUG(PARSE)) {
2521 fprintf(debug_file, "%s: %s\n", __func__, file);
2522 }
2523
2524 /*
2525 * Skip over whitespace
2526 */
2527 while (isspace((unsigned char)*file))
2528 file++;
2529
2530 /*
2531 * Substitute for any variables in the file name before trying to
2532 * find the thing.
2533 */
2534 all_files = Var_Subst(NULL, file, VAR_CMD, VARF_WANTRES);
2535
2536 if (*file == '\0') {
2537 Parse_Error(PARSE_FATAL,
2538 "Filename missing from \"include\"");
2539 return;
2540 }
2541
2542 for (file = all_files; !done; file = cp + 1) {
2543 /* Skip to end of line or next whitespace */
2544 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2545 continue;
2546
2547 if (*cp)
2548 *cp = '\0';
2549 else
2550 done = 1;
2551
2552 Parse_include_file(file, FALSE, FALSE, silent);
2553 }
2554 free(all_files);
2555 }
2556 #endif
2557
2558 #ifdef GMAKEEXPORT
2559 /*-
2560 *---------------------------------------------------------------------
2561 * ParseGmakeExport --
2562 * Parse export <variable>=<value>
2563 *
2564 * And set the environment with it.
2565 *
2566 * Results:
2567 * None
2568 *
2569 * Side Effects:
2570 * None
2571 *---------------------------------------------------------------------
2572 */
2573 static void
2574 ParseGmakeExport(char *line)
2575 {
2576 char *variable = &line[6];
2577 char *value;
2578
2579 if (DEBUG(PARSE)) {
2580 fprintf(debug_file, "%s: %s\n", __func__, variable);
2581 }
2582
2583 /*
2584 * Skip over whitespace
2585 */
2586 while (isspace((unsigned char)*variable))
2587 variable++;
2588
2589 for (value = variable; *value && *value != '='; value++)
2590 continue;
2591
2592 if (*value != '=') {
2593 Parse_Error(PARSE_FATAL,
2594 "Variable/Value missing from \"export\"");
2595 return;
2596 }
2597 *value++ = '\0'; /* terminate variable */
2598
2599 /*
2600 * Expand the value before putting it in the environment.
2601 */
2602 value = Var_Subst(NULL, value, VAR_CMD, VARF_WANTRES);
2603 setenv(variable, value, 1);
2604 }
2605 #endif
2606
2607 /*-
2608 *---------------------------------------------------------------------
2609 * ParseEOF --
2610 * Called when EOF is reached in the current file. If we were reading
2611 * an include file, the includes stack is popped and things set up
2612 * to go back to reading the previous file at the previous location.
2613 *
2614 * Results:
2615 * CONTINUE if there's more to do. DONE if not.
2616 *
2617 * Side Effects:
2618 * The old curFILE, is closed. The includes list is shortened.
2619 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2620 *---------------------------------------------------------------------
2621 */
2622 static int
2623 ParseEOF(void)
2624 {
2625 char *ptr;
2626 size_t len;
2627
2628 assert(curFile->nextbuf != NULL);
2629
2630 doing_depend = curFile->depending; /* restore this */
2631 /* get next input buffer, if any */
2632 ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2633 curFile->P_ptr = ptr;
2634 curFile->P_str = ptr;
2635 curFile->P_end = ptr + len;
2636 curFile->lineno = curFile->first_lineno;
2637 if (ptr != NULL) {
2638 /* Iterate again */
2639 return CONTINUE;
2640 }
2641
2642 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2643 Cond_restore_depth(curFile->cond_depth);
2644
2645 if (curFile->lf != NULL) {
2646 loadedfile_destroy(curFile->lf);
2647 curFile->lf = NULL;
2648 }
2649
2650 /* Dispose of curFile info */
2651 /* Leak curFile->fname because all the gnodes have pointers to it */
2652 free(curFile->P_str);
2653 free(curFile);
2654
2655 curFile = Lst_DeQueue(includes);
2656
2657 if (curFile == NULL) {
2658 /* We've run out of input */
2659 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2660 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2661 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2662 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2663 return DONE;
2664 }
2665
2666 if (DEBUG(PARSE))
2667 fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2668 curFile->fname, curFile->lineno);
2669
2670 /* Restore the PARSEDIR/PARSEFILE variables */
2671 ParseSetParseFile(curFile->fname);
2672 return (CONTINUE);
2673 }
2674
2675 #define PARSE_RAW 1
2676 #define PARSE_SKIP 2
2677
2678 static char *
2679 ParseGetLine(int flags, int *length)
2680 {
2681 IFile *cf = curFile;
2682 char *ptr;
2683 char ch;
2684 char *line;
2685 char *line_end;
2686 char *escaped;
2687 char *comment;
2688 char *tp;
2689
2690 /* Loop through blank lines and comment lines */
2691 for (;;) {
2692 cf->lineno++;
2693 line = cf->P_ptr;
2694 ptr = line;
2695 line_end = line;
2696 escaped = NULL;
2697 comment = NULL;
2698 for (;;) {
2699 if (cf->P_end != NULL && ptr == cf->P_end) {
2700 /* end of buffer */
2701 ch = 0;
2702 break;
2703 }
2704 ch = *ptr;
2705 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2706 if (cf->P_end == NULL)
2707 /* End of string (aka for loop) data */
2708 break;
2709 /* see if there is more we can parse */
2710 while (ptr++ < cf->P_end) {
2711 if ((ch = *ptr) == '\n') {
2712 if (ptr > line && ptr[-1] == '\\')
2713 continue;
2714 Parse_Error(PARSE_WARNING,
2715 "Zero byte read from file, skipping rest of line.");
2716 break;
2717 }
2718 }
2719 if (cf->nextbuf != NULL) {
2720 /*
2721 * End of this buffer; return EOF and outer logic
2722 * will get the next one. (eww)
2723 */
2724 break;
2725 }
2726 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2727 return NULL;
2728 }
2729
2730 if (ch == '\\') {
2731 /* Don't treat next character as special, remember first one */
2732 if (escaped == NULL)
2733 escaped = ptr;
2734 if (ptr[1] == '\n')
2735 cf->lineno++;
2736 ptr += 2;
2737 line_end = ptr;
2738 continue;
2739 }
2740 if (ch == '#' && comment == NULL) {
2741 /* Remember first '#' for comment stripping */
2742 /* Unless previous char was '[', as in modifier :[#] */
2743 if (!(ptr > line && ptr[-1] == '['))
2744 comment = line_end;
2745 }
2746 ptr++;
2747 if (ch == '\n')
2748 break;
2749 if (!isspace((unsigned char)ch))
2750 /* We are not interested in trailing whitespace */
2751 line_end = ptr;
2752 }
2753
2754 /* Save next 'to be processed' location */
2755 cf->P_ptr = ptr;
2756
2757 /* Check we have a non-comment, non-blank line */
2758 if (line_end == line || comment == line) {
2759 if (ch == 0)
2760 /* At end of file */
2761 return NULL;
2762 /* Parse another line */
2763 continue;
2764 }
2765
2766 /* We now have a line of data */
2767 *line_end = 0;
2768
2769 if (flags & PARSE_RAW) {
2770 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2771 *length = line_end - line;
2772 return line;
2773 }
2774
2775 if (flags & PARSE_SKIP) {
2776 /* Completely ignore non-directives */
2777 if (line[0] != '.')
2778 continue;
2779 /* We could do more of the .else/.elif/.endif checks here */
2780 }
2781 break;
2782 }
2783
2784 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2785 if (comment != NULL && line[0] != '\t') {
2786 line_end = comment;
2787 *line_end = 0;
2788 }
2789
2790 /* If we didn't see a '\\' then the in-situ data is fine */
2791 if (escaped == NULL) {
2792 *length = line_end - line;
2793 return line;
2794 }
2795
2796 /* Remove escapes from '\n' and '#' */
2797 tp = ptr = escaped;
2798 escaped = line;
2799 for (; ; *tp++ = ch) {
2800 ch = *ptr++;
2801 if (ch != '\\') {
2802 if (ch == 0)
2803 break;
2804 continue;
2805 }
2806
2807 ch = *ptr++;
2808 if (ch == 0) {
2809 /* Delete '\\' at end of buffer */
2810 tp--;
2811 break;
2812 }
2813
2814 if (ch == '#' && line[0] != '\t')
2815 /* Delete '\\' from before '#' on non-command lines */
2816 continue;
2817
2818 if (ch != '\n') {
2819 /* Leave '\\' in buffer for later */
2820 *tp++ = '\\';
2821 /* Make sure we don't delete an escaped ' ' from the line end */
2822 escaped = tp + 1;
2823 continue;
2824 }
2825
2826 /* Escaped '\n' replace following whitespace with a single ' ' */
2827 while (ptr[0] == ' ' || ptr[0] == '\t')
2828 ptr++;
2829 ch = ' ';
2830 }
2831
2832 /* Delete any trailing spaces - eg from empty continuations */
2833 while (tp > escaped && isspace((unsigned char)tp[-1]))
2834 tp--;
2835
2836 *tp = 0;
2837 *length = tp - line;
2838 return line;
2839 }
2840
2841 /*-
2842 *---------------------------------------------------------------------
2843 * ParseReadLine --
2844 * Read an entire line from the input file. Called only by Parse_File.
2845 *
2846 * Results:
2847 * A line w/o its newline
2848 *
2849 * Side Effects:
2850 * Only those associated with reading a character
2851 *---------------------------------------------------------------------
2852 */
2853 static char *
2854 ParseReadLine(void)
2855 {
2856 char *line; /* Result */
2857 int lineLength; /* Length of result */
2858 int lineno; /* Saved line # */
2859 int rval;
2860
2861 for (;;) {
2862 line = ParseGetLine(0, &lineLength);
2863 if (line == NULL)
2864 return NULL;
2865
2866 if (line[0] != '.')
2867 return line;
2868
2869 /*
2870 * The line might be a conditional. Ask the conditional module
2871 * about it and act accordingly
2872 */
2873 switch (Cond_Eval(line)) {
2874 case COND_SKIP:
2875 /* Skip to next conditional that evaluates to COND_PARSE. */
2876 do {
2877 line = ParseGetLine(PARSE_SKIP, &lineLength);
2878 } while (line && Cond_Eval(line) != COND_PARSE);
2879 if (line == NULL)
2880 break;
2881 continue;
2882 case COND_PARSE:
2883 continue;
2884 case COND_INVALID: /* Not a conditional line */
2885 /* Check for .for loops */
2886 rval = For_Eval(line);
2887 if (rval == 0)
2888 /* Not a .for line */
2889 break;
2890 if (rval < 0)
2891 /* Syntax error - error printed, ignore line */
2892 continue;
2893 /* Start of a .for loop */
2894 lineno = curFile->lineno;
2895 /* Accumulate loop lines until matching .endfor */
2896 do {
2897 line = ParseGetLine(PARSE_RAW, &lineLength);
2898 if (line == NULL) {
2899 Parse_Error(PARSE_FATAL,
2900 "Unexpected end of file in for loop.");
2901 break;
2902 }
2903 } while (For_Accum(line));
2904 /* Stash each iteration as a new 'input file' */
2905 For_Run(lineno);
2906 /* Read next line from for-loop buffer */
2907 continue;
2908 }
2909 return (line);
2910 }
2911 }
2912
2913 /*-
2914 *-----------------------------------------------------------------------
2915 * ParseFinishLine --
2916 * Handle the end of a dependency group.
2917 *
2918 * Results:
2919 * Nothing.
2920 *
2921 * Side Effects:
2922 * inLine set FALSE. 'targets' list destroyed.
2923 *
2924 *-----------------------------------------------------------------------
2925 */
2926 static void
2927 ParseFinishLine(void)
2928 {
2929 if (inLine) {
2930 Lst_ForEach(targets, Suff_EndTransform, NULL);
2931 Lst_Destroy(targets, ParseHasCommands);
2932 targets = NULL;
2933 inLine = FALSE;
2934 }
2935 }
2936
2937
2938 /*-
2939 *---------------------------------------------------------------------
2940 * Parse_File --
2941 * Parse a file into its component parts, incorporating it into the
2942 * current dependency graph. This is the main function and controls
2943 * almost every other function in this module
2944 *
2945 * Input:
2946 * name the name of the file being read
2947 * fd Open file to makefile to parse
2948 *
2949 * Results:
2950 * None
2951 *
2952 * Side Effects:
2953 * closes fd.
2954 * Loads. Nodes are added to the list of all targets, nodes and links
2955 * are added to the dependency graph. etc. etc. etc.
2956 *---------------------------------------------------------------------
2957 */
2958 void
2959 Parse_File(const char *name, int fd)
2960 {
2961 char *cp; /* pointer into the line */
2962 char *line; /* the line we're working on */
2963 struct loadedfile *lf;
2964
2965 lf = loadfile(name, fd);
2966
2967 inLine = FALSE;
2968 fatals = 0;
2969
2970 if (name == NULL) {
2971 name = "(stdin)";
2972 }
2973
2974 Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
2975 curFile->lf = lf;
2976
2977 do {
2978 for (; (line = ParseReadLine()) != NULL; ) {
2979 if (DEBUG(PARSE))
2980 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2981 curFile->lineno, line);
2982 if (*line == '.') {
2983 /*
2984 * Lines that begin with the special character may be
2985 * include or undef directives.
2986 * On the other hand they can be suffix rules (.c.o: ...)
2987 * or just dependencies for filenames that start '.'.
2988 */
2989 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2990 continue;
2991 }
2992 if (strncmp(cp, "include", 7) == 0 ||
2993 ((cp[0] == 'd' || cp[0] == 's' || cp[0] == '-') &&
2994 strncmp(&cp[1], "include", 7) == 0)) {
2995 ParseDoInclude(cp);
2996 continue;
2997 }
2998 if (strncmp(cp, "undef", 5) == 0) {
2999 char *cp2;
3000 for (cp += 5; isspace((unsigned char) *cp); cp++)
3001 continue;
3002 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
3003 (*cp2 != '\0'); cp2++)
3004 continue;
3005 *cp2 = '\0';
3006 Var_Delete(cp, VAR_GLOBAL);
3007 continue;
3008 } else if (strncmp(cp, "export", 6) == 0) {
3009 for (cp += 6; isspace((unsigned char) *cp); cp++)
3010 continue;
3011 Var_Export(cp, 1);
3012 continue;
3013 } else if (strncmp(cp, "unexport", 8) == 0) {
3014 Var_UnExport(cp);
3015 continue;
3016 } else if (strncmp(cp, "info", 4) == 0 ||
3017 strncmp(cp, "error", 5) == 0 ||
3018 strncmp(cp, "warning", 7) == 0) {
3019 if (ParseMessage(cp))
3020 continue;
3021 }
3022 }
3023
3024 if (*line == '\t') {
3025 /*
3026 * If a line starts with a tab, it can only hope to be
3027 * a creation command.
3028 */
3029 cp = line + 1;
3030 shellCommand:
3031 for (; isspace ((unsigned char)*cp); cp++) {
3032 continue;
3033 }
3034 if (*cp) {
3035 if (!inLine)
3036 Parse_Error(PARSE_FATAL,
3037 "Unassociated shell command \"%s\"",
3038 cp);
3039 /*
3040 * So long as it's not a blank line and we're actually
3041 * in a dependency spec, add the command to the list of
3042 * commands of all targets in the dependency spec
3043 */
3044 if (targets) {
3045 cp = bmake_strdup(cp);
3046 Lst_ForEach(targets, ParseAddCmd, cp);
3047 #ifdef CLEANUP
3048 Lst_AtEnd(targCmds, cp);
3049 #endif
3050 }
3051 }
3052 continue;
3053 }
3054
3055 #ifdef SYSVINCLUDE
3056 if (((strncmp(line, "include", 7) == 0 &&
3057 isspace((unsigned char) line[7])) ||
3058 ((line[0] == 's' || line[0] == '-') &&
3059 strncmp(&line[1], "include", 7) == 0 &&
3060 isspace((unsigned char) line[8]))) &&
3061 strchr(line, ':') == NULL) {
3062 /*
3063 * It's an S3/S5-style "include".
3064 */
3065 ParseTraditionalInclude(line);
3066 continue;
3067 }
3068 #endif
3069 #ifdef GMAKEEXPORT
3070 if (strncmp(line, "export", 6) == 0 &&
3071 isspace((unsigned char) line[6]) &&
3072 strchr(line, ':') == NULL) {
3073 /*
3074 * It's a Gmake "export".
3075 */
3076 ParseGmakeExport(line);
3077 continue;
3078 }
3079 #endif
3080 if (Parse_IsVar(line)) {
3081 ParseFinishLine();
3082 Parse_DoVar(line, VAR_GLOBAL);
3083 continue;
3084 }
3085
3086 #ifndef POSIX
3087 /*
3088 * To make life easier on novices, if the line is indented we
3089 * first make sure the line has a dependency operator in it.
3090 * If it doesn't have an operator and we're in a dependency
3091 * line's script, we assume it's actually a shell command
3092 * and add it to the current list of targets.
3093 */
3094 cp = line;
3095 if (isspace((unsigned char) line[0])) {
3096 while ((*cp != '\0') && isspace((unsigned char) *cp))
3097 cp++;
3098 while (*cp && (ParseIsEscaped(line, cp) ||
3099 (*cp != ':') && (*cp != '!'))) {
3100 cp++;
3101 }
3102 if (*cp == '\0') {
3103 if (inLine) {
3104 Parse_Error(PARSE_WARNING,
3105 "Shell command needs a leading tab");
3106 goto shellCommand;
3107 }
3108 }
3109 }
3110 #endif
3111 ParseFinishLine();
3112
3113 /*
3114 * For some reason - probably to make the parser impossible -
3115 * a ';' can be used to separate commands from dependencies.
3116 * Attempt to avoid ';' inside substitution patterns.
3117 */
3118 {
3119 int level = 0;
3120
3121 for (cp = line; *cp != 0; cp++) {
3122 if (*cp == '\\' && cp[1] != 0) {
3123 cp++;
3124 continue;
3125 }
3126 if (*cp == '$' &&
3127 (cp[1] == '(' || cp[1] == '{')) {
3128 level++;
3129 continue;
3130 }
3131 if (level > 0) {
3132 if (*cp == ')' || *cp == '}') {
3133 level--;
3134 continue;
3135 }
3136 } else if (*cp == ';') {
3137 break;
3138 }
3139 }
3140 }
3141 if (*cp != 0)
3142 /* Terminate the dependency list at the ';' */
3143 *cp++ = 0;
3144 else
3145 cp = NULL;
3146
3147 /*
3148 * We now know it's a dependency line so it needs to have all
3149 * variables expanded before being parsed. Tell the variable
3150 * module to complain if some variable is undefined...
3151 */
3152 line = Var_Subst(NULL, line, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES);
3153
3154 /*
3155 * Need a non-circular list for the target nodes
3156 */
3157 if (targets)
3158 Lst_Destroy(targets, NULL);
3159
3160 targets = Lst_Init(FALSE);
3161 inLine = TRUE;
3162
3163 ParseDoDependency(line);
3164 free(line);
3165
3166 /* If there were commands after a ';', add them now */
3167 if (cp != NULL) {
3168 goto shellCommand;
3169 }
3170 }
3171 /*
3172 * Reached EOF, but it may be just EOF of an include file...
3173 */
3174 } while (ParseEOF() == CONTINUE);
3175
3176 if (fatals) {
3177 (void)fflush(stdout);
3178 (void)fprintf(stderr,
3179 "%s: Fatal errors encountered -- cannot continue",
3180 progname);
3181 PrintOnError(NULL, NULL);
3182 exit(1);
3183 }
3184 }
3185
3186 /*-
3187 *---------------------------------------------------------------------
3188 * Parse_Init --
3189 * initialize the parsing module
3190 *
3191 * Results:
3192 * none
3193 *
3194 * Side Effects:
3195 * the parseIncPath list is initialized...
3196 *---------------------------------------------------------------------
3197 */
3198 void
3199 Parse_Init(void)
3200 {
3201 mainNode = NULL;
3202 parseIncPath = Lst_Init(FALSE);
3203 sysIncPath = Lst_Init(FALSE);
3204 defIncPath = Lst_Init(FALSE);
3205 includes = Lst_Init(FALSE);
3206 #ifdef CLEANUP
3207 targCmds = Lst_Init(FALSE);
3208 #endif
3209 }
3210
3211 void
3212 Parse_End(void)
3213 {
3214 #ifdef CLEANUP
3215 Lst_Destroy(targCmds, (FreeProc *)free);
3216 if (targets)
3217 Lst_Destroy(targets, NULL);
3218 Lst_Destroy(defIncPath, Dir_Destroy);
3219 Lst_Destroy(sysIncPath, Dir_Destroy);
3220 Lst_Destroy(parseIncPath, Dir_Destroy);
3221 Lst_Destroy(includes, NULL); /* Should be empty now */
3222 #endif
3223 }
3224
3225
3226 /*-
3227 *-----------------------------------------------------------------------
3228 * Parse_MainName --
3229 * Return a Lst of the main target to create for main()'s sake. If
3230 * no such target exists, we Punt with an obnoxious error message.
3231 *
3232 * Results:
3233 * A Lst of the single node to create.
3234 *
3235 * Side Effects:
3236 * None.
3237 *
3238 *-----------------------------------------------------------------------
3239 */
3240 Lst
3241 Parse_MainName(void)
3242 {
3243 Lst mainList; /* result list */
3244
3245 mainList = Lst_Init(FALSE);
3246
3247 if (mainNode == NULL) {
3248 Punt("no target to make.");
3249 /*NOTREACHED*/
3250 } else if (mainNode->type & OP_DOUBLEDEP) {
3251 (void)Lst_AtEnd(mainList, mainNode);
3252 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3253 }
3254 else
3255 (void)Lst_AtEnd(mainList, mainNode);
3256 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3257 return (mainList);
3258 }
3259
3260 /*-
3261 *-----------------------------------------------------------------------
3262 * ParseMark --
3263 * Add the filename and lineno to the GNode so that we remember
3264 * where it was first defined.
3265 *
3266 * Side Effects:
3267 * None.
3268 *
3269 *-----------------------------------------------------------------------
3270 */
3271 static void
3272 ParseMark(GNode *gn)
3273 {
3274 gn->fname = curFile->fname;
3275 gn->lineno = curFile->lineno;
3276 }
3277