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