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