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