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