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