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