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