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