parse.c revision 1.244 1 /* $NetBSD: parse.c,v 1.244 2020/08/01 09:25:36 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.244 2020/08/01 09:25:36 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.244 2020/08/01 09:25:36 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 free(cp2);
703 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 while (isspace((unsigned char)*dirstart))
1295 dirstart++;
1296 const char *dirend = dirstart;
1297 while (isalnum((unsigned char)*dirend) || *dirend == '-')
1298 dirend++;
1299 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
1300 (int)(dirend - dirstart), dirstart);
1301 } else
1302 Parse_Error(PARSE_FATAL, "Need an operator");
1303 goto out;
1304 }
1305
1306 /* Insert a null terminator. */
1307 savec = *cp;
1308 *cp = '\0';
1309
1310 /*
1311 * Got the word. See if it's a special target and if so set
1312 * specType to match it.
1313 */
1314 if (*line == '.' && isupper ((unsigned char)line[1])) {
1315 /*
1316 * See if the target is a special target that must have it
1317 * or its sources handled specially.
1318 */
1319 int keywd = ParseFindKeyword(line);
1320 if (keywd != -1) {
1321 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1322 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1323 goto out;
1324 }
1325
1326 specType = parseKeywords[keywd].spec;
1327 tOp = parseKeywords[keywd].op;
1328
1329 /*
1330 * Certain special targets have special semantics:
1331 * .PATH Have to set the dirSearchPath
1332 * variable too
1333 * .MAIN Its sources are only used if
1334 * nothing has been specified to
1335 * create.
1336 * .DEFAULT Need to create a node to hang
1337 * commands on, but we don't want
1338 * it in the graph, nor do we want
1339 * it to be the Main Target, so we
1340 * create it, set OP_NOTMAIN and
1341 * add it to the list, setting
1342 * DEFAULT to the new node for
1343 * later use. We claim the node is
1344 * A transformation rule to make
1345 * life easier later, when we'll
1346 * use Make_HandleUse to actually
1347 * apply the .DEFAULT commands.
1348 * .PHONY The list of targets
1349 * .NOPATH Don't search for file in the path
1350 * .STALE
1351 * .BEGIN
1352 * .END
1353 * .ERROR
1354 * .DELETE_ON_ERROR
1355 * .INTERRUPT Are not to be considered the
1356 * main target.
1357 * .NOTPARALLEL Make only one target at a time.
1358 * .SINGLESHELL Create a shell for each command.
1359 * .ORDER Must set initial predecessor to NULL
1360 */
1361 switch (specType) {
1362 case ExPath:
1363 if (paths == NULL) {
1364 paths = Lst_Init(FALSE);
1365 }
1366 (void)Lst_AtEnd(paths, dirSearchPath);
1367 break;
1368 case Main:
1369 if (!Lst_IsEmpty(create)) {
1370 specType = Not;
1371 }
1372 break;
1373 case Begin:
1374 case End:
1375 case Stale:
1376 case dotError:
1377 case Interrupt:
1378 gn = Targ_FindNode(line, TARG_CREATE);
1379 if (doing_depend)
1380 ParseMark(gn);
1381 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1382 (void)Lst_AtEnd(targets, gn);
1383 break;
1384 case Default:
1385 gn = Targ_NewGN(".DEFAULT");
1386 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1387 (void)Lst_AtEnd(targets, gn);
1388 DEFAULT = gn;
1389 break;
1390 case DeleteOnError:
1391 deleteOnError = TRUE;
1392 break;
1393 case NotParallel:
1394 maxJobs = 1;
1395 break;
1396 case SingleShell:
1397 compatMake = TRUE;
1398 break;
1399 case Order:
1400 predecessor = NULL;
1401 break;
1402 default:
1403 break;
1404 }
1405 } else if (strncmp(line, ".PATH", 5) == 0) {
1406 /*
1407 * .PATH<suffix> has to be handled specially.
1408 * Call on the suffix module to give us a path to
1409 * modify.
1410 */
1411 Lst path;
1412
1413 specType = ExPath;
1414 path = Suff_GetPath(&line[5]);
1415 if (path == NULL) {
1416 Parse_Error(PARSE_FATAL,
1417 "Suffix '%s' not defined (yet)",
1418 &line[5]);
1419 goto out;
1420 } else {
1421 if (paths == NULL) {
1422 paths = Lst_Init(FALSE);
1423 }
1424 (void)Lst_AtEnd(paths, path);
1425 }
1426 }
1427 }
1428
1429 /*
1430 * Have word in line. Get or create its node and stick it at
1431 * the end of the targets list
1432 */
1433 if (specType == Not && *line != '\0') {
1434 if (Dir_HasWildcards(line)) {
1435 /*
1436 * Targets are to be sought only in the current directory,
1437 * so create an empty path for the thing. Note we need to
1438 * use Dir_Destroy in the destruction of the path as the
1439 * Dir module could have added a directory to the path...
1440 */
1441 Lst emptyPath = Lst_Init(FALSE);
1442
1443 Dir_Expand(line, emptyPath, curTargs);
1444
1445 Lst_Destroy(emptyPath, Dir_Destroy);
1446 } else {
1447 /*
1448 * No wildcards, but we want to avoid code duplication,
1449 * so create a list with the word on it.
1450 */
1451 (void)Lst_AtEnd(curTargs, line);
1452 }
1453
1454 /* Apply the targets. */
1455
1456 while(!Lst_IsEmpty(curTargs)) {
1457 char *targName = (char *)Lst_DeQueue(curTargs);
1458
1459 if (!Suff_IsTransform (targName)) {
1460 gn = Targ_FindNode(targName, TARG_CREATE);
1461 } else {
1462 gn = Suff_AddTransform(targName);
1463 }
1464 if (doing_depend)
1465 ParseMark(gn);
1466
1467 (void)Lst_AtEnd(targets, gn);
1468 }
1469 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1470 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1471 }
1472
1473 /* Don't need the inserted null terminator any more. */
1474 *cp = savec;
1475
1476 /*
1477 * If it is a special type and not .PATH, it's the only target we
1478 * allow on this line...
1479 */
1480 if (specType != Not && specType != ExPath) {
1481 Boolean warning = FALSE;
1482
1483 while (*cp && (ParseIsEscaped(lstart, cp) ||
1484 (*cp != '!' && *cp != ':'))) {
1485 if (ParseIsEscaped(lstart, cp) ||
1486 (*cp != ' ' && *cp != '\t')) {
1487 warning = TRUE;
1488 }
1489 cp++;
1490 }
1491 if (warning) {
1492 Parse_Error(PARSE_WARNING, "Extra target ignored");
1493 }
1494 } else {
1495 while (*cp && isspace ((unsigned char)*cp)) {
1496 cp++;
1497 }
1498 }
1499 line = cp;
1500 } while (*line && (ParseIsEscaped(lstart, line) ||
1501 (*line != '!' && *line != ':')));
1502
1503 /*
1504 * Don't need the list of target names anymore...
1505 */
1506 Lst_Destroy(curTargs, NULL);
1507 curTargs = NULL;
1508
1509 if (!Lst_IsEmpty(targets)) {
1510 switch(specType) {
1511 default:
1512 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1513 break;
1514 case Default:
1515 case Stale:
1516 case Begin:
1517 case End:
1518 case dotError:
1519 case Interrupt:
1520 /*
1521 * These four create nodes on which to hang commands, so
1522 * targets shouldn't be empty...
1523 */
1524 case Not:
1525 /*
1526 * Nothing special here -- targets can be empty if it wants.
1527 */
1528 break;
1529 }
1530 }
1531
1532 /*
1533 * Have now parsed all the target names. Must parse the operator next. The
1534 * result is left in op .
1535 */
1536 if (*cp == '!') {
1537 op = OP_FORCE;
1538 } else if (*cp == ':') {
1539 if (cp[1] == ':') {
1540 op = OP_DOUBLEDEP;
1541 cp++;
1542 } else {
1543 op = OP_DEPENDS;
1544 }
1545 } else {
1546 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1547 : "Missing dependency operator");
1548 goto out;
1549 }
1550
1551 /* Advance beyond the operator */
1552 cp++;
1553
1554 /*
1555 * Apply the operator to the target. This is how we remember which
1556 * operator a target was defined with. It fails if the operator
1557 * used isn't consistent across all references.
1558 */
1559 Lst_ForEach(targets, ParseDoOp, &op);
1560
1561 /*
1562 * Onward to the sources.
1563 *
1564 * LINE will now point to the first source word, if any, or the
1565 * end of the string if not.
1566 */
1567 while (*cp && isspace ((unsigned char)*cp)) {
1568 cp++;
1569 }
1570 line = cp;
1571
1572 /*
1573 * Several special targets take different actions if present with no
1574 * sources:
1575 * a .SUFFIXES line with no sources clears out all old suffixes
1576 * a .PRECIOUS line makes all targets precious
1577 * a .IGNORE line ignores errors for all targets
1578 * a .SILENT line creates silence when making all targets
1579 * a .PATH removes all directories from the search path(s).
1580 */
1581 if (!*line) {
1582 switch (specType) {
1583 case Suffixes:
1584 Suff_ClearSuffixes();
1585 break;
1586 case Precious:
1587 allPrecious = TRUE;
1588 break;
1589 case Ignore:
1590 ignoreErrors = TRUE;
1591 break;
1592 case Silent:
1593 beSilent = TRUE;
1594 break;
1595 case ExPath:
1596 Lst_ForEach(paths, ParseClearPath, NULL);
1597 Dir_SetPATH();
1598 break;
1599 #ifdef POSIX
1600 case Posix:
1601 Var_Set("%POSIX", "1003.2", VAR_GLOBAL);
1602 break;
1603 #endif
1604 default:
1605 break;
1606 }
1607 } else if (specType == MFlags) {
1608 /*
1609 * Call on functions in main.c to deal with these arguments and
1610 * set the initial character to a null-character so the loop to
1611 * get sources won't get anything
1612 */
1613 Main_ParseArgLine(line);
1614 *line = '\0';
1615 } else if (specType == ExShell) {
1616 if (Job_ParseShell(line) != SUCCESS) {
1617 Parse_Error(PARSE_FATAL, "improper shell specification");
1618 goto out;
1619 }
1620 *line = '\0';
1621 } else if (specType == NotParallel || specType == SingleShell ||
1622 specType == DeleteOnError) {
1623 *line = '\0';
1624 }
1625
1626 /*
1627 * NOW GO FOR THE SOURCES
1628 */
1629 if (specType == Suffixes || specType == ExPath ||
1630 specType == Includes || specType == Libs ||
1631 specType == Null || specType == ExObjdir)
1632 {
1633 while (*line) {
1634 /*
1635 * If the target was one that doesn't take files as its sources
1636 * but takes something like suffixes, we take each
1637 * space-separated word on the line as a something and deal
1638 * with it accordingly.
1639 *
1640 * If the target was .SUFFIXES, we take each source as a
1641 * suffix and add it to the list of suffixes maintained by the
1642 * Suff module.
1643 *
1644 * If the target was a .PATH, we add the source as a directory
1645 * to search on the search path.
1646 *
1647 * If it was .INCLUDES, the source is taken to be the suffix of
1648 * files which will be #included and whose search path should
1649 * be present in the .INCLUDES variable.
1650 *
1651 * If it was .LIBS, the source is taken to be the suffix of
1652 * files which are considered libraries and whose search path
1653 * should be present in the .LIBS variable.
1654 *
1655 * If it was .NULL, the source is the suffix to use when a file
1656 * has no valid suffix.
1657 *
1658 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1659 * and will cause make to do a new chdir to that path.
1660 */
1661 while (*cp && !isspace ((unsigned char)*cp)) {
1662 cp++;
1663 }
1664 savec = *cp;
1665 *cp = '\0';
1666 switch (specType) {
1667 case Suffixes:
1668 Suff_AddSuffix(line, &mainNode);
1669 break;
1670 case ExPath:
1671 Lst_ForEach(paths, ParseAddDir, line);
1672 break;
1673 case Includes:
1674 Suff_AddInclude(line);
1675 break;
1676 case Libs:
1677 Suff_AddLib(line);
1678 break;
1679 case Null:
1680 Suff_SetNull(line);
1681 break;
1682 case ExObjdir:
1683 Main_SetObjdir("%s", line);
1684 break;
1685 default:
1686 break;
1687 }
1688 *cp = savec;
1689 if (savec != '\0') {
1690 cp++;
1691 }
1692 while (*cp && isspace ((unsigned char)*cp)) {
1693 cp++;
1694 }
1695 line = cp;
1696 }
1697 if (paths) {
1698 Lst_Destroy(paths, NULL);
1699 paths = NULL;
1700 }
1701 if (specType == ExPath)
1702 Dir_SetPATH();
1703 } else {
1704 assert(paths == NULL);
1705 while (*line) {
1706 /*
1707 * The targets take real sources, so we must beware of archive
1708 * specifications (i.e. things with left parentheses in them)
1709 * and handle them accordingly.
1710 */
1711 for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1712 if (*cp == LPAREN && cp > line && cp[-1] != '$') {
1713 /*
1714 * Only stop for a left parenthesis if it isn't at the
1715 * start of a word (that'll be for variable changes
1716 * later) and isn't preceded by a dollar sign (a dynamic
1717 * source).
1718 */
1719 break;
1720 }
1721 }
1722
1723 if (*cp == LPAREN) {
1724 sources = Lst_Init(FALSE);
1725 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1726 Parse_Error(PARSE_FATAL,
1727 "Error in source archive spec \"%s\"", line);
1728 goto out;
1729 }
1730
1731 while (!Lst_IsEmpty (sources)) {
1732 gn = (GNode *)Lst_DeQueue(sources);
1733 ParseDoSrc(tOp, gn->name);
1734 }
1735 Lst_Destroy(sources, NULL);
1736 cp = line;
1737 } else {
1738 if (*cp) {
1739 *cp = '\0';
1740 cp += 1;
1741 }
1742
1743 ParseDoSrc(tOp, line);
1744 }
1745 while (*cp && isspace ((unsigned char)*cp)) {
1746 cp++;
1747 }
1748 line = cp;
1749 }
1750 }
1751
1752 if (mainNode == NULL) {
1753 /*
1754 * If we have yet to decide on a main target to make, in the
1755 * absence of any user input, we want the first target on
1756 * the first dependency line that is actually a real target
1757 * (i.e. isn't a .USE or .EXEC rule) to be made.
1758 */
1759 Lst_ForEach(targets, ParseFindMain, NULL);
1760 }
1761
1762 out:
1763 if (paths)
1764 Lst_Destroy(paths, NULL);
1765 if (curTargs)
1766 Lst_Destroy(curTargs, NULL);
1767 }
1768
1769 /*-
1770 *---------------------------------------------------------------------
1771 * Parse_IsVar --
1772 * Return TRUE if the passed line is a variable assignment. A variable
1773 * assignment consists of a single word followed by optional whitespace
1774 * followed by either a += or an = operator.
1775 * This function is used both by the Parse_File function and main when
1776 * parsing the command-line arguments.
1777 *
1778 * Input:
1779 * line the line to check
1780 *
1781 * Results:
1782 * TRUE if it is. FALSE if it ain't
1783 *
1784 * Side Effects:
1785 * none
1786 *---------------------------------------------------------------------
1787 */
1788 Boolean
1789 Parse_IsVar(char *line)
1790 {
1791 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1792 char ch;
1793 int level = 0;
1794 #define ISEQOPERATOR(c) \
1795 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1796
1797 /*
1798 * Skip to variable name
1799 */
1800 while (*line == ' ' || *line == '\t')
1801 line++;
1802
1803 /* Scan for one of the assignment operators outside a variable expansion */
1804 while ((ch = *line++) != 0) {
1805 if (ch == '(' || ch == '{') {
1806 level++;
1807 continue;
1808 }
1809 if (ch == ')' || ch == '}') {
1810 level--;
1811 continue;
1812 }
1813 if (level != 0)
1814 continue;
1815 while (ch == ' ' || ch == '\t') {
1816 ch = *line++;
1817 wasSpace = TRUE;
1818 }
1819 #ifdef SUNSHCMD
1820 if (ch == ':' && strncmp(line, "sh", 2) == 0) {
1821 line += 2;
1822 continue;
1823 }
1824 #endif
1825 if (ch == '=')
1826 return TRUE;
1827 if (*line == '=' && ISEQOPERATOR(ch))
1828 return TRUE;
1829 if (wasSpace)
1830 return FALSE;
1831 }
1832
1833 return FALSE;
1834 }
1835
1836 /*-
1837 *---------------------------------------------------------------------
1838 * Parse_DoVar --
1839 * Take the variable assignment in the passed line and do it in the
1840 * global context.
1841 *
1842 * Note: There is a lexical ambiguity with assignment modifier characters
1843 * in variable names. This routine interprets the character before the =
1844 * as a modifier. Therefore, an assignment like
1845 * C++=/usr/bin/CC
1846 * is interpreted as "C+ +=" instead of "C++ =".
1847 *
1848 * Input:
1849 * line a line guaranteed to be a variable assignment.
1850 * This reduces error checks
1851 * ctxt Context in which to do the assignment
1852 *
1853 * Results:
1854 * none
1855 *
1856 * Side Effects:
1857 * the variable structure of the given variable name is altered in the
1858 * global context.
1859 *---------------------------------------------------------------------
1860 */
1861 void
1862 Parse_DoVar(char *line, GNode *ctxt)
1863 {
1864 char *cp; /* pointer into line */
1865 enum {
1866 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1867 } type; /* Type of assignment */
1868 char *opc; /* ptr to operator character to
1869 * null-terminate the variable name */
1870 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1871 * i.e. if any variable expansion was
1872 * performed */
1873 int depth;
1874
1875 /*
1876 * Skip to variable name
1877 */
1878 while (*line == ' ' || *line == '\t')
1879 line++;
1880
1881 /*
1882 * Skip to operator character, nulling out whitespace as we go
1883 * XXX Rather than counting () and {} we should look for $ and
1884 * then expand the variable.
1885 */
1886 for (depth = 0, cp = line + 1; depth > 0 || *cp != '='; cp++) {
1887 if (*cp == '(' || *cp == '{') {
1888 depth++;
1889 continue;
1890 }
1891 if (*cp == ')' || *cp == '}') {
1892 depth--;
1893 continue;
1894 }
1895 if (depth == 0 && isspace ((unsigned char)*cp)) {
1896 *cp = '\0';
1897 }
1898 }
1899 opc = cp-1; /* operator is the previous character */
1900 *cp++ = '\0'; /* nuke the = */
1901
1902 /*
1903 * Check operator type
1904 */
1905 switch (*opc) {
1906 case '+':
1907 type = VAR_APPEND;
1908 *opc = '\0';
1909 break;
1910
1911 case '?':
1912 /*
1913 * If the variable already has a value, we don't do anything.
1914 */
1915 *opc = '\0';
1916 if (Var_Exists(line, ctxt)) {
1917 return;
1918 } else {
1919 type = VAR_NORMAL;
1920 }
1921 break;
1922
1923 case ':':
1924 type = VAR_SUBST;
1925 *opc = '\0';
1926 break;
1927
1928 case '!':
1929 type = VAR_SHELL;
1930 *opc = '\0';
1931 break;
1932
1933 default:
1934 #ifdef SUNSHCMD
1935 while (opc > line && *opc != ':')
1936 opc--;
1937
1938 if (strncmp(opc, ":sh", 3) == 0) {
1939 type = VAR_SHELL;
1940 *opc = '\0';
1941 break;
1942 }
1943 #endif
1944 type = VAR_NORMAL;
1945 break;
1946 }
1947
1948 while (isspace((unsigned char)*cp))
1949 cp++;
1950
1951 if (DEBUG(LINT)) {
1952 if (type != VAR_SUBST && strchr(cp, '$') != NULL) {
1953 /* sanity check now */
1954 char *cp2;
1955
1956 cp2 = Var_Subst(cp, ctxt, VARE_WANTRES|VARE_ASSIGN);
1957 free(cp2);
1958 }
1959 }
1960
1961 if (type == VAR_APPEND) {
1962 Var_Append(line, cp, ctxt);
1963 } else if (type == VAR_SUBST) {
1964 /*
1965 * Allow variables in the old value to be undefined, but leave their
1966 * invocation alone -- this is done by forcing oldVars to be false.
1967 * XXX: This can cause recursive variables, but that's not hard to do,
1968 * and this allows someone to do something like
1969 *
1970 * CFLAGS = $(.INCLUDES)
1971 * CFLAGS := -I.. $(CFLAGS)
1972 *
1973 * And not get an error.
1974 */
1975 Boolean oldOldVars = oldVars;
1976
1977 oldVars = FALSE;
1978
1979 /*
1980 * make sure that we set the variable the first time to nothing
1981 * so that it gets substituted!
1982 */
1983 if (!Var_Exists(line, ctxt))
1984 Var_Set(line, "", ctxt);
1985
1986 cp = Var_Subst(cp, ctxt, VARE_WANTRES|VARE_ASSIGN);
1987 oldVars = oldOldVars;
1988 freeCp = TRUE;
1989
1990 Var_Set(line, cp, ctxt);
1991 } else if (type == VAR_SHELL) {
1992 char *res;
1993 const char *error;
1994
1995 if (strchr(cp, '$') != NULL) {
1996 /*
1997 * There's a dollar sign in the command, so perform variable
1998 * expansion on the whole thing. The resulting string will need
1999 * freeing when we're done.
2000 */
2001 cp = Var_Subst(cp, VAR_CMD, VARE_UNDEFERR|VARE_WANTRES);
2002 freeCp = TRUE;
2003 }
2004
2005 res = Cmd_Exec(cp, &error);
2006 Var_Set(line, res, ctxt);
2007 free(res);
2008
2009 if (error)
2010 Parse_Error(PARSE_WARNING, error, cp);
2011 } else {
2012 /*
2013 * Normal assignment -- just do it.
2014 */
2015 Var_Set(line, cp, ctxt);
2016 }
2017 if (strcmp(line, MAKEOVERRIDES) == 0)
2018 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
2019 else if (strcmp(line, ".CURDIR") == 0) {
2020 /*
2021 * Somone is being (too?) clever...
2022 * Let's pretend they know what they are doing and
2023 * re-initialize the 'cur' Path.
2024 */
2025 Dir_InitCur(cp);
2026 Dir_SetPATH();
2027 } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
2028 Job_SetPrefix();
2029 } else if (strcmp(line, MAKE_EXPORTED) == 0) {
2030 Var_Export(cp, 0);
2031 }
2032 if (freeCp)
2033 free(cp);
2034 }
2035
2036
2037 /*
2038 * ParseMaybeSubMake --
2039 * Scan the command string to see if it a possible submake node
2040 * Input:
2041 * cmd the command to scan
2042 * Results:
2043 * TRUE if the command is possibly a submake, FALSE if not.
2044 */
2045 static Boolean
2046 ParseMaybeSubMake(const char *cmd)
2047 {
2048 size_t i;
2049 static struct {
2050 const char *name;
2051 size_t len;
2052 } vals[] = {
2053 #define MKV(A) { A, sizeof(A) - 1 }
2054 MKV("${MAKE}"),
2055 MKV("${.MAKE}"),
2056 MKV("$(MAKE)"),
2057 MKV("$(.MAKE)"),
2058 MKV("make"),
2059 };
2060 for (i = 0; i < sizeof(vals)/sizeof(vals[0]); i++) {
2061 char *ptr;
2062 if ((ptr = strstr(cmd, vals[i].name)) == NULL)
2063 continue;
2064 if ((ptr == cmd || !isalnum((unsigned char)ptr[-1]))
2065 && !isalnum((unsigned char)ptr[vals[i].len]))
2066 return TRUE;
2067 }
2068 return FALSE;
2069 }
2070
2071 /*-
2072 * ParseAddCmd --
2073 * Lst_ForEach function to add a command line to all targets
2074 *
2075 * Input:
2076 * gnp the node to which the command is to be added
2077 * cmd the command to add
2078 *
2079 * Results:
2080 * Always 0
2081 *
2082 * Side Effects:
2083 * A new element is added to the commands list of the node,
2084 * and the node can be marked as a submake node if the command is
2085 * determined to be that.
2086 */
2087 static int
2088 ParseAddCmd(void *gnp, void *cmd)
2089 {
2090 GNode *gn = (GNode *)gnp;
2091
2092 /* Add to last (ie current) cohort for :: targets */
2093 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
2094 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
2095
2096 /* if target already supplied, ignore commands */
2097 if (!(gn->type & OP_HAS_COMMANDS)) {
2098 (void)Lst_AtEnd(gn->commands, cmd);
2099 if (ParseMaybeSubMake(cmd))
2100 gn->type |= OP_SUBMAKE;
2101 ParseMark(gn);
2102 } else {
2103 #ifdef notyet
2104 /* XXX: We cannot do this until we fix the tree */
2105 (void)Lst_AtEnd(gn->commands, cmd);
2106 Parse_Error(PARSE_WARNING,
2107 "overriding commands for target \"%s\"; "
2108 "previous commands defined at %s: %d ignored",
2109 gn->name, gn->fname, gn->lineno);
2110 #else
2111 Parse_Error(PARSE_WARNING,
2112 "duplicate script for target \"%s\" ignored",
2113 gn->name);
2114 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
2115 "using previous script for \"%s\" defined here",
2116 gn->name);
2117 #endif
2118 }
2119 return 0;
2120 }
2121
2122 /*-
2123 *-----------------------------------------------------------------------
2124 * ParseHasCommands --
2125 * Callback procedure for Parse_File when destroying the list of
2126 * targets on the last dependency line. Marks a target as already
2127 * having commands if it does, to keep from having shell commands
2128 * on multiple dependency lines.
2129 *
2130 * Input:
2131 * gnp Node to examine
2132 *
2133 * Results:
2134 * None
2135 *
2136 * Side Effects:
2137 * OP_HAS_COMMANDS may be set for the target.
2138 *
2139 *-----------------------------------------------------------------------
2140 */
2141 static void
2142 ParseHasCommands(void *gnp)
2143 {
2144 GNode *gn = (GNode *)gnp;
2145 if (!Lst_IsEmpty(gn->commands)) {
2146 gn->type |= OP_HAS_COMMANDS;
2147 }
2148 }
2149
2150 /*-
2151 *-----------------------------------------------------------------------
2152 * Parse_AddIncludeDir --
2153 * Add a directory to the path searched for included makefiles
2154 * bracketed by double-quotes. Used by functions in main.c
2155 *
2156 * Input:
2157 * dir The name of the directory to add
2158 *
2159 * Results:
2160 * None.
2161 *
2162 * Side Effects:
2163 * The directory is appended to the list.
2164 *
2165 *-----------------------------------------------------------------------
2166 */
2167 void
2168 Parse_AddIncludeDir(char *dir)
2169 {
2170 (void)Dir_AddDir(parseIncPath, dir);
2171 }
2172
2173 /*-
2174 *---------------------------------------------------------------------
2175 * ParseDoInclude --
2176 * Push to another file.
2177 *
2178 * The input is the line minus the `.'. A file spec is a string
2179 * enclosed in <> or "". The former is looked for only in sysIncPath.
2180 * The latter in . and the directories specified by -I command line
2181 * options
2182 *
2183 * Results:
2184 * None
2185 *
2186 * Side Effects:
2187 * A structure is added to the includes Lst and readProc, lineno,
2188 * fname and curFILE are altered for the new file
2189 *---------------------------------------------------------------------
2190 */
2191
2192 static void
2193 Parse_include_file(char *file, Boolean isSystem, Boolean depinc, int silent)
2194 {
2195 struct loadedfile *lf;
2196 char *fullname; /* full pathname of file */
2197 char *newName;
2198 char *prefEnd, *incdir;
2199 int fd;
2200 int i;
2201
2202 /*
2203 * Now we know the file's name and its search path, we attempt to
2204 * find the durn thing. A return of NULL indicates the file don't
2205 * exist.
2206 */
2207 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2208
2209 if (fullname == NULL && !isSystem) {
2210 /*
2211 * Include files contained in double-quotes are first searched for
2212 * relative to the including file's location. We don't want to
2213 * cd there, of course, so we just tack on the old file's
2214 * leading path components and call Dir_FindFile to see if
2215 * we can locate the beast.
2216 */
2217
2218 incdir = bmake_strdup(curFile->fname);
2219 prefEnd = strrchr(incdir, '/');
2220 if (prefEnd != NULL) {
2221 *prefEnd = '\0';
2222 /* Now do lexical processing of leading "../" on the filename */
2223 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2224 prefEnd = strrchr(incdir + 1, '/');
2225 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
2226 break;
2227 *prefEnd = '\0';
2228 }
2229 newName = str_concat(incdir, file + i, STR_ADDSLASH);
2230 fullname = Dir_FindFile(newName, parseIncPath);
2231 if (fullname == NULL)
2232 fullname = Dir_FindFile(newName, dirSearchPath);
2233 free(newName);
2234 }
2235 free(incdir);
2236
2237 if (fullname == NULL) {
2238 /*
2239 * Makefile wasn't found in same directory as included makefile.
2240 * Search for it first on the -I search path,
2241 * then on the .PATH search path, if not found in a -I directory.
2242 * If we have a suffix specific path we should use that.
2243 */
2244 char *suff;
2245 Lst suffPath = NULL;
2246
2247 if ((suff = strrchr(file, '.'))) {
2248 suffPath = Suff_GetPath(suff);
2249 if (suffPath != NULL) {
2250 fullname = Dir_FindFile(file, suffPath);
2251 }
2252 }
2253 if (fullname == NULL) {
2254 fullname = Dir_FindFile(file, parseIncPath);
2255 if (fullname == NULL) {
2256 fullname = Dir_FindFile(file, dirSearchPath);
2257 }
2258 }
2259 }
2260 }
2261
2262 /* Looking for a system file or file still not found */
2263 if (fullname == NULL) {
2264 /*
2265 * Look for it on the system path
2266 */
2267 fullname = Dir_FindFile(file,
2268 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2269 }
2270
2271 if (fullname == NULL) {
2272 if (!silent)
2273 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2274 return;
2275 }
2276
2277 /* Actually open the file... */
2278 fd = open(fullname, O_RDONLY);
2279 if (fd == -1) {
2280 if (!silent)
2281 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2282 free(fullname);
2283 return;
2284 }
2285
2286 /* load it */
2287 lf = loadfile(fullname, fd);
2288
2289 ParseSetIncludedFile();
2290 /* Start reading from this file next */
2291 Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2292 curFile->lf = lf;
2293 if (depinc)
2294 doing_depend = depinc; /* only turn it on */
2295 }
2296
2297 static void
2298 ParseDoInclude(char *line)
2299 {
2300 char endc; /* the character which ends the file spec */
2301 char *cp; /* current position in file spec */
2302 int silent = *line != 'i';
2303 char *file = &line[7 + silent];
2304
2305 /* Skip to delimiter character so we know where to look */
2306 while (*file == ' ' || *file == '\t')
2307 file++;
2308
2309 if (*file != '"' && *file != '<') {
2310 Parse_Error(PARSE_FATAL,
2311 ".include filename must be delimited by '\"' or '<'");
2312 return;
2313 }
2314
2315 /*
2316 * Set the search path on which to find the include file based on the
2317 * characters which bracket its name. Angle-brackets imply it's
2318 * a system Makefile while double-quotes imply it's a user makefile
2319 */
2320 if (*file == '<') {
2321 endc = '>';
2322 } else {
2323 endc = '"';
2324 }
2325
2326 /* Skip to matching delimiter */
2327 for (cp = ++file; *cp && *cp != endc; cp++)
2328 continue;
2329
2330 if (*cp != endc) {
2331 Parse_Error(PARSE_FATAL,
2332 "Unclosed %cinclude filename. '%c' expected",
2333 '.', endc);
2334 return;
2335 }
2336 *cp = '\0';
2337
2338 /*
2339 * Substitute for any variables in the file name before trying to
2340 * find the thing.
2341 */
2342 file = Var_Subst(file, VAR_CMD, VARE_WANTRES);
2343
2344 Parse_include_file(file, endc == '>', *line == 'd', silent);
2345 free(file);
2346 }
2347
2348
2349 /*-
2350 *---------------------------------------------------------------------
2351 * ParseSetIncludedFile --
2352 * Set the .INCLUDEDFROMFILE variable to the contents of .PARSEFILE
2353 * and the .INCLUDEDFROMDIR variable to the contents of .PARSEDIR
2354 *
2355 * Results:
2356 * None
2357 *
2358 * Side Effects:
2359 * The .INCLUDEDFROMFILE variable is overwritten by the contents
2360 * of .PARSEFILE and the .INCLUDEDFROMDIR variable is overwriten
2361 * by the contents of .PARSEDIR
2362 *---------------------------------------------------------------------
2363 */
2364 static void
2365 ParseSetIncludedFile(void)
2366 {
2367 char *pf_freeIt;
2368 char *pd_freeIt;
2369
2370 const char *pf = Var_Value(".PARSEFILE", VAR_GLOBAL, &pf_freeIt);
2371 Var_Set(".INCLUDEDFROMFILE", pf, VAR_GLOBAL);
2372 const char *pd = Var_Value(".PARSEDIR", VAR_GLOBAL, &pd_freeIt);
2373 Var_Set(".INCLUDEDFROMDIR", pd, VAR_GLOBAL);
2374
2375 if (DEBUG(PARSE))
2376 fprintf(debug_file, "%s: ${.INCLUDEDFROMDIR} = `%s' "
2377 "${.INCLUDEDFROMFILE} = `%s'\n", __func__, pd, pf);
2378
2379 free(pf_freeIt);
2380 free(pd_freeIt);
2381 }
2382 /*-
2383 *---------------------------------------------------------------------
2384 * ParseSetParseFile --
2385 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2386 * basename of the given filename
2387 *
2388 * Results:
2389 * None
2390 *
2391 * Side Effects:
2392 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
2393 * dirname and basename of the given filename.
2394 *---------------------------------------------------------------------
2395 */
2396 static void
2397 ParseSetParseFile(const char *filename)
2398 {
2399 char *slash, *dirname;
2400 const char *pd, *pf;
2401 int len;
2402
2403 slash = strrchr(filename, '/');
2404 if (slash == NULL) {
2405 Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL);
2406 Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL);
2407 dirname= NULL;
2408 } else {
2409 len = slash - filename;
2410 dirname = bmake_malloc(len + 1);
2411 memcpy(dirname, filename, len);
2412 dirname[len] = '\0';
2413 Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL);
2414 Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL);
2415 }
2416 if (DEBUG(PARSE))
2417 fprintf(debug_file, "%s: ${.PARSEDIR} = `%s' ${.PARSEFILE} = `%s'\n",
2418 __func__, pd, pf);
2419 free(dirname);
2420 }
2421
2422 /*
2423 * Track the makefiles we read - so makefiles can
2424 * set dependencies on them.
2425 * Avoid adding anything more than once.
2426 */
2427
2428 static void
2429 ParseTrackInput(const char *name)
2430 {
2431 char *fp = NULL;
2432
2433 const char *old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2434 if (old) {
2435 size_t name_len = strlen(name);
2436 const char *ep = old + strlen(old) - name_len;
2437 /* does it contain name? */
2438 for (; old != NULL; old = strchr(old, ' ')) {
2439 if (*old == ' ')
2440 old++;
2441 if (old >= ep)
2442 break; /* cannot contain name */
2443 if (memcmp(old, name, name_len) == 0
2444 && (old[name_len] == 0 || old[name_len] == ' '))
2445 goto cleanup;
2446 }
2447 }
2448 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2449 cleanup:
2450 free(fp);
2451 }
2452
2453
2454 /*-
2455 *---------------------------------------------------------------------
2456 * Parse_setInput --
2457 * Start Parsing from the given source
2458 *
2459 * Results:
2460 * None
2461 *
2462 * Side Effects:
2463 * A structure is added to the includes Lst and readProc, lineno,
2464 * fname and curFile are altered for the new file
2465 *---------------------------------------------------------------------
2466 */
2467 void
2468 Parse_SetInput(const char *name, int line, int fd,
2469 char *(*nextbuf)(void *, size_t *), void *arg)
2470 {
2471 char *buf;
2472 size_t len;
2473
2474 if (name == NULL)
2475 name = curFile->fname;
2476 else
2477 ParseTrackInput(name);
2478
2479 if (DEBUG(PARSE))
2480 fprintf(debug_file, "%s: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2481 __func__, name, line, fd, nextbuf, arg);
2482
2483 if (fd == -1 && nextbuf == NULL)
2484 /* sanity */
2485 return;
2486
2487 if (curFile != NULL)
2488 /* Save exiting file info */
2489 Lst_AtFront(includes, curFile);
2490
2491 /* Allocate and fill in new structure */
2492 curFile = bmake_malloc(sizeof *curFile);
2493
2494 /*
2495 * Once the previous state has been saved, we can get down to reading
2496 * the new file. We set up the name of the file to be the absolute
2497 * name of the include file so error messages refer to the right
2498 * place.
2499 */
2500 curFile->fname = bmake_strdup(name);
2501 curFile->lineno = line;
2502 curFile->first_lineno = line;
2503 curFile->nextbuf = nextbuf;
2504 curFile->nextbuf_arg = arg;
2505 curFile->lf = NULL;
2506 curFile->depending = doing_depend; /* restore this on EOF */
2507
2508 assert(nextbuf != NULL);
2509
2510 /* Get first block of input data */
2511 buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2512 if (buf == NULL) {
2513 /* Was all a waste of time ... */
2514 if (curFile->fname)
2515 free(curFile->fname);
2516 free(curFile);
2517 return;
2518 }
2519 curFile->P_str = buf;
2520 curFile->P_ptr = buf;
2521 curFile->P_end = buf+len;
2522
2523 curFile->cond_depth = Cond_save_depth();
2524 ParseSetParseFile(name);
2525 }
2526
2527 /*-
2528 *-----------------------------------------------------------------------
2529 * IsInclude --
2530 * Check if the line is an include directive
2531 *
2532 * Results:
2533 * TRUE if it is.
2534 *
2535 * Side Effects:
2536 * None
2537 *
2538 *-----------------------------------------------------------------------
2539 */
2540 static Boolean
2541 IsInclude(const char *line, Boolean sysv)
2542 {
2543 static const char inc[] = "include";
2544 static const size_t inclen = sizeof(inc) - 1;
2545
2546 // 'd' is not valid for sysv
2547 int o = strchr(&("ds-"[sysv]), *line) != NULL;
2548
2549 if (strncmp(line + o, inc, inclen) != 0)
2550 return FALSE;
2551
2552 // Space is not mandatory for BSD .include
2553 return !sysv || isspace((unsigned char)line[inclen + o]);
2554 }
2555
2556
2557 #ifdef SYSVINCLUDE
2558 /*-
2559 *-----------------------------------------------------------------------
2560 * IsSysVInclude --
2561 * Check if the line is a SYSV include directive
2562 *
2563 * Results:
2564 * TRUE if it is.
2565 *
2566 * Side Effects:
2567 * None
2568 *
2569 *-----------------------------------------------------------------------
2570 */
2571 static Boolean
2572 IsSysVInclude(const char *line)
2573 {
2574 const char *p;
2575
2576 if (!IsInclude(line, TRUE))
2577 return FALSE;
2578
2579 /* Avoid interpeting a dependency line as an include */
2580 for (p = line; (p = strchr(p, ':')) != NULL;) {
2581 if (*++p == '\0') {
2582 /* end of line -> dependency */
2583 return FALSE;
2584 }
2585 if (*p == ':' || isspace((unsigned char)*p)) {
2586 /* :: operator or ': ' -> dependency */
2587 return FALSE;
2588 }
2589 }
2590 return TRUE;
2591 }
2592
2593 /*-
2594 *---------------------------------------------------------------------
2595 * ParseTraditionalInclude --
2596 * Push to another file.
2597 *
2598 * The input is the current line. The file name(s) are
2599 * following the "include".
2600 *
2601 * Results:
2602 * None
2603 *
2604 * Side Effects:
2605 * A structure is added to the includes Lst and readProc, lineno,
2606 * fname and curFILE are altered for the new file
2607 *---------------------------------------------------------------------
2608 */
2609 static void
2610 ParseTraditionalInclude(char *line)
2611 {
2612 char *cp; /* current position in file spec */
2613 int done = 0;
2614 int silent = line[0] != 'i';
2615 char *file = &line[silent + 7];
2616 char *all_files;
2617
2618 if (DEBUG(PARSE)) {
2619 fprintf(debug_file, "%s: %s\n", __func__, file);
2620 }
2621
2622 /*
2623 * Skip over whitespace
2624 */
2625 while (isspace((unsigned char)*file))
2626 file++;
2627
2628 /*
2629 * Substitute for any variables in the file name before trying to
2630 * find the thing.
2631 */
2632 all_files = Var_Subst(file, VAR_CMD, VARE_WANTRES);
2633
2634 if (*file == '\0') {
2635 Parse_Error(PARSE_FATAL,
2636 "Filename missing from \"include\"");
2637 goto out;
2638 }
2639
2640 for (file = all_files; !done; file = cp + 1) {
2641 /* Skip to end of line or next whitespace */
2642 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2643 continue;
2644
2645 if (*cp)
2646 *cp = '\0';
2647 else
2648 done = 1;
2649
2650 Parse_include_file(file, FALSE, FALSE, silent);
2651 }
2652 out:
2653 free(all_files);
2654 }
2655 #endif
2656
2657 #ifdef GMAKEEXPORT
2658 /*-
2659 *---------------------------------------------------------------------
2660 * ParseGmakeExport --
2661 * Parse export <variable>=<value>
2662 *
2663 * And set the environment with it.
2664 *
2665 * Results:
2666 * None
2667 *
2668 * Side Effects:
2669 * None
2670 *---------------------------------------------------------------------
2671 */
2672 static void
2673 ParseGmakeExport(char *line)
2674 {
2675 char *variable = &line[6];
2676 char *value;
2677
2678 if (DEBUG(PARSE)) {
2679 fprintf(debug_file, "%s: %s\n", __func__, variable);
2680 }
2681
2682 /*
2683 * Skip over whitespace
2684 */
2685 while (isspace((unsigned char)*variable))
2686 variable++;
2687
2688 for (value = variable; *value && *value != '='; value++)
2689 continue;
2690
2691 if (*value != '=') {
2692 Parse_Error(PARSE_FATAL,
2693 "Variable/Value missing from \"export\"");
2694 return;
2695 }
2696 *value++ = '\0'; /* terminate variable */
2697
2698 /*
2699 * Expand the value before putting it in the environment.
2700 */
2701 value = Var_Subst(value, VAR_CMD, VARE_WANTRES);
2702 setenv(variable, value, 1);
2703 free(value);
2704 }
2705 #endif
2706
2707 /*-
2708 *---------------------------------------------------------------------
2709 * ParseEOF --
2710 * Called when EOF is reached in the current file. If we were reading
2711 * an include file, the includes stack is popped and things set up
2712 * to go back to reading the previous file at the previous location.
2713 *
2714 * Results:
2715 * CONTINUE if there's more to do. DONE if not.
2716 *
2717 * Side Effects:
2718 * The old curFILE, is closed. The includes list is shortened.
2719 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2720 *---------------------------------------------------------------------
2721 */
2722 static int
2723 ParseEOF(void)
2724 {
2725 char *ptr;
2726 size_t len;
2727
2728 assert(curFile->nextbuf != NULL);
2729
2730 doing_depend = curFile->depending; /* restore this */
2731 /* get next input buffer, if any */
2732 ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2733 curFile->P_ptr = ptr;
2734 curFile->P_str = ptr;
2735 curFile->P_end = ptr + len;
2736 curFile->lineno = curFile->first_lineno;
2737 if (ptr != NULL) {
2738 /* Iterate again */
2739 return CONTINUE;
2740 }
2741
2742 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2743 Cond_restore_depth(curFile->cond_depth);
2744
2745 if (curFile->lf != NULL) {
2746 loadedfile_destroy(curFile->lf);
2747 curFile->lf = NULL;
2748 }
2749
2750 /* Dispose of curFile info */
2751 /* Leak curFile->fname because all the gnodes have pointers to it */
2752 free(curFile->P_str);
2753 free(curFile);
2754
2755 curFile = Lst_DeQueue(includes);
2756
2757 if (curFile == NULL) {
2758 /* We've run out of input */
2759 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2760 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2761 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2762 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2763 return DONE;
2764 }
2765
2766 if (DEBUG(PARSE))
2767 fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2768 curFile->fname, curFile->lineno);
2769
2770 /* Restore the PARSEDIR/PARSEFILE variables */
2771 ParseSetParseFile(curFile->fname);
2772 return CONTINUE;
2773 }
2774
2775 #define PARSE_RAW 1
2776 #define PARSE_SKIP 2
2777
2778 static char *
2779 ParseGetLine(int flags, int *length)
2780 {
2781 IFile *cf = curFile;
2782 char *ptr;
2783 char ch;
2784 char *line;
2785 char *line_end;
2786 char *escaped;
2787 char *comment;
2788 char *tp;
2789
2790 /* Loop through blank lines and comment lines */
2791 for (;;) {
2792 cf->lineno++;
2793 line = cf->P_ptr;
2794 ptr = line;
2795 line_end = line;
2796 escaped = NULL;
2797 comment = NULL;
2798 for (;;) {
2799 if (cf->P_end != NULL && ptr == cf->P_end) {
2800 /* end of buffer */
2801 ch = 0;
2802 break;
2803 }
2804 ch = *ptr;
2805 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2806 if (cf->P_end == NULL)
2807 /* End of string (aka for loop) data */
2808 break;
2809 /* see if there is more we can parse */
2810 while (ptr++ < cf->P_end) {
2811 if ((ch = *ptr) == '\n') {
2812 if (ptr > line && ptr[-1] == '\\')
2813 continue;
2814 Parse_Error(PARSE_WARNING,
2815 "Zero byte read from file, skipping rest of line.");
2816 break;
2817 }
2818 }
2819 if (cf->nextbuf != NULL) {
2820 /*
2821 * End of this buffer; return EOF and outer logic
2822 * will get the next one. (eww)
2823 */
2824 break;
2825 }
2826 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2827 return NULL;
2828 }
2829
2830 if (ch == '\\') {
2831 /* Don't treat next character as special, remember first one */
2832 if (escaped == NULL)
2833 escaped = ptr;
2834 if (ptr[1] == '\n')
2835 cf->lineno++;
2836 ptr += 2;
2837 line_end = ptr;
2838 continue;
2839 }
2840 if (ch == '#' && comment == NULL) {
2841 /* Remember first '#' for comment stripping */
2842 /* Unless previous char was '[', as in modifier :[#] */
2843 if (!(ptr > line && ptr[-1] == '['))
2844 comment = line_end;
2845 }
2846 ptr++;
2847 if (ch == '\n')
2848 break;
2849 if (!isspace((unsigned char)ch))
2850 /* We are not interested in trailing whitespace */
2851 line_end = ptr;
2852 }
2853
2854 /* Save next 'to be processed' location */
2855 cf->P_ptr = ptr;
2856
2857 /* Check we have a non-comment, non-blank line */
2858 if (line_end == line || comment == line) {
2859 if (ch == 0)
2860 /* At end of file */
2861 return NULL;
2862 /* Parse another line */
2863 continue;
2864 }
2865
2866 /* We now have a line of data */
2867 *line_end = 0;
2868
2869 if (flags & PARSE_RAW) {
2870 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2871 *length = line_end - line;
2872 return line;
2873 }
2874
2875 if (flags & PARSE_SKIP) {
2876 /* Completely ignore non-directives */
2877 if (line[0] != '.')
2878 continue;
2879 /* We could do more of the .else/.elif/.endif checks here */
2880 }
2881 break;
2882 }
2883
2884 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2885 if (comment != NULL && line[0] != '\t') {
2886 line_end = comment;
2887 *line_end = 0;
2888 }
2889
2890 /* If we didn't see a '\\' then the in-situ data is fine */
2891 if (escaped == NULL) {
2892 *length = line_end - line;
2893 return line;
2894 }
2895
2896 /* Remove escapes from '\n' and '#' */
2897 tp = ptr = escaped;
2898 escaped = line;
2899 for (; ; *tp++ = ch) {
2900 ch = *ptr++;
2901 if (ch != '\\') {
2902 if (ch == 0)
2903 break;
2904 continue;
2905 }
2906
2907 ch = *ptr++;
2908 if (ch == 0) {
2909 /* Delete '\\' at end of buffer */
2910 tp--;
2911 break;
2912 }
2913
2914 if (ch == '#' && line[0] != '\t')
2915 /* Delete '\\' from before '#' on non-command lines */
2916 continue;
2917
2918 if (ch != '\n') {
2919 /* Leave '\\' in buffer for later */
2920 *tp++ = '\\';
2921 /* Make sure we don't delete an escaped ' ' from the line end */
2922 escaped = tp + 1;
2923 continue;
2924 }
2925
2926 /* Escaped '\n' replace following whitespace with a single ' ' */
2927 while (ptr[0] == ' ' || ptr[0] == '\t')
2928 ptr++;
2929 ch = ' ';
2930 }
2931
2932 /* Delete any trailing spaces - eg from empty continuations */
2933 while (tp > escaped && isspace((unsigned char)tp[-1]))
2934 tp--;
2935
2936 *tp = 0;
2937 *length = tp - line;
2938 return line;
2939 }
2940
2941 /*-
2942 *---------------------------------------------------------------------
2943 * ParseReadLine --
2944 * Read an entire line from the input file. Called only by Parse_File.
2945 *
2946 * Results:
2947 * A line w/o its newline
2948 *
2949 * Side Effects:
2950 * Only those associated with reading a character
2951 *---------------------------------------------------------------------
2952 */
2953 static char *
2954 ParseReadLine(void)
2955 {
2956 char *line; /* Result */
2957 int lineLength; /* Length of result */
2958 int lineno; /* Saved line # */
2959 int rval;
2960
2961 for (;;) {
2962 line = ParseGetLine(0, &lineLength);
2963 if (line == NULL)
2964 return NULL;
2965
2966 if (line[0] != '.')
2967 return line;
2968
2969 /*
2970 * The line might be a conditional. Ask the conditional module
2971 * about it and act accordingly
2972 */
2973 switch (Cond_Eval(line)) {
2974 case COND_SKIP:
2975 /* Skip to next conditional that evaluates to COND_PARSE. */
2976 do {
2977 line = ParseGetLine(PARSE_SKIP, &lineLength);
2978 } while (line && Cond_Eval(line) != COND_PARSE);
2979 if (line == NULL)
2980 break;
2981 continue;
2982 case COND_PARSE:
2983 continue;
2984 case COND_INVALID: /* Not a conditional line */
2985 /* Check for .for loops */
2986 rval = For_Eval(line);
2987 if (rval == 0)
2988 /* Not a .for line */
2989 break;
2990 if (rval < 0)
2991 /* Syntax error - error printed, ignore line */
2992 continue;
2993 /* Start of a .for loop */
2994 lineno = curFile->lineno;
2995 /* Accumulate loop lines until matching .endfor */
2996 do {
2997 line = ParseGetLine(PARSE_RAW, &lineLength);
2998 if (line == NULL) {
2999 Parse_Error(PARSE_FATAL,
3000 "Unexpected end of file in for loop.");
3001 break;
3002 }
3003 } while (For_Accum(line));
3004 /* Stash each iteration as a new 'input file' */
3005 For_Run(lineno);
3006 /* Read next line from for-loop buffer */
3007 continue;
3008 }
3009 return line;
3010 }
3011 }
3012
3013 /*-
3014 *-----------------------------------------------------------------------
3015 * ParseFinishLine --
3016 * Handle the end of a dependency group.
3017 *
3018 * Results:
3019 * Nothing.
3020 *
3021 * Side Effects:
3022 * inLine set FALSE. 'targets' list destroyed.
3023 *
3024 *-----------------------------------------------------------------------
3025 */
3026 static void
3027 ParseFinishLine(void)
3028 {
3029 if (inLine) {
3030 Lst_ForEach(targets, Suff_EndTransform, NULL);
3031 Lst_Destroy(targets, ParseHasCommands);
3032 targets = NULL;
3033 inLine = FALSE;
3034 }
3035 }
3036
3037
3038 /*-
3039 *---------------------------------------------------------------------
3040 * Parse_File --
3041 * Parse a file into its component parts, incorporating it into the
3042 * current dependency graph. This is the main function and controls
3043 * almost every other function in this module
3044 *
3045 * Input:
3046 * name the name of the file being read
3047 * fd Open file to makefile to parse
3048 *
3049 * Results:
3050 * None
3051 *
3052 * Side Effects:
3053 * closes fd.
3054 * Loads. Nodes are added to the list of all targets, nodes and links
3055 * are added to the dependency graph. etc. etc. etc.
3056 *---------------------------------------------------------------------
3057 */
3058 void
3059 Parse_File(const char *name, int fd)
3060 {
3061 char *cp; /* pointer into the line */
3062 char *line; /* the line we're working on */
3063 struct loadedfile *lf;
3064
3065 lf = loadfile(name, fd);
3066
3067 inLine = FALSE;
3068 fatals = 0;
3069
3070 if (name == NULL)
3071 name = "(stdin)";
3072
3073 Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
3074 curFile->lf = lf;
3075
3076 do {
3077 for (; (line = ParseReadLine()) != NULL; ) {
3078 if (DEBUG(PARSE))
3079 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
3080 curFile->lineno, line);
3081 if (*line == '.') {
3082 /*
3083 * Lines that begin with the special character may be
3084 * include or undef directives.
3085 * On the other hand they can be suffix rules (.c.o: ...)
3086 * or just dependencies for filenames that start '.'.
3087 */
3088 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
3089 continue;
3090 }
3091 if (IsInclude(cp, FALSE)) {
3092 ParseDoInclude(cp);
3093 continue;
3094 }
3095 if (strncmp(cp, "undef", 5) == 0) {
3096 char *cp2;
3097 for (cp += 5; isspace((unsigned char) *cp); cp++)
3098 continue;
3099 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
3100 *cp2 != '\0'; cp2++)
3101 continue;
3102 *cp2 = '\0';
3103 Var_Delete(cp, VAR_GLOBAL);
3104 continue;
3105 } else if (strncmp(cp, "export", 6) == 0) {
3106 for (cp += 6; isspace((unsigned char) *cp); cp++)
3107 continue;
3108 Var_Export(cp, 1);
3109 continue;
3110 } else if (strncmp(cp, "unexport", 8) == 0) {
3111 Var_UnExport(cp);
3112 continue;
3113 } else if (strncmp(cp, "info", 4) == 0 ||
3114 strncmp(cp, "error", 5) == 0 ||
3115 strncmp(cp, "warning", 7) == 0) {
3116 if (ParseMessage(cp))
3117 continue;
3118 }
3119 }
3120
3121 if (*line == '\t') {
3122 /*
3123 * If a line starts with a tab, it can only hope to be
3124 * a creation command.
3125 */
3126 cp = line + 1;
3127 shellCommand:
3128 for (; isspace ((unsigned char)*cp); cp++) {
3129 continue;
3130 }
3131 if (*cp) {
3132 if (!inLine)
3133 Parse_Error(PARSE_FATAL,
3134 "Unassociated shell command \"%s\"",
3135 cp);
3136 /*
3137 * So long as it's not a blank line and we're actually
3138 * in a dependency spec, add the command to the list of
3139 * commands of all targets in the dependency spec
3140 */
3141 if (targets) {
3142 cp = bmake_strdup(cp);
3143 Lst_ForEach(targets, ParseAddCmd, cp);
3144 #ifdef CLEANUP
3145 Lst_AtEnd(targCmds, cp);
3146 #endif
3147 }
3148 }
3149 continue;
3150 }
3151
3152 #ifdef SYSVINCLUDE
3153 if (IsSysVInclude(line)) {
3154 /*
3155 * It's an S3/S5-style "include".
3156 */
3157 ParseTraditionalInclude(line);
3158 continue;
3159 }
3160 #endif
3161 #ifdef GMAKEEXPORT
3162 if (strncmp(line, "export", 6) == 0 &&
3163 isspace((unsigned char) line[6]) &&
3164 strchr(line, ':') == NULL) {
3165 /*
3166 * It's a Gmake "export".
3167 */
3168 ParseGmakeExport(line);
3169 continue;
3170 }
3171 #endif
3172 if (Parse_IsVar(line)) {
3173 ParseFinishLine();
3174 Parse_DoVar(line, VAR_GLOBAL);
3175 continue;
3176 }
3177
3178 #ifndef POSIX
3179 /*
3180 * To make life easier on novices, if the line is indented we
3181 * first make sure the line has a dependency operator in it.
3182 * If it doesn't have an operator and we're in a dependency
3183 * line's script, we assume it's actually a shell command
3184 * and add it to the current list of targets.
3185 */
3186 cp = line;
3187 if (isspace((unsigned char) line[0])) {
3188 while (isspace((unsigned char) *cp))
3189 cp++;
3190 while (*cp && (ParseIsEscaped(line, cp) ||
3191 *cp != ':' && *cp != '!')) {
3192 cp++;
3193 }
3194 if (*cp == '\0') {
3195 if (inLine) {
3196 Parse_Error(PARSE_WARNING,
3197 "Shell command needs a leading tab");
3198 goto shellCommand;
3199 }
3200 }
3201 }
3202 #endif
3203 ParseFinishLine();
3204
3205 /*
3206 * For some reason - probably to make the parser impossible -
3207 * a ';' can be used to separate commands from dependencies.
3208 * Attempt to avoid ';' inside substitution patterns.
3209 */
3210 {
3211 int level = 0;
3212
3213 for (cp = line; *cp != 0; cp++) {
3214 if (*cp == '\\' && cp[1] != 0) {
3215 cp++;
3216 continue;
3217 }
3218 if (*cp == '$' &&
3219 (cp[1] == '(' || cp[1] == '{')) {
3220 level++;
3221 continue;
3222 }
3223 if (level > 0) {
3224 if (*cp == ')' || *cp == '}') {
3225 level--;
3226 continue;
3227 }
3228 } else if (*cp == ';') {
3229 break;
3230 }
3231 }
3232 }
3233 if (*cp != 0)
3234 /* Terminate the dependency list at the ';' */
3235 *cp++ = 0;
3236 else
3237 cp = NULL;
3238
3239 /*
3240 * We now know it's a dependency line so it needs to have all
3241 * variables expanded before being parsed. Tell the variable
3242 * module to complain if some variable is undefined...
3243 */
3244 line = Var_Subst(line, VAR_CMD, VARE_UNDEFERR|VARE_WANTRES);
3245
3246 /*
3247 * Need a non-circular list for the target nodes
3248 */
3249 if (targets)
3250 Lst_Destroy(targets, NULL);
3251
3252 targets = Lst_Init(FALSE);
3253 inLine = TRUE;
3254
3255 ParseDoDependency(line);
3256 free(line);
3257
3258 /* If there were commands after a ';', add them now */
3259 if (cp != NULL) {
3260 goto shellCommand;
3261 }
3262 }
3263 /*
3264 * Reached EOF, but it may be just EOF of an include file...
3265 */
3266 } while (ParseEOF() == CONTINUE);
3267
3268 if (fatals) {
3269 (void)fflush(stdout);
3270 (void)fprintf(stderr,
3271 "%s: Fatal errors encountered -- cannot continue",
3272 progname);
3273 PrintOnError(NULL, NULL);
3274 exit(1);
3275 }
3276 }
3277
3278 /*-
3279 *---------------------------------------------------------------------
3280 * Parse_Init --
3281 * initialize the parsing module
3282 *
3283 * Results:
3284 * none
3285 *
3286 * Side Effects:
3287 * the parseIncPath list is initialized...
3288 *---------------------------------------------------------------------
3289 */
3290 void
3291 Parse_Init(void)
3292 {
3293 mainNode = NULL;
3294 parseIncPath = Lst_Init(FALSE);
3295 sysIncPath = Lst_Init(FALSE);
3296 defIncPath = Lst_Init(FALSE);
3297 includes = Lst_Init(FALSE);
3298 #ifdef CLEANUP
3299 targCmds = Lst_Init(FALSE);
3300 #endif
3301 }
3302
3303 void
3304 Parse_End(void)
3305 {
3306 #ifdef CLEANUP
3307 Lst_Destroy(targCmds, (FreeProc *)free);
3308 if (targets)
3309 Lst_Destroy(targets, NULL);
3310 Lst_Destroy(defIncPath, Dir_Destroy);
3311 Lst_Destroy(sysIncPath, Dir_Destroy);
3312 Lst_Destroy(parseIncPath, Dir_Destroy);
3313 Lst_Destroy(includes, NULL); /* Should be empty now */
3314 #endif
3315 }
3316
3317
3318 /*-
3319 *-----------------------------------------------------------------------
3320 * Parse_MainName --
3321 * Return a Lst of the main target to create for main()'s sake. If
3322 * no such target exists, we Punt with an obnoxious error message.
3323 *
3324 * Results:
3325 * A Lst of the single node to create.
3326 *
3327 * Side Effects:
3328 * None.
3329 *
3330 *-----------------------------------------------------------------------
3331 */
3332 Lst
3333 Parse_MainName(void)
3334 {
3335 Lst mainList; /* result list */
3336
3337 mainList = Lst_Init(FALSE);
3338
3339 if (mainNode == NULL) {
3340 Punt("no target to make.");
3341 /*NOTREACHED*/
3342 } else if (mainNode->type & OP_DOUBLEDEP) {
3343 (void)Lst_AtEnd(mainList, mainNode);
3344 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3345 }
3346 else
3347 (void)Lst_AtEnd(mainList, mainNode);
3348 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3349 return mainList;
3350 }
3351
3352 /*-
3353 *-----------------------------------------------------------------------
3354 * ParseMark --
3355 * Add the filename and lineno to the GNode so that we remember
3356 * where it was first defined.
3357 *
3358 * Side Effects:
3359 * None.
3360 *
3361 *-----------------------------------------------------------------------
3362 */
3363 static void
3364 ParseMark(GNode *gn)
3365 {
3366 gn->fname = curFile->fname;
3367 gn->lineno = curFile->lineno;
3368 }
3369