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