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