parse.c revision 1.109 1 /* $NetBSD: parse.c,v 1.109 2006/02/11 20:59:49 dsl 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 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: parse.c,v 1.109 2006/02/11 20:59:49 dsl Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)parse.c 8.3 (Berkeley) 3/19/94";
78 #else
79 __RCSID("$NetBSD: parse.c,v 1.109 2006/02/11 20:59:49 dsl Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83
84 /*-
85 * parse.c --
86 * Functions to parse a makefile.
87 *
88 * One function, Parse_Init, must be called before any functions
89 * in this module are used. After that, the function Parse_File is the
90 * main entry point and controls most of the other functions in this
91 * module.
92 *
93 * Most important structures are kept in Lsts. Directories for
94 * the #include "..." function are kept in the 'parseIncPath' Lst, while
95 * those for the #include <...> are kept in the 'sysIncPath' Lst. The
96 * targets currently being defined are kept in the 'targets' Lst.
97 *
98 * The variables 'fname' and 'lineno' are used to track the name
99 * of the current file and the line number in that file so that error
100 * messages can be more meaningful.
101 *
102 * Interface:
103 * Parse_Init Initialization function which must be
104 * called before anything else in this module
105 * is used.
106 *
107 * Parse_End Cleanup the module
108 *
109 * Parse_File Function used to parse a makefile. It must
110 * be given the name of the file, which should
111 * already have been opened, and a function
112 * to call to read a character from the file.
113 *
114 * Parse_IsVar Returns TRUE if the given line is a
115 * variable assignment. Used by MainParseArgs
116 * to determine if an argument is a target
117 * or a variable assignment. Used internally
118 * for pretty much the same thing...
119 *
120 * Parse_Error Function called when an error occurs in
121 * parsing. Used by the variable and
122 * conditional modules.
123 * Parse_MainName Returns a Lst of the main target to create.
124 */
125
126 #include <ctype.h>
127 #include <errno.h>
128 #include <stdarg.h>
129 #include <stdio.h>
130
131 #include "make.h"
132 #include "hash.h"
133 #include "dir.h"
134 #include "job.h"
135 #include "buf.h"
136 #include "pathnames.h"
137
138 /*
139 * These values are returned by ParseEOF to tell Parse_File whether to
140 * CONTINUE parsing, i.e. it had only reached the end of an include file,
141 * or if it's DONE.
142 */
143 #define CONTINUE 1
144 #define DONE 0
145 static Lst targets; /* targets we're working on */
146 #ifdef CLEANUP
147 static Lst targCmds; /* command lines for targets */
148 #endif
149 static Boolean inLine; /* true if currently in a dependency
150 * line or its commands */
151 typedef struct {
152 char *str;
153 char *ptr;
154 } PTR;
155
156 static int fatals = 0;
157
158 static GNode *mainNode; /* The main target to create. This is the
159 * first target on the first dependency
160 * line in the first makefile */
161 typedef struct IFile {
162 char *fname; /* name of previous file */
163 int lineno; /* saved line number */
164 FILE * F; /* the open stream */
165 PTR * P; /* the char pointer */
166 } IFile;
167
168 static IFile curFile;
169
170
171 /*
172 * Definitions for handling #include specifications
173 */
174
175 static Lst includes; /* stack of IFiles generated by
176 * #includes */
177 Lst parseIncPath; /* list of directories for "..." includes */
178 Lst sysIncPath; /* list of directories for <...> includes */
179 Lst defIncPath; /* default directories for <...> includes */
180
181 /*-
182 * specType contains the SPECial TYPE of the current target. It is
183 * Not if the target is unspecial. If it *is* special, however, the children
184 * are linked as children of the parent but not vice versa. This variable is
185 * set in ParseDoDependency
186 */
187 typedef enum {
188 Begin, /* .BEGIN */
189 Default, /* .DEFAULT */
190 End, /* .END */
191 Ignore, /* .IGNORE */
192 Includes, /* .INCLUDES */
193 Interrupt, /* .INTERRUPT */
194 Libs, /* .LIBS */
195 MFlags, /* .MFLAGS or .MAKEFLAGS */
196 Main, /* .MAIN and we don't have anything user-specified to
197 * make */
198 NoExport, /* .NOEXPORT */
199 NoPath, /* .NOPATH */
200 Not, /* Not special */
201 NotParallel, /* .NOTPARALLEL */
202 Null, /* .NULL */
203 ExObjdir, /* .OBJDIR */
204 Order, /* .ORDER */
205 Parallel, /* .PARALLEL */
206 ExPath, /* .PATH */
207 Phony, /* .PHONY */
208 #ifdef POSIX
209 Posix, /* .POSIX */
210 #endif
211 Precious, /* .PRECIOUS */
212 ExShell, /* .SHELL */
213 Silent, /* .SILENT */
214 SingleShell, /* .SINGLESHELL */
215 Suffixes, /* .SUFFIXES */
216 Wait, /* .WAIT */
217 Attribute /* Generic attribute */
218 } ParseSpecial;
219
220 static ParseSpecial specType;
221 static int waiting;
222
223 #define LPAREN '('
224 #define RPAREN ')'
225 /*
226 * Predecessor node for handling .ORDER. Initialized to NILGNODE when .ORDER
227 * seen, then set to each successive source on the line.
228 */
229 static GNode *predecessor;
230
231 /*
232 * The parseKeywords table is searched using binary search when deciding
233 * if a target or source is special. The 'spec' field is the ParseSpecial
234 * type of the keyword ("Not" if the keyword isn't special as a target) while
235 * the 'op' field is the operator to apply to the list of targets if the
236 * keyword is used as a source ("0" if the keyword isn't special as a source)
237 */
238 static struct {
239 const char *name; /* Name of keyword */
240 ParseSpecial spec; /* Type when used as a target */
241 int op; /* Operator when used as a source */
242 } parseKeywords[] = {
243 { ".BEGIN", Begin, 0 },
244 { ".DEFAULT", Default, 0 },
245 { ".END", End, 0 },
246 { ".EXEC", Attribute, OP_EXEC },
247 { ".IGNORE", Ignore, OP_IGNORE },
248 { ".INCLUDES", Includes, 0 },
249 { ".INTERRUPT", Interrupt, 0 },
250 { ".INVISIBLE", Attribute, OP_INVISIBLE },
251 { ".JOIN", Attribute, OP_JOIN },
252 { ".LIBS", Libs, 0 },
253 { ".MADE", Attribute, OP_MADE },
254 { ".MAIN", Main, 0 },
255 { ".MAKE", Attribute, OP_MAKE },
256 { ".MAKEFLAGS", MFlags, 0 },
257 { ".MFLAGS", MFlags, 0 },
258 { ".NOPATH", NoPath, OP_NOPATH },
259 { ".NOTMAIN", Attribute, OP_NOTMAIN },
260 { ".NOTPARALLEL", NotParallel, 0 },
261 { ".NO_PARALLEL", NotParallel, 0 },
262 { ".NULL", Null, 0 },
263 { ".OBJDIR", ExObjdir, 0 },
264 { ".OPTIONAL", Attribute, OP_OPTIONAL },
265 { ".ORDER", Order, 0 },
266 { ".PARALLEL", Parallel, 0 },
267 { ".PATH", ExPath, 0 },
268 { ".PHONY", Phony, OP_PHONY },
269 #ifdef POSIX
270 { ".POSIX", Posix, 0 },
271 #endif
272 { ".PRECIOUS", Precious, OP_PRECIOUS },
273 { ".RECURSIVE", Attribute, OP_MAKE },
274 { ".SHELL", ExShell, 0 },
275 { ".SILENT", Silent, OP_SILENT },
276 { ".SINGLESHELL", SingleShell, 0 },
277 { ".SUFFIXES", Suffixes, 0 },
278 { ".USE", Attribute, OP_USE },
279 { ".USEBEFORE", Attribute, OP_USEBEFORE },
280 { ".WAIT", Wait, 0 },
281 };
282
283 /*
284 * Used by ParseDoSpecialSrc()
285 */
286 typedef struct {
287 int op;
288 char *src;
289 Lst allsrc;
290 } SpecialSrc;
291
292 static int ParseIsEscaped(const char *, const char *);
293 static void ParseErrorInternal(char *, size_t, int, const char *, ...)
294 __attribute__((__format__(__printf__, 4, 5)));
295 static void ParseVErrorInternal(char *, size_t, int, const char *, va_list)
296 __attribute__((__format__(__printf__, 4, 0)));
297 static int ParseFindKeyword(char *);
298 static int ParseLinkSrc(ClientData, ClientData);
299 static int ParseDoOp(ClientData, ClientData);
300 static int ParseAddDep(ClientData, ClientData);
301 static int ParseDoSpecialSrc(ClientData, ClientData);
302 static void ParseDoSrc(int, char *, Lst, Boolean);
303 static int ParseFindMain(ClientData, ClientData);
304 static int ParseAddDir(ClientData, ClientData);
305 static int ParseClearPath(ClientData, ClientData);
306 static void ParseDoDependency(char *);
307 static int ParseAddCmd(ClientData, ClientData);
308 static inline int ParseReadc(void);
309 static void ParseUnreadc(int);
310 static void ParseHasCommands(ClientData);
311 static void ParseDoInclude(char *);
312 static void ParseSetParseFile(char *);
313 #ifdef SYSVINCLUDE
314 static void ParseTraditionalInclude(char *);
315 #endif
316 static int ParseEOF(int);
317 static char *ParseReadLine(void);
318 static char *ParseSkipLine(int, int);
319 static void ParseFinishLine(void);
320 static void ParseMark(GNode *);
321
322 extern int maxJobs;
323
324
325 /*-
326 *----------------------------------------------------------------------
327 * ParseIsEscaped --
328 * Check if the current character is escaped on the current line
329 *
330 * Results:
331 * 0 if the character is not backslash escaped, 1 otherwise
332 *
333 * Side Effects:
334 * None
335 *----------------------------------------------------------------------
336 */
337 static int
338 ParseIsEscaped(const char *line, const char *c)
339 {
340 int active = 0;
341 for (;;) {
342 if (line == c)
343 return active;
344 if (*--c != '\\')
345 return active;
346 active = !active;
347 }
348 }
349
350 /*-
351 *----------------------------------------------------------------------
352 * ParseFindKeyword --
353 * Look in the table of keywords for one matching the given string.
354 *
355 * Input:
356 * str String to find
357 *
358 * Results:
359 * The index of the keyword, or -1 if it isn't there.
360 *
361 * Side Effects:
362 * None
363 *----------------------------------------------------------------------
364 */
365 static int
366 ParseFindKeyword(char *str)
367 {
368 int start, end, cur;
369 int diff;
370
371 start = 0;
372 end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
373
374 do {
375 cur = start + ((end - start) / 2);
376 diff = strcmp(str, parseKeywords[cur].name);
377
378 if (diff == 0) {
379 return (cur);
380 } else if (diff < 0) {
381 end = cur - 1;
382 } else {
383 start = cur + 1;
384 }
385 } while (start <= end);
386 return (-1);
387 }
388
389 /*-
390 * ParseVErrorInternal --
391 * Error message abort function for parsing. Prints out the context
392 * of the error (line number and file) as well as the message with
393 * two optional arguments.
394 *
395 * Results:
396 * None
397 *
398 * Side Effects:
399 * "fatals" is incremented if the level is PARSE_FATAL.
400 */
401 /* VARARGS */
402 static void
403 ParseVErrorInternal(char *cfname, size_t clineno, int type, const char *fmt,
404 va_list ap)
405 {
406 static Boolean fatal_warning_error_printed = FALSE;
407
408 (void)fprintf(stderr, "%s: \"", progname);
409
410 if (*cfname != '/') {
411 char *cp;
412 const char *dir;
413
414 /*
415 * Nothing is more anoying than not knowing which Makefile
416 * is the culprit.
417 */
418 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
419 if (dir == NULL || *dir == '\0' ||
420 (*dir == '.' && dir[1] == '\0'))
421 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
422 if (dir == NULL)
423 dir = ".";
424
425 (void)fprintf(stderr, "%s/%s", dir, cfname);
426 } else
427 (void)fprintf(stderr, "%s", cfname);
428
429 (void)fprintf(stderr, "\" line %d: ", (int)clineno);
430 if (type == PARSE_WARNING)
431 (void)fprintf(stderr, "warning: ");
432 (void)vfprintf(stderr, fmt, ap);
433 (void)fprintf(stderr, "\n");
434 (void)fflush(stderr);
435 if (type == PARSE_FATAL || parseWarnFatal)
436 fatals += 1;
437 if (parseWarnFatal && !fatal_warning_error_printed) {
438 Error("parsing warnings being treated as errors");
439 fatal_warning_error_printed = TRUE;
440 }
441 }
442
443 /*-
444 * ParseErrorInternal --
445 * Error function
446 *
447 * Results:
448 * None
449 *
450 * Side Effects:
451 * None
452 */
453 /* VARARGS */
454 static void
455 ParseErrorInternal(char *cfname, size_t clineno, int type, const char *fmt, ...)
456 {
457 va_list ap;
458
459 va_start(ap, fmt);
460 ParseVErrorInternal(cfname, clineno, type, fmt, ap);
461 va_end(ap);
462 }
463
464 /*-
465 * Parse_Error --
466 * External interface to ParseErrorInternal; uses the default filename
467 * Line number.
468 *
469 * Results:
470 * None
471 *
472 * Side Effects:
473 * None
474 */
475 /* VARARGS */
476 void
477 Parse_Error(int type, const char *fmt, ...)
478 {
479 va_list ap;
480
481 va_start(ap, fmt);
482 ParseVErrorInternal(curFile.fname, curFile.lineno, type, fmt, ap);
483 va_end(ap);
484 }
485
486 /*-
487 *---------------------------------------------------------------------
488 * ParseLinkSrc --
489 * Link the parent node to its new child. Used in a Lst_ForEach by
490 * ParseDoDependency. If the specType isn't 'Not', the parent
491 * isn't linked as a parent of the child.
492 *
493 * Input:
494 * pgnp The parent node
495 * cgpn The child node
496 *
497 * Results:
498 * Always = 0
499 *
500 * Side Effects:
501 * New elements are added to the parents list of cgn and the
502 * children list of cgn. the unmade field of pgn is updated
503 * to reflect the additional child.
504 *---------------------------------------------------------------------
505 */
506 static int
507 ParseLinkSrc(ClientData pgnp, ClientData cgnp)
508 {
509 GNode *pgn = (GNode *)pgnp;
510 GNode *cgn = (GNode *)cgnp;
511
512 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
513 pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
514 (void)Lst_AtEnd(pgn->children, (ClientData)cgn);
515 if (specType == Not)
516 (void)Lst_AtEnd(cgn->parents, (ClientData)pgn);
517 pgn->unmade += 1;
518 if (DEBUG(PARSE)) {
519 printf("# ParseLinkSrc: added child %s - %s\n", pgn->name, cgn->name);
520 Targ_PrintNode(pgn, 0);
521 Targ_PrintNode(cgn, 0);
522 }
523 return (0);
524 }
525
526 /*-
527 *---------------------------------------------------------------------
528 * ParseDoOp --
529 * Apply the parsed operator to the given target node. Used in a
530 * Lst_ForEach call by ParseDoDependency once all targets have
531 * been found and their operator parsed. If the previous and new
532 * operators are incompatible, a major error is taken.
533 *
534 * Input:
535 * gnp The node to which the operator is to be applied
536 * opp The operator to apply
537 *
538 * Results:
539 * Always 0
540 *
541 * Side Effects:
542 * The type field of the node is altered to reflect any new bits in
543 * the op.
544 *---------------------------------------------------------------------
545 */
546 static int
547 ParseDoOp(ClientData gnp, ClientData opp)
548 {
549 GNode *gn = (GNode *)gnp;
550 int op = *(int *)opp;
551 /*
552 * If the dependency mask of the operator and the node don't match and
553 * the node has actually had an operator applied to it before, and
554 * the operator actually has some dependency information in it, complain.
555 */
556 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
557 !OP_NOP(gn->type) && !OP_NOP(op))
558 {
559 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
560 return (1);
561 }
562
563 if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
564 /*
565 * If the node was the object of a :: operator, we need to create a
566 * new instance of it for the children and commands on this dependency
567 * line. The new instance is placed on the 'cohorts' list of the
568 * initial one (note the initial one is not on its own cohorts list)
569 * and the new instance is linked to all parents of the initial
570 * instance.
571 */
572 GNode *cohort;
573
574 /*
575 * Propagate copied bits to the initial node. They'll be propagated
576 * back to the rest of the cohorts later.
577 */
578 gn->type |= op & ~OP_OPMASK;
579
580 cohort = Targ_NewGN(gn->name);
581 /*
582 * Make the cohort invisible as well to avoid duplicating it into
583 * other variables. True, parents of this target won't tend to do
584 * anything with their local variables, but better safe than
585 * sorry. (I think this is pointless now, since the relevant list
586 * traversals will no longer see this node anyway. -mycroft)
587 */
588 cohort->type = op | OP_INVISIBLE;
589 (void)Lst_AtEnd(gn->cohorts, (ClientData)cohort);
590 cohort->centurion = gn;
591 gn->unmade_cohorts += 1;
592 } else {
593 /*
594 * We don't want to nuke any previous flags (whatever they were) so we
595 * just OR the new operator into the old
596 */
597 gn->type |= op;
598 }
599
600 return (0);
601 }
602
603 /*-
604 *---------------------------------------------------------------------
605 * ParseAddDep --
606 * Check if the pair of GNodes given needs to be synchronized.
607 * This has to be when two nodes are on different sides of a
608 * .WAIT directive.
609 *
610 * Results:
611 * Returns 1 if the two targets need to be ordered, 0 otherwise.
612 * If it returns 1, the search can stop
613 *
614 * Side Effects:
615 * A dependency can be added between the two nodes.
616 *
617 *---------------------------------------------------------------------
618 */
619 static int
620 ParseAddDep(ClientData pp, ClientData sp)
621 {
622 GNode *p = (GNode *)pp;
623 GNode *s = (GNode *)sp;
624
625 if (DEBUG(PARSE))
626 printf("ParseAddDep: %p(%s):%d %p(%s):%d\n",
627 p, p->name, p->order, s, s->name, s->order);
628 if (p->order >= s->order)
629 return 1;
630
631 /*
632 * XXX: This can cause loops, and loops can cause unmade targets,
633 * but checking is tedious, and the debugging output can show the
634 * problem
635 */
636 (void)Lst_AtEnd(p->successors, (ClientData)s);
637 (void)Lst_AtEnd(s->preds, (ClientData)p);
638 if (DEBUG(PARSE)) {
639 printf("# ParseAddDep: added .WAIT dependency %s - %s\n",
640 p->name, s->name);
641 Targ_PrintNode(p, 0);
642 Targ_PrintNode(s, 0);
643 }
644 return 0;
645 }
646
647 /* -
648 *---------------------------------------------------------------------
649 * ParseDoSpecialSrc --
650 * ParseDoSrc struck an unexpanded variable in a src.
651 * The most likely reason is a src that refers to .TARGET or
652 * .PREFIX so we get called to set those for each target
653 * and then call ParseDoSrc again to do the real work.
654 *
655 * Input:
656 * tp A target GNode *
657 * sp A SpecialSrc * which contains the args we need
658 * for ParseDoSrc.
659 *
660 * Results:
661 * Goodness
662 *
663 * Side Effects:
664 * The target GNode will have .TARGET and .PREFIX set, this seems
665 * harmless.
666 */
667 static int
668 ParseDoSpecialSrc(ClientData tp, ClientData sp)
669 {
670 GNode *tn = (GNode *)tp;
671 GNode *gn;
672 SpecialSrc *ss = (SpecialSrc *)sp;
673 char *cp;
674 char *cp2;
675 char *pref;
676
677 /*
678 * If the target is a suffix rule, leave it alone.
679 */
680 if (Suff_IsTransform(tn->name)) {
681 ParseDoSrc(ss->op, ss->src, ss->allsrc, FALSE); /* don't come back */
682 return 0;
683 }
684 Var_Set(TARGET, tn->name, tn, 0);
685 if ((pref = strrchr(tn->name, '/')))
686 pref++;
687 else
688 pref = tn->name;
689 if ((cp2 = strchr(pref, '.')) > pref) {
690 cp = estrdup(pref);
691 cp[cp2 - pref] = '\0';
692 Var_Set(PREFIX, cp, tn, 0);
693 free(cp);
694 } else
695 Var_Set(PREFIX, pref, tn, 0);
696 cp = Var_Subst(NULL, ss->src, tn, FALSE);
697 if (strchr(cp, '$')) {
698 Parse_Error(PARSE_WARNING, "Cannot resolve '%s' here", ss->src);
699 ParseDoSrc(ss->op, ss->src, ss->allsrc, FALSE); /* don't come back */
700 return 1; /* stop list traversal */
701 }
702 /*
703 * We don't want to make every target dependent on sources for
704 * other targets. This is the bit of ParseDoSrc which is relevant.
705 * The main difference is we don't link the resolved src to all targets.
706 */
707 gn = Targ_FindNode(cp, TARG_CREATE);
708 if (ss->op) {
709 gn->type |= ss->op;
710 } else {
711 ParseLinkSrc((ClientData)tn, (ClientData)gn);
712 }
713 if (DEBUG(PARSE))
714 printf("ParseDoSpecialSrc: set %p(%s):%d (was %d)\n",
715 gn, gn->name, waiting, gn->order);
716 gn->order = waiting;
717 (void)Lst_AtEnd(ss->allsrc, (ClientData)gn);
718 if (waiting) {
719 Lst_ForEach(ss->allsrc, ParseAddDep, (ClientData)gn);
720 }
721 return 0;
722 }
723
724
725 /*-
726 *---------------------------------------------------------------------
727 * ParseDoSrc --
728 * Given the name of a source, figure out if it is an attribute
729 * and apply it to the targets if it is. Else decide if there is
730 * some attribute which should be applied *to* the source because
731 * of some special target and apply it if so. Otherwise, make the
732 * source be a child of the targets in the list 'targets'
733 *
734 * Input:
735 * tOp operator (if any) from special targets
736 * src name of the source to handle
737 * allsrc List of all sources to wait for
738 * resolve boolean - should we try and resolve .TARGET refs.
739 *
740 * Results:
741 * None
742 *
743 * Side Effects:
744 * Operator bits may be added to the list of targets or to the source.
745 * The targets may have a new source added to their lists of children.
746 *---------------------------------------------------------------------
747 */
748 static void
749 ParseDoSrc(int tOp, char *src, Lst allsrc, Boolean resolve)
750 {
751 GNode *gn = NULL;
752
753 if (*src == '.' && isupper ((unsigned char)src[1])) {
754 int keywd = ParseFindKeyword(src);
755 if (keywd != -1) {
756 int op = parseKeywords[keywd].op;
757 if (op != 0) {
758 Lst_ForEach(targets, ParseDoOp, (ClientData)&op);
759 return;
760 }
761 if (parseKeywords[keywd].spec == Wait) {
762 waiting++;
763 return;
764 }
765 }
766 }
767
768 switch (specType) {
769 case Main:
770 /*
771 * If we have noted the existence of a .MAIN, it means we need
772 * to add the sources of said target to the list of things
773 * to create. The string 'src' is likely to be free, so we
774 * must make a new copy of it. Note that this will only be
775 * invoked if the user didn't specify a target on the command
776 * line. This is to allow #ifmake's to succeed, or something...
777 */
778 (void)Lst_AtEnd(create, (ClientData)estrdup(src));
779 /*
780 * Add the name to the .TARGETS variable as well, so the user cna
781 * employ that, if desired.
782 */
783 Var_Append(".TARGETS", src, VAR_GLOBAL);
784 return;
785
786 case Order:
787 /*
788 * Create proper predecessor/successor links between the previous
789 * source and the current one.
790 */
791 gn = Targ_FindNode(src, TARG_CREATE);
792 if (predecessor != NILGNODE) {
793 (void)Lst_AtEnd(predecessor->successors, (ClientData)gn);
794 (void)Lst_AtEnd(gn->preds, (ClientData)predecessor);
795 if (DEBUG(PARSE)) {
796 printf("# ParseDoSrc: added Order dependency %s - %s\n",
797 predecessor->name, gn->name);
798 Targ_PrintNode(predecessor, 0);
799 Targ_PrintNode(gn, 0);
800 }
801 }
802 /*
803 * The current source now becomes the predecessor for the next one.
804 */
805 predecessor = gn;
806 break;
807
808 default:
809 /*
810 * If the source is not an attribute, we need to find/create
811 * a node for it. After that we can apply any operator to it
812 * from a special target or link it to its parents, as
813 * appropriate.
814 *
815 * In the case of a source that was the object of a :: operator,
816 * the attribute is applied to all of its instances (as kept in
817 * the 'cohorts' list of the node) or all the cohorts are linked
818 * to all the targets.
819 */
820 if (resolve && strchr(src, '$')) {
821 SpecialSrc ss;
822
823 ss.op = tOp;
824 ss.src = src;
825 ss.allsrc = allsrc;
826
827 /*
828 * If src cannot be fully resolved, we'll be called again
829 * with resolve==FALSE.
830 */
831 Lst_ForEach(targets, ParseDoSpecialSrc, (ClientData)&ss);
832 return;
833 }
834 gn = Targ_FindNode(src, TARG_CREATE);
835 if (tOp) {
836 gn->type |= tOp;
837 } else {
838 Lst_ForEach(targets, ParseLinkSrc, (ClientData)gn);
839 }
840 break;
841 }
842
843 if (DEBUG(PARSE))
844 printf("ParseDoSrc: set %p(%s):%d (was %d)\n",
845 gn, gn->name, waiting, gn->order);
846 gn->order = waiting;
847 (void)Lst_AtEnd(allsrc, (ClientData)gn);
848 if (waiting) {
849 Lst_ForEach(allsrc, ParseAddDep, (ClientData)gn);
850 }
851 }
852
853 /*-
854 *-----------------------------------------------------------------------
855 * ParseFindMain --
856 * Find a real target in the list and set it to be the main one.
857 * Called by ParseDoDependency when a main target hasn't been found
858 * yet.
859 *
860 * Input:
861 * gnp Node to examine
862 *
863 * Results:
864 * 0 if main not found yet, 1 if it is.
865 *
866 * Side Effects:
867 * mainNode is changed and Targ_SetMain is called.
868 *
869 *-----------------------------------------------------------------------
870 */
871 static int
872 ParseFindMain(ClientData gnp, ClientData dummy)
873 {
874 GNode *gn = (GNode *)gnp;
875 if ((gn->type & OP_NOTARGET) == 0) {
876 mainNode = gn;
877 Targ_SetMain(gn);
878 return (dummy ? 1 : 1);
879 } else {
880 return (dummy ? 0 : 0);
881 }
882 }
883
884 /*-
885 *-----------------------------------------------------------------------
886 * ParseAddDir --
887 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
888 *
889 * Results:
890 * === 0
891 *
892 * Side Effects:
893 * See Dir_AddDir.
894 *
895 *-----------------------------------------------------------------------
896 */
897 static int
898 ParseAddDir(ClientData path, ClientData name)
899 {
900 (void)Dir_AddDir((Lst) path, (char *)name);
901 return(0);
902 }
903
904 /*-
905 *-----------------------------------------------------------------------
906 * ParseClearPath --
907 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
908 *
909 * Results:
910 * === 0
911 *
912 * Side Effects:
913 * See Dir_ClearPath
914 *
915 *-----------------------------------------------------------------------
916 */
917 static int
918 ParseClearPath(ClientData path, ClientData dummy)
919 {
920 Dir_ClearPath((Lst) path);
921 return(dummy ? 0 : 0);
922 }
923
924 /*-
925 *---------------------------------------------------------------------
926 * ParseDoDependency --
927 * Parse the dependency line in line.
928 *
929 * Input:
930 * line the line to parse
931 *
932 * Results:
933 * None
934 *
935 * Side Effects:
936 * The nodes of the sources are linked as children to the nodes of the
937 * targets. Some nodes may be created.
938 *
939 * We parse a dependency line by first extracting words from the line and
940 * finding nodes in the list of all targets with that name. This is done
941 * until a character is encountered which is an operator character. Currently
942 * these are only ! and :. At this point the operator is parsed and the
943 * pointer into the line advanced until the first source is encountered.
944 * The parsed operator is applied to each node in the 'targets' list,
945 * which is where the nodes found for the targets are kept, by means of
946 * the ParseDoOp function.
947 * The sources are read in much the same way as the targets were except
948 * that now they are expanded using the wildcarding scheme of the C-Shell
949 * and all instances of the resulting words in the list of all targets
950 * are found. Each of the resulting nodes is then linked to each of the
951 * targets as one of its children.
952 * Certain targets are handled specially. These are the ones detailed
953 * by the specType variable.
954 * The storing of transformation rules is also taken care of here.
955 * A target is recognized as a transformation rule by calling
956 * Suff_IsTransform. If it is a transformation rule, its node is gotten
957 * from the suffix module via Suff_AddTransform rather than the standard
958 * Targ_FindNode in the target module.
959 *---------------------------------------------------------------------
960 */
961 static void
962 ParseDoDependency(char *line)
963 {
964 char *cp; /* our current position */
965 GNode *gn = NULL; /* a general purpose temporary node */
966 int op; /* the operator on the line */
967 char savec; /* a place to save a character */
968 Lst paths; /* List of search paths to alter when parsing
969 * a list of .PATH targets */
970 int tOp; /* operator from special target */
971 Lst sources; /* list of archive source names after
972 * expansion */
973 Lst curTargs; /* list of target names to be found and added
974 * to the targets list */
975 Lst curSrcs; /* list of sources in order */
976 char *lstart = line;
977 Boolean hasWait; /* is .WAIT present in srcs */
978
979 tOp = 0;
980
981 specType = Not;
982 waiting = 0;
983 paths = (Lst)NULL;
984
985 curTargs = Lst_Init(FALSE);
986 curSrcs = Lst_Init(FALSE);
987
988 do {
989 for (cp = line;
990 *cp && (ParseIsEscaped(lstart, cp) ||
991 (!isspace ((unsigned char)*cp) &&
992 (*cp != '!') && (*cp != ':') && (*cp != LPAREN)));
993 cp++)
994 {
995 if (*cp == '$') {
996 /*
997 * Must be a dynamic source (would have been expanded
998 * otherwise), so call the Var module to parse the puppy
999 * so we can safely advance beyond it...There should be
1000 * no errors in this, as they would have been discovered
1001 * in the initial Var_Subst and we wouldn't be here.
1002 */
1003 int length;
1004 Boolean freeIt;
1005 char *result;
1006
1007 result=Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
1008
1009 if (freeIt) {
1010 free(result);
1011 }
1012 cp += length-1;
1013 }
1014 continue;
1015 }
1016 if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
1017 /*
1018 * Archives must be handled specially to make sure the OP_ARCHV
1019 * flag is set in their 'type' field, for one thing, and because
1020 * things like "archive(file1.o file2.o file3.o)" are permissible.
1021 * Arch_ParseArchive will set 'line' to be the first non-blank
1022 * after the archive-spec. It creates/finds nodes for the members
1023 * and places them on the given list, returning SUCCESS if all
1024 * went well and FAILURE if there was an error in the
1025 * specification. On error, line should remain untouched.
1026 */
1027 if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
1028 Parse_Error(PARSE_FATAL,
1029 "Error in archive specification: \"%s\"", line);
1030 return;
1031 } else {
1032 continue;
1033 }
1034 }
1035 savec = *cp;
1036
1037 if (!*cp) {
1038 /*
1039 * Ending a dependency line without an operator is a Bozo
1040 * no-no. As a heuristic, this is also often triggered by
1041 * undetected conflicts from cvs/rcs merges.
1042 */
1043 if ((strncmp(line, "<<<<<<", 6) == 0) ||
1044 (strncmp(line, "======", 6) == 0) ||
1045 (strncmp(line, ">>>>>>", 6) == 0))
1046 Parse_Error(PARSE_FATAL,
1047 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1048 else
1049 Parse_Error(PARSE_FATAL, "Need an operator");
1050 return;
1051 }
1052 *cp = '\0';
1053 /*
1054 * Have a word in line. See if it's a special target and set
1055 * specType to match it.
1056 */
1057 if (*line == '.' && isupper ((unsigned char)line[1])) {
1058 /*
1059 * See if the target is a special target that must have it
1060 * or its sources handled specially.
1061 */
1062 int keywd = ParseFindKeyword(line);
1063 if (keywd != -1) {
1064 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1065 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1066 return;
1067 }
1068
1069 specType = parseKeywords[keywd].spec;
1070 tOp = parseKeywords[keywd].op;
1071
1072 /*
1073 * Certain special targets have special semantics:
1074 * .PATH Have to set the dirSearchPath
1075 * variable too
1076 * .MAIN Its sources are only used if
1077 * nothing has been specified to
1078 * create.
1079 * .DEFAULT Need to create a node to hang
1080 * commands on, but we don't want
1081 * it in the graph, nor do we want
1082 * it to be the Main Target, so we
1083 * create it, set OP_NOTMAIN and
1084 * add it to the list, setting
1085 * DEFAULT to the new node for
1086 * later use. We claim the node is
1087 * A transformation rule to make
1088 * life easier later, when we'll
1089 * use Make_HandleUse to actually
1090 * apply the .DEFAULT commands.
1091 * .PHONY The list of targets
1092 * .NOPATH Don't search for file in the path
1093 * .BEGIN
1094 * .END
1095 * .INTERRUPT Are not to be considered the
1096 * main target.
1097 * .NOTPARALLEL Make only one target at a time.
1098 * .SINGLESHELL Create a shell for each command.
1099 * .ORDER Must set initial predecessor to NIL
1100 */
1101 switch (specType) {
1102 case ExPath:
1103 if (paths == NULL) {
1104 paths = Lst_Init(FALSE);
1105 }
1106 (void)Lst_AtEnd(paths, (ClientData)dirSearchPath);
1107 break;
1108 case Main:
1109 if (!Lst_IsEmpty(create)) {
1110 specType = Not;
1111 }
1112 break;
1113 case Begin:
1114 case End:
1115 case Interrupt:
1116 gn = Targ_FindNode(line, TARG_CREATE);
1117 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1118 (void)Lst_AtEnd(targets, (ClientData)gn);
1119 break;
1120 case Default:
1121 gn = Targ_NewGN(".DEFAULT");
1122 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1123 (void)Lst_AtEnd(targets, (ClientData)gn);
1124 DEFAULT = gn;
1125 break;
1126 case NotParallel:
1127 not_parallel = 1;
1128 break;
1129 case SingleShell:
1130 compatMake = TRUE;
1131 break;
1132 case Order:
1133 predecessor = NILGNODE;
1134 break;
1135 default:
1136 break;
1137 }
1138 } else if (strncmp(line, ".PATH", 5) == 0) {
1139 /*
1140 * .PATH<suffix> has to be handled specially.
1141 * Call on the suffix module to give us a path to
1142 * modify.
1143 */
1144 Lst path;
1145
1146 specType = ExPath;
1147 path = Suff_GetPath(&line[5]);
1148 if (path == NILLST) {
1149 Parse_Error(PARSE_FATAL,
1150 "Suffix '%s' not defined (yet)",
1151 &line[5]);
1152 return;
1153 } else {
1154 if (paths == (Lst)NULL) {
1155 paths = Lst_Init(FALSE);
1156 }
1157 (void)Lst_AtEnd(paths, (ClientData)path);
1158 }
1159 }
1160 }
1161
1162 /*
1163 * Have word in line. Get or create its node and stick it at
1164 * the end of the targets list
1165 */
1166 if ((specType == Not) && (*line != '\0')) {
1167 if (Dir_HasWildcards(line)) {
1168 /*
1169 * Targets are to be sought only in the current directory,
1170 * so create an empty path for the thing. Note we need to
1171 * use Dir_Destroy in the destruction of the path as the
1172 * Dir module could have added a directory to the path...
1173 */
1174 Lst emptyPath = Lst_Init(FALSE);
1175
1176 Dir_Expand(line, emptyPath, curTargs);
1177
1178 Lst_Destroy(emptyPath, Dir_Destroy);
1179 } else {
1180 /*
1181 * No wildcards, but we want to avoid code duplication,
1182 * so create a list with the word on it.
1183 */
1184 (void)Lst_AtEnd(curTargs, (ClientData)line);
1185 }
1186
1187 while(!Lst_IsEmpty(curTargs)) {
1188 char *targName = (char *)Lst_DeQueue(curTargs);
1189
1190 if (!Suff_IsTransform (targName)) {
1191 gn = Targ_FindNode(targName, TARG_CREATE);
1192 } else {
1193 gn = Suff_AddTransform(targName);
1194 }
1195
1196 (void)Lst_AtEnd(targets, (ClientData)gn);
1197 }
1198 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1199 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1200 }
1201
1202 *cp = savec;
1203 /*
1204 * If it is a special type and not .PATH, it's the only target we
1205 * allow on this line...
1206 */
1207 if (specType != Not && specType != ExPath) {
1208 Boolean warn = FALSE;
1209
1210 while (*cp && (ParseIsEscaped(lstart, cp) ||
1211 ((*cp != '!') && (*cp != ':')))) {
1212 if (ParseIsEscaped(lstart, cp) ||
1213 (*cp != ' ' && *cp != '\t')) {
1214 warn = TRUE;
1215 }
1216 cp++;
1217 }
1218 if (warn) {
1219 Parse_Error(PARSE_WARNING, "Extra target ignored");
1220 }
1221 } else {
1222 while (*cp && isspace ((unsigned char)*cp)) {
1223 cp++;
1224 }
1225 }
1226 line = cp;
1227 } while (*line && (ParseIsEscaped(lstart, line) ||
1228 ((*line != '!') && (*line != ':'))));
1229
1230 /*
1231 * Don't need the list of target names anymore...
1232 */
1233 Lst_Destroy(curTargs, NOFREE);
1234
1235 if (!Lst_IsEmpty(targets)) {
1236 switch(specType) {
1237 default:
1238 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1239 break;
1240 case Default:
1241 case Begin:
1242 case End:
1243 case Interrupt:
1244 /*
1245 * These four create nodes on which to hang commands, so
1246 * targets shouldn't be empty...
1247 */
1248 case Not:
1249 /*
1250 * Nothing special here -- targets can be empty if it wants.
1251 */
1252 break;
1253 }
1254 }
1255
1256 /*
1257 * Have now parsed all the target names. Must parse the operator next. The
1258 * result is left in op .
1259 */
1260 if (*cp == '!') {
1261 op = OP_FORCE;
1262 } else if (*cp == ':') {
1263 if (cp[1] == ':') {
1264 op = OP_DOUBLEDEP;
1265 cp++;
1266 } else {
1267 op = OP_DEPENDS;
1268 }
1269 } else {
1270 Parse_Error(PARSE_FATAL, "Missing dependency operator");
1271 return;
1272 }
1273
1274 cp++; /* Advance beyond operator */
1275
1276 Lst_ForEach(targets, ParseDoOp, (ClientData)&op);
1277
1278 /*
1279 * Get to the first source
1280 */
1281 while (*cp && isspace ((unsigned char)*cp)) {
1282 cp++;
1283 }
1284 line = cp;
1285
1286 /*
1287 * Several special targets take different actions if present with no
1288 * sources:
1289 * a .SUFFIXES line with no sources clears out all old suffixes
1290 * a .PRECIOUS line makes all targets precious
1291 * a .IGNORE line ignores errors for all targets
1292 * a .SILENT line creates silence when making all targets
1293 * a .PATH removes all directories from the search path(s).
1294 */
1295 if (!*line) {
1296 switch (specType) {
1297 case Suffixes:
1298 Suff_ClearSuffixes();
1299 break;
1300 case Precious:
1301 allPrecious = TRUE;
1302 break;
1303 case Ignore:
1304 ignoreErrors = TRUE;
1305 break;
1306 case Silent:
1307 beSilent = TRUE;
1308 break;
1309 case ExPath:
1310 Lst_ForEach(paths, ParseClearPath, (ClientData)NULL);
1311 Dir_SetPATH();
1312 break;
1313 #ifdef POSIX
1314 case Posix:
1315 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1316 break;
1317 #endif
1318 default:
1319 break;
1320 }
1321 } else if (specType == MFlags) {
1322 /*
1323 * Call on functions in main.c to deal with these arguments and
1324 * set the initial character to a null-character so the loop to
1325 * get sources won't get anything
1326 */
1327 Main_ParseArgLine(line);
1328 *line = '\0';
1329 } else if (specType == ExShell) {
1330 if (Job_ParseShell(line) != SUCCESS) {
1331 Parse_Error(PARSE_FATAL, "improper shell specification");
1332 return;
1333 }
1334 *line = '\0';
1335 } else if ((specType == NotParallel) || (specType == SingleShell)) {
1336 *line = '\0';
1337 }
1338
1339 /*
1340 * NOW GO FOR THE SOURCES
1341 */
1342 if ((specType == Suffixes) || (specType == ExPath) ||
1343 (specType == Includes) || (specType == Libs) ||
1344 (specType == Null) || (specType == ExObjdir))
1345 {
1346 while (*line) {
1347 /*
1348 * If the target was one that doesn't take files as its sources
1349 * but takes something like suffixes, we take each
1350 * space-separated word on the line as a something and deal
1351 * with it accordingly.
1352 *
1353 * If the target was .SUFFIXES, we take each source as a
1354 * suffix and add it to the list of suffixes maintained by the
1355 * Suff module.
1356 *
1357 * If the target was a .PATH, we add the source as a directory
1358 * to search on the search path.
1359 *
1360 * If it was .INCLUDES, the source is taken to be the suffix of
1361 * files which will be #included and whose search path should
1362 * be present in the .INCLUDES variable.
1363 *
1364 * If it was .LIBS, the source is taken to be the suffix of
1365 * files which are considered libraries and whose search path
1366 * should be present in the .LIBS variable.
1367 *
1368 * If it was .NULL, the source is the suffix to use when a file
1369 * has no valid suffix.
1370 *
1371 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1372 * and will cause make to do a new chdir to that path.
1373 */
1374 while (*cp && !isspace ((unsigned char)*cp)) {
1375 cp++;
1376 }
1377 savec = *cp;
1378 *cp = '\0';
1379 switch (specType) {
1380 case Suffixes:
1381 Suff_AddSuffix(line, &mainNode);
1382 break;
1383 case ExPath:
1384 Lst_ForEach(paths, ParseAddDir, (ClientData)line);
1385 break;
1386 case Includes:
1387 Suff_AddInclude(line);
1388 break;
1389 case Libs:
1390 Suff_AddLib(line);
1391 break;
1392 case Null:
1393 Suff_SetNull(line);
1394 break;
1395 case ExObjdir:
1396 Main_SetObjdir(line);
1397 break;
1398 default:
1399 break;
1400 }
1401 *cp = savec;
1402 if (savec != '\0') {
1403 cp++;
1404 }
1405 while (*cp && isspace ((unsigned char)*cp)) {
1406 cp++;
1407 }
1408 line = cp;
1409 }
1410 if (paths) {
1411 Lst_Destroy(paths, NOFREE);
1412 }
1413 if (specType == ExPath)
1414 Dir_SetPATH();
1415 } else {
1416 /*
1417 * We don't need ParseDoSpecialSrc unless .WAIT is present.
1418 */
1419 hasWait = (strstr(line, ".WAIT") != NULL);
1420
1421 while (*line) {
1422 /*
1423 * The targets take real sources, so we must beware of archive
1424 * specifications (i.e. things with left parentheses in them)
1425 * and handle them accordingly.
1426 */
1427 while (*cp && !isspace ((unsigned char)*cp)) {
1428 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1429 /*
1430 * Only stop for a left parenthesis if it isn't at the
1431 * start of a word (that'll be for variable changes
1432 * later) and isn't preceded by a dollar sign (a dynamic
1433 * source).
1434 */
1435 break;
1436 } else {
1437 cp++;
1438 }
1439 }
1440
1441 if (*cp == LPAREN) {
1442 sources = Lst_Init(FALSE);
1443 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1444 Parse_Error(PARSE_FATAL,
1445 "Error in source archive spec \"%s\"", line);
1446 return;
1447 }
1448
1449 while (!Lst_IsEmpty (sources)) {
1450 gn = (GNode *)Lst_DeQueue(sources);
1451 ParseDoSrc(tOp, gn->name, curSrcs, hasWait);
1452 }
1453 Lst_Destroy(sources, NOFREE);
1454 cp = line;
1455 } else {
1456 if (*cp) {
1457 *cp = '\0';
1458 cp += 1;
1459 }
1460
1461 ParseDoSrc(tOp, line, curSrcs, hasWait);
1462 }
1463 while (*cp && isspace ((unsigned char)*cp)) {
1464 cp++;
1465 }
1466 line = cp;
1467 }
1468 }
1469
1470 if (mainNode == NILGNODE) {
1471 /*
1472 * If we have yet to decide on a main target to make, in the
1473 * absence of any user input, we want the first target on
1474 * the first dependency line that is actually a real target
1475 * (i.e. isn't a .USE or .EXEC rule) to be made.
1476 */
1477 Lst_ForEach(targets, ParseFindMain, (ClientData)0);
1478 }
1479
1480 /*
1481 * Finally, destroy the list of sources
1482 */
1483 Lst_Destroy(curSrcs, NOFREE);
1484 }
1485
1486 /*-
1487 *---------------------------------------------------------------------
1488 * Parse_IsVar --
1489 * Return TRUE if the passed line is a variable assignment. A variable
1490 * assignment consists of a single word followed by optional whitespace
1491 * followed by either a += or an = operator.
1492 * This function is used both by the Parse_File function and main when
1493 * parsing the command-line arguments.
1494 *
1495 * Input:
1496 * line the line to check
1497 *
1498 * Results:
1499 * TRUE if it is. FALSE if it ain't
1500 *
1501 * Side Effects:
1502 * none
1503 *---------------------------------------------------------------------
1504 */
1505 Boolean
1506 Parse_IsVar(char *line)
1507 {
1508 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1509 Boolean haveName = FALSE; /* Set TRUE if have a variable name */
1510 int level = 0;
1511 #define ISEQOPERATOR(c) \
1512 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1513
1514 /*
1515 * Skip to variable name
1516 */
1517 for (;(*line == ' ') || (*line == '\t'); line++)
1518 continue;
1519
1520 for (; *line != '=' || level != 0; line++)
1521 switch (*line) {
1522 case '\0':
1523 /*
1524 * end-of-line -- can't be a variable assignment.
1525 */
1526 return FALSE;
1527
1528 case ' ':
1529 case '\t':
1530 /*
1531 * there can be as much white space as desired so long as there is
1532 * only one word before the operator
1533 */
1534 wasSpace = TRUE;
1535 break;
1536
1537 case LPAREN:
1538 case '{':
1539 level++;
1540 break;
1541
1542 case '}':
1543 case RPAREN:
1544 level--;
1545 break;
1546
1547 default:
1548 if (wasSpace && haveName) {
1549 if (ISEQOPERATOR(*line)) {
1550 /*
1551 * We must have a finished word
1552 */
1553 if (level != 0)
1554 return FALSE;
1555
1556 /*
1557 * When an = operator [+?!:] is found, the next
1558 * character must be an = or it ain't a valid
1559 * assignment.
1560 */
1561 if (line[1] == '=')
1562 return haveName;
1563 #ifdef SUNSHCMD
1564 /*
1565 * This is a shell command
1566 */
1567 if (strncmp(line, ":sh", 3) == 0)
1568 return haveName;
1569 #endif
1570 }
1571 /*
1572 * This is the start of another word, so not assignment.
1573 */
1574 return FALSE;
1575 }
1576 else {
1577 haveName = TRUE;
1578 wasSpace = FALSE;
1579 }
1580 break;
1581 }
1582
1583 return haveName;
1584 }
1585
1586 /*-
1587 *---------------------------------------------------------------------
1588 * Parse_DoVar --
1589 * Take the variable assignment in the passed line and do it in the
1590 * global context.
1591 *
1592 * Note: There is a lexical ambiguity with assignment modifier characters
1593 * in variable names. This routine interprets the character before the =
1594 * as a modifier. Therefore, an assignment like
1595 * C++=/usr/bin/CC
1596 * is interpreted as "C+ +=" instead of "C++ =".
1597 *
1598 * Input:
1599 * line a line guaranteed to be a variable assignment.
1600 * This reduces error checks
1601 * ctxt Context in which to do the assignment
1602 *
1603 * Results:
1604 * none
1605 *
1606 * Side Effects:
1607 * the variable structure of the given variable name is altered in the
1608 * global context.
1609 *---------------------------------------------------------------------
1610 */
1611 void
1612 Parse_DoVar(char *line, GNode *ctxt)
1613 {
1614 char *cp; /* pointer into line */
1615 enum {
1616 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1617 } type; /* Type of assignment */
1618 char *opc; /* ptr to operator character to
1619 * null-terminate the variable name */
1620 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1621 * i.e. if any variable expansion was
1622 * performed */
1623 /*
1624 * Avoid clobbered variable warnings by forcing the compiler
1625 * to ``unregister'' variables
1626 */
1627 #if __GNUC__
1628 (void) &cp;
1629 (void) &line;
1630 #endif
1631
1632 /*
1633 * Skip to variable name
1634 */
1635 while ((*line == ' ') || (*line == '\t')) {
1636 line++;
1637 }
1638
1639 /*
1640 * Skip to operator character, nulling out whitespace as we go
1641 */
1642 for (cp = line + 1; *cp != '='; cp++) {
1643 if (isspace ((unsigned char)*cp)) {
1644 *cp = '\0';
1645 }
1646 }
1647 opc = cp-1; /* operator is the previous character */
1648 *cp++ = '\0'; /* nuke the = */
1649
1650 /*
1651 * Check operator type
1652 */
1653 switch (*opc) {
1654 case '+':
1655 type = VAR_APPEND;
1656 *opc = '\0';
1657 break;
1658
1659 case '?':
1660 /*
1661 * If the variable already has a value, we don't do anything.
1662 */
1663 *opc = '\0';
1664 if (Var_Exists(line, ctxt)) {
1665 return;
1666 } else {
1667 type = VAR_NORMAL;
1668 }
1669 break;
1670
1671 case ':':
1672 type = VAR_SUBST;
1673 *opc = '\0';
1674 break;
1675
1676 case '!':
1677 type = VAR_SHELL;
1678 *opc = '\0';
1679 break;
1680
1681 default:
1682 #ifdef SUNSHCMD
1683 while (opc > line && *opc != ':')
1684 opc--;
1685
1686 if (strncmp(opc, ":sh", 3) == 0) {
1687 type = VAR_SHELL;
1688 *opc = '\0';
1689 break;
1690 }
1691 #endif
1692 type = VAR_NORMAL;
1693 break;
1694 }
1695
1696 while (isspace ((unsigned char)*cp)) {
1697 cp++;
1698 }
1699
1700 if (type == VAR_APPEND) {
1701 Var_Append(line, cp, ctxt);
1702 } else if (type == VAR_SUBST) {
1703 /*
1704 * Allow variables in the old value to be undefined, but leave their
1705 * invocation alone -- this is done by forcing oldVars to be false.
1706 * XXX: This can cause recursive variables, but that's not hard to do,
1707 * and this allows someone to do something like
1708 *
1709 * CFLAGS = $(.INCLUDES)
1710 * CFLAGS := -I.. $(CFLAGS)
1711 *
1712 * And not get an error.
1713 */
1714 Boolean oldOldVars = oldVars;
1715
1716 oldVars = FALSE;
1717
1718 /*
1719 * make sure that we set the variable the first time to nothing
1720 * so that it gets substituted!
1721 */
1722 if (!Var_Exists(line, ctxt))
1723 Var_Set(line, "", ctxt, 0);
1724
1725 cp = Var_Subst(NULL, cp, ctxt, FALSE);
1726 oldVars = oldOldVars;
1727 freeCp = TRUE;
1728
1729 Var_Set(line, cp, ctxt, 0);
1730 } else if (type == VAR_SHELL) {
1731 char *res;
1732 const char *err;
1733
1734 if (strchr(cp, '$') != NULL) {
1735 /*
1736 * There's a dollar sign in the command, so perform variable
1737 * expansion on the whole thing. The resulting string will need
1738 * freeing when we're done, so set freeCmd to TRUE.
1739 */
1740 cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1741 freeCp = TRUE;
1742 }
1743
1744 res = Cmd_Exec(cp, &err);
1745 Var_Set(line, res, ctxt, 0);
1746 free(res);
1747
1748 if (err)
1749 Parse_Error(PARSE_WARNING, err, cp);
1750 } else {
1751 /*
1752 * Normal assignment -- just do it.
1753 */
1754 Var_Set(line, cp, ctxt, 0);
1755 }
1756 if (strcmp(line, MAKEOVERRIDES) == 0)
1757 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1758 else if (strcmp(line, ".CURDIR") == 0) {
1759 /*
1760 * Somone is being (too?) clever...
1761 * Let's pretend they know what they are doing and
1762 * re-initialize the 'cur' Path.
1763 */
1764 Dir_InitCur(cp);
1765 Dir_SetPATH();
1766 }
1767 if (freeCp)
1768 free(cp);
1769 }
1770
1771
1772 /*-
1773 * ParseAddCmd --
1774 * Lst_ForEach function to add a command line to all targets
1775 *
1776 * Input:
1777 * gnp the node to which the command is to be added
1778 * cmd the command to add
1779 *
1780 * Results:
1781 * Always 0
1782 *
1783 * Side Effects:
1784 * A new element is added to the commands list of the node.
1785 */
1786 static int
1787 ParseAddCmd(ClientData gnp, ClientData cmd)
1788 {
1789 GNode *gn = (GNode *)gnp;
1790 /* if target already supplied, ignore commands */
1791 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1792 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1793 if (!(gn->type & OP_HAS_COMMANDS)) {
1794 (void)Lst_AtEnd(gn->commands, cmd);
1795 ParseMark(gn);
1796 } else {
1797 #ifdef notyet
1798 /* XXX: We cannot do this until we fix the tree */
1799 (void)Lst_AtEnd(gn->commands, cmd);
1800 Parse_Error(PARSE_WARNING,
1801 "overriding commands for target \"%s\"; "
1802 "previous commands defined at %s: %d ignored",
1803 gn->name, gn->fname, gn->lineno);
1804 #else
1805 Parse_Error(PARSE_WARNING,
1806 "duplicate script for target \"%s\" ignored",
1807 gn->name);
1808 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1809 "using previous script for \"%s\" defined here",
1810 gn->name);
1811 #endif
1812 }
1813 return(0);
1814 }
1815
1816 /*-
1817 *-----------------------------------------------------------------------
1818 * ParseHasCommands --
1819 * Callback procedure for Parse_File when destroying the list of
1820 * targets on the last dependency line. Marks a target as already
1821 * having commands if it does, to keep from having shell commands
1822 * on multiple dependency lines.
1823 *
1824 * Input:
1825 * gnp Node to examine
1826 *
1827 * Results:
1828 * None
1829 *
1830 * Side Effects:
1831 * OP_HAS_COMMANDS may be set for the target.
1832 *
1833 *-----------------------------------------------------------------------
1834 */
1835 static void
1836 ParseHasCommands(ClientData gnp)
1837 {
1838 GNode *gn = (GNode *)gnp;
1839 if (!Lst_IsEmpty(gn->commands)) {
1840 gn->type |= OP_HAS_COMMANDS;
1841 }
1842 }
1843
1844 /*-
1845 *-----------------------------------------------------------------------
1846 * Parse_AddIncludeDir --
1847 * Add a directory to the path searched for included makefiles
1848 * bracketed by double-quotes. Used by functions in main.c
1849 *
1850 * Input:
1851 * dir The name of the directory to add
1852 *
1853 * Results:
1854 * None.
1855 *
1856 * Side Effects:
1857 * The directory is appended to the list.
1858 *
1859 *-----------------------------------------------------------------------
1860 */
1861 void
1862 Parse_AddIncludeDir(char *dir)
1863 {
1864 (void)Dir_AddDir(parseIncPath, dir);
1865 }
1866
1867 /*-
1868 *---------------------------------------------------------------------
1869 * ParseDoInclude --
1870 * Push to another file.
1871 *
1872 * The input is the line minus the `.'. A file spec is a string
1873 * enclosed in <> or "". The former is looked for only in sysIncPath.
1874 * The latter in . and the directories specified by -I command line
1875 * options
1876 *
1877 * Results:
1878 * None
1879 *
1880 * Side Effects:
1881 * A structure is added to the includes Lst and readProc, lineno,
1882 * fname and curFILE are altered for the new file
1883 *---------------------------------------------------------------------
1884 */
1885 static void
1886 ParseDoInclude(char *line)
1887 {
1888 char *fullname; /* full pathname of file */
1889 IFile *oldFile; /* state associated with current file */
1890 char endc; /* the character which ends the file spec */
1891 char *cp; /* current position in file spec */
1892 Boolean isSystem; /* TRUE if makefile is a system makefile */
1893 int silent = (*line != 'i') ? 1 : 0;
1894 char *file = &line[7 + silent];
1895
1896 /*
1897 * Skip to delimiter character so we know where to look
1898 */
1899 while ((*file == ' ') || (*file == '\t')) {
1900 file++;
1901 }
1902
1903 if ((*file != '"') && (*file != '<')) {
1904 Parse_Error(PARSE_FATAL,
1905 ".include filename must be delimited by '\"' or '<'");
1906 return;
1907 }
1908
1909 /*
1910 * Set the search path on which to find the include file based on the
1911 * characters which bracket its name. Angle-brackets imply it's
1912 * a system Makefile while double-quotes imply it's a user makefile
1913 */
1914 if (*file == '<') {
1915 isSystem = TRUE;
1916 endc = '>';
1917 } else {
1918 isSystem = FALSE;
1919 endc = '"';
1920 }
1921
1922 /*
1923 * Skip to matching delimiter
1924 */
1925 for (cp = ++file; *cp && *cp != endc; cp++) {
1926 continue;
1927 }
1928
1929 if (*cp != endc) {
1930 Parse_Error(PARSE_FATAL,
1931 "Unclosed %cinclude filename. '%c' expected",
1932 '.', endc);
1933 return;
1934 }
1935 *cp = '\0';
1936
1937 /*
1938 * Substitute for any variables in the file name before trying to
1939 * find the thing.
1940 */
1941 file = Var_Subst(NULL, file, VAR_CMD, FALSE);
1942
1943 /*
1944 * Now we know the file's name and its search path, we attempt to
1945 * find the durn thing. A return of NULL indicates the file don't
1946 * exist.
1947 */
1948 fullname = NULL;
1949
1950 if (!isSystem) {
1951 /*
1952 * Include files contained in double-quotes are first searched for
1953 * relative to the including file's location. We don't want to
1954 * cd there, of course, so we just tack on the old file's
1955 * leading path components and call Dir_FindFile to see if
1956 * we can locate the beast.
1957 */
1958 char *prefEnd, *Fname;
1959
1960 /* Make a temporary copy of this, to be safe. */
1961 Fname = estrdup(curFile.fname);
1962
1963 prefEnd = strrchr(Fname, '/');
1964 if (prefEnd != NULL) {
1965 char *newName;
1966
1967 *prefEnd = '\0';
1968 if (file[0] == '/')
1969 newName = estrdup(file);
1970 else
1971 newName = str_concat(Fname, file, STR_ADDSLASH);
1972 fullname = Dir_FindFile(newName, parseIncPath);
1973 if (fullname == NULL) {
1974 fullname = Dir_FindFile(newName, dirSearchPath);
1975 }
1976 free(newName);
1977 *prefEnd = '/';
1978 } else {
1979 fullname = NULL;
1980 }
1981 free(Fname);
1982 if (fullname == NULL) {
1983 /*
1984 * Makefile wasn't found in same directory as included makefile.
1985 * Search for it first on the -I search path,
1986 * then on the .PATH search path, if not found in a -I directory.
1987 * XXX: Suffix specific?
1988 */
1989 fullname = Dir_FindFile(file, parseIncPath);
1990 if (fullname == NULL) {
1991 fullname = Dir_FindFile(file, dirSearchPath);
1992 }
1993 }
1994 }
1995
1996 /* Looking for a system file or file still not found */
1997 if (fullname == NULL) {
1998 /*
1999 * Look for it on the system path
2000 */
2001 fullname = Dir_FindFile(file, Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2002 }
2003
2004 if (fullname == NULL) {
2005 *cp = endc;
2006 if (!silent)
2007 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2008 return;
2009 }
2010
2011 free(file);
2012
2013 /*
2014 * Once we find the absolute path to the file, we get to save all the
2015 * state from the current file before we can start reading this
2016 * include file. The state is stored in an IFile structure which
2017 * is placed on a list with other IFile structures. The list makes
2018 * a very nice stack to track how we got here...
2019 */
2020 oldFile = emalloc(sizeof(IFile));
2021
2022 memcpy(oldFile, &curFile, sizeof(IFile));
2023
2024 (void)Lst_AtFront(includes, (ClientData)oldFile);
2025
2026 /*
2027 * Once the previous state has been saved, we can get down to reading
2028 * the new file. We set up the name of the file to be the absolute
2029 * name of the include file so error messages refer to the right
2030 * place. Naturally enough, we start reading at line number 0.
2031 */
2032 curFile.fname = fullname;
2033 curFile.lineno = 0;
2034
2035 ParseSetParseFile(curFile.fname);
2036
2037 curFile.F = fopen(fullname, "r");
2038 curFile.P = NULL;
2039
2040 if (curFile.F == (FILE * ) NULL) {
2041 if (!silent)
2042 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2043 /*
2044 * Pop to previous file
2045 */
2046 (void)ParseEOF(0);
2047 }
2048 }
2049
2050
2051 /*-
2052 *---------------------------------------------------------------------
2053 * ParseSetParseFile --
2054 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2055 * basename of the given filename
2056 *
2057 * Results:
2058 * None
2059 *
2060 * Side Effects:
2061 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
2062 * dirname and basename of the given filename.
2063 *---------------------------------------------------------------------
2064 */
2065 static void
2066 ParseSetParseFile(char *filename)
2067 {
2068 char *slash;
2069
2070 slash = strrchr(filename, '/');
2071 if (slash == 0) {
2072 Var_Set(".PARSEDIR", ".", VAR_GLOBAL, 0);
2073 Var_Set(".PARSEFILE", filename, VAR_GLOBAL, 0);
2074 } else {
2075 *slash = '\0';
2076 Var_Set(".PARSEDIR", filename, VAR_GLOBAL, 0);
2077 Var_Set(".PARSEFILE", slash+1, VAR_GLOBAL, 0);
2078 *slash = '/';
2079 }
2080 }
2081
2082
2083 /*-
2084 *---------------------------------------------------------------------
2085 * Parse_FromString --
2086 * Start Parsing from the given string
2087 *
2088 * Results:
2089 * None
2090 *
2091 * Side Effects:
2092 * A structure is added to the includes Lst and readProc, lineno,
2093 * fname and curFILE are altered for the new file
2094 *---------------------------------------------------------------------
2095 */
2096 void
2097 Parse_FromString(char *str, int lineno)
2098 {
2099 IFile *oldFile; /* state associated with this file */
2100
2101 if (DEBUG(FOR))
2102 (void)fprintf(stderr, "%s\n---- at line %d\n", str, lineno);
2103
2104 oldFile = emalloc(sizeof(IFile));
2105 memcpy(oldFile, &curFile, sizeof(IFile));
2106
2107 (void)Lst_AtFront(includes, (ClientData)oldFile);
2108
2109 curFile.F = NULL;
2110 curFile.P = emalloc(sizeof(PTR));
2111 curFile.P->str = curFile.P->ptr = str;
2112 curFile.lineno = lineno;
2113 curFile.fname = estrdup(curFile.fname);
2114 }
2115
2116
2117 #ifdef SYSVINCLUDE
2118 /*-
2119 *---------------------------------------------------------------------
2120 * ParseTraditionalInclude --
2121 * Push to another file.
2122 *
2123 * The input is the current line. The file name(s) are
2124 * following the "include".
2125 *
2126 * Results:
2127 * None
2128 *
2129 * Side Effects:
2130 * A structure is added to the includes Lst and readProc, lineno,
2131 * fname and curFILE are altered for the new file
2132 *---------------------------------------------------------------------
2133 */
2134 static void
2135 ParseTraditionalInclude(char *line)
2136 {
2137 char *fullname; /* full pathname of file */
2138 IFile *oldFile; /* state associated with current file */
2139 char *cp; /* current position in file spec */
2140 char *prefEnd;
2141 int done = 0;
2142 int silent = (line[0] != 'i') ? 1 : 0;
2143 char *file = &line[silent + 7];
2144 char *cfname;
2145 size_t clineno;
2146
2147 cfname = curFile.fname;
2148 clineno = curFile.lineno;
2149
2150 /*
2151 * Skip over whitespace
2152 */
2153 while (isspace((unsigned char)*file))
2154 file++;
2155
2156 if (*file == '\0') {
2157 Parse_Error(PARSE_FATAL,
2158 "Filename missing from \"include\"");
2159 return;
2160 }
2161
2162 for (; !done; file = cp + 1) {
2163 /*
2164 * Skip to end of line or next whitespace
2165 */
2166 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2167 continue;
2168
2169 if (*cp)
2170 *cp = '\0';
2171 else
2172 done = 1;
2173
2174 /*
2175 * Substitute for any variables in the file name before trying to
2176 * find the thing.
2177 */
2178 file = Var_Subst(NULL, file, VAR_CMD, FALSE);
2179
2180 /*
2181 * Now we know the file's name, we attempt to find the durn thing.
2182 * A return of NULL indicates the file don't exist.
2183 *
2184 * Include files are first searched for relative to the including
2185 * file's location. We don't want to cd there, of course, so we
2186 * just tack on the old file's leading path components and call
2187 * Dir_FindFile to see if we can locate the beast.
2188 * XXX - this *does* search in the current directory, right?
2189 */
2190
2191 prefEnd = strrchr(cfname, '/');
2192 if (prefEnd != NULL) {
2193 char *newName;
2194
2195 *prefEnd = '\0';
2196 newName = str_concat(cfname, file, STR_ADDSLASH);
2197 fullname = Dir_FindFile(newName, parseIncPath);
2198 if (fullname == NULL) {
2199 fullname = Dir_FindFile(newName, dirSearchPath);
2200 }
2201 free(newName);
2202 *prefEnd = '/';
2203 } else {
2204 fullname = NULL;
2205 }
2206
2207 if (fullname == NULL) {
2208 /*
2209 * System makefile or makefile wasn't found in same directory as
2210 * included makefile. Search for it first on the -I search path,
2211 * then on the .PATH search path, if not found in a
2212 * -I directory. XXX: Suffix specific?
2213 */
2214 fullname = Dir_FindFile(file, parseIncPath);
2215 if (fullname == NULL) {
2216 fullname = Dir_FindFile(file, dirSearchPath);
2217 }
2218 }
2219
2220 if (fullname == NULL) {
2221 /*
2222 * Still haven't found the makefile. Look for it on the system
2223 * path as a last resort.
2224 */
2225 fullname = Dir_FindFile(file,
2226 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2227 }
2228
2229 if (fullname == NULL) {
2230 if (!silent)
2231 ParseErrorInternal(cfname, clineno, PARSE_FATAL,
2232 "Could not find %s", file);
2233 free(file);
2234 continue;
2235 }
2236
2237 free(file);
2238
2239 /*
2240 * Once we find the absolute path to the file, we get to save all
2241 * the state from the current file before we can start reading this
2242 * include file. The state is stored in an IFile structure which
2243 * is placed on a list with other IFile structures. The list makes
2244 * a very nice stack to track how we got here...
2245 */
2246 oldFile = emalloc(sizeof(IFile));
2247 memcpy(oldFile, &curFile, sizeof(IFile));
2248
2249 (void)Lst_AtFront(includes, (ClientData)oldFile);
2250
2251 /*
2252 * Once the previous state has been saved, we can get down to
2253 * reading the new file. We set up the name of the file to be the
2254 * absolute name of the include file so error messages refer to the
2255 * right place. Naturally enough, we start reading at line number 0.
2256 */
2257 curFile.fname = fullname;
2258 curFile.lineno = 0;
2259
2260 curFile.F = fopen(fullname, "r");
2261 curFile.P = NULL;
2262
2263 if (curFile.F == NULL) {
2264 if (!silent)
2265 ParseErrorInternal(cfname, clineno, PARSE_FATAL,
2266 "Cannot open %s", fullname);
2267 /*
2268 * Pop to previous file
2269 */
2270 (void)ParseEOF(1);
2271 }
2272 }
2273 }
2274 #endif
2275
2276 /*-
2277 *---------------------------------------------------------------------
2278 * ParseEOF --
2279 * Called when EOF is reached in the current file. If we were reading
2280 * an include file, the includes stack is popped and things set up
2281 * to go back to reading the previous file at the previous location.
2282 *
2283 * Results:
2284 * CONTINUE if there's more to do. DONE if not.
2285 *
2286 * Side Effects:
2287 * The old curFILE, is closed. The includes list is shortened.
2288 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2289 *---------------------------------------------------------------------
2290 */
2291 static int
2292 ParseEOF(int opened)
2293 {
2294 IFile *ifile; /* the state on the top of the includes stack */
2295
2296 if (Lst_IsEmpty(includes)) {
2297 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2298 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2299 return (DONE);
2300 }
2301
2302 ifile = (IFile *)Lst_DeQueue(includes);
2303
2304 /* XXX dispose of curFile info */
2305 free( curFile.fname);
2306 if (opened && curFile.F)
2307 (void)fclose(curFile.F);
2308 if (curFile.P) {
2309 free(curFile.P->str);
2310 free(curFile.P);
2311 }
2312
2313 memcpy(&curFile, ifile, sizeof(IFile));
2314
2315 free(ifile);
2316
2317 /* pop the PARSEDIR/PARSEFILE variables */
2318 ParseSetParseFile(curFile.fname);
2319 return (CONTINUE);
2320 }
2321
2322 /*-
2323 *---------------------------------------------------------------------
2324 * ParseReadc --
2325 * Read a character from the current file
2326 *
2327 * Results:
2328 * The character that was read
2329 *
2330 * Side Effects:
2331 *---------------------------------------------------------------------
2332 */
2333 static inline int
2334 ParseReadc(void)
2335 {
2336 if (curFile.F)
2337 return fgetc(curFile.F);
2338
2339 if (curFile.P && *curFile.P->ptr)
2340 return *curFile.P->ptr++;
2341 return EOF;
2342 }
2343
2344
2345 /*-
2346 *---------------------------------------------------------------------
2347 * ParseUnreadc --
2348 * Put back a character to the current file
2349 *
2350 * Results:
2351 * None.
2352 *
2353 * Side Effects:
2354 *---------------------------------------------------------------------
2355 */
2356 static void
2357 ParseUnreadc(int c)
2358 {
2359 if (curFile.F) {
2360 ungetc(c, curFile.F);
2361 return;
2362 }
2363 if (curFile.P) {
2364 *--(curFile.P->ptr) = c;
2365 return;
2366 }
2367 }
2368
2369
2370 /* ParseSkipLine():
2371 * Grab the next line
2372 *
2373 * Input:
2374 * skip Skip lines that don't start with .
2375 * keep_newline Keep newline character as is.
2376 *
2377 */
2378 static char *
2379 ParseSkipLine(int skip, int keep_newline)
2380 {
2381 char *line;
2382 int c, lastc, lineLength = 0;
2383 Buffer buf;
2384
2385 buf = Buf_Init(MAKE_BSIZE);
2386
2387 do {
2388 Buf_Discard(buf, lineLength);
2389 lastc = '\0';
2390
2391 while (((c = ParseReadc()) != '\n' || lastc == '\\')
2392 && c != EOF) {
2393 if (c == '\n') {
2394 if (keep_newline)
2395 Buf_AddByte(buf, (Byte)c);
2396 else
2397 Buf_ReplaceLastByte(buf, (Byte)' ');
2398 curFile.lineno++;
2399
2400 while ((c = ParseReadc()) == ' ' || c == '\t');
2401
2402 if (c == EOF)
2403 break;
2404 }
2405
2406 Buf_AddByte(buf, (Byte)c);
2407 lastc = c;
2408 }
2409
2410 if (c == EOF) {
2411 Parse_Error(PARSE_FATAL, "Unclosed conditional/for loop");
2412 Buf_Destroy(buf, TRUE);
2413 return(NULL);
2414 }
2415
2416 curFile.lineno++;
2417 Buf_AddByte(buf, (Byte)'\0');
2418 line = (char *)Buf_GetAll(buf, &lineLength);
2419 } while (skip == 1 && line[0] != '.');
2420
2421 Buf_Destroy(buf, FALSE);
2422 return line;
2423 }
2424
2425
2426 /*-
2427 *---------------------------------------------------------------------
2428 * ParseReadLine --
2429 * Read an entire line from the input file. Called only by Parse_File.
2430 * To facilitate escaped newlines and what have you, a character is
2431 * buffered in 'lastc', which is '\0' when no characters have been
2432 * read. When we break out of the loop, c holds the terminating
2433 * character and lastc holds a character that should be added to
2434 * the line (unless we don't read anything but a terminator).
2435 *
2436 * Results:
2437 * A line w/o its newline
2438 *
2439 * Side Effects:
2440 * Only those associated with reading a character
2441 *---------------------------------------------------------------------
2442 */
2443 static char *
2444 ParseReadLine(void)
2445 {
2446 Buffer buf; /* Buffer for current line */
2447 int c; /* the current character */
2448 int lastc; /* The most-recent character */
2449 Boolean semiNL; /* treat semi-colons as newlines */
2450 Boolean ignDepOp; /* TRUE if should ignore dependency operators
2451 * for the purposes of setting semiNL */
2452 Boolean ignComment; /* TRUE if should ignore comments (in a
2453 * shell command */
2454 char *line; /* Result */
2455 char *ep; /* to strip trailing blanks */
2456 int lineLength; /* Length of result */
2457 int lineno; /* Saved line # */
2458
2459 semiNL = FALSE;
2460 ignDepOp = FALSE;
2461 ignComment = FALSE;
2462
2463 /*
2464 * Handle special-characters at the beginning of the line. Either a
2465 * leading tab (shell command) or pound-sign (possible conditional)
2466 * forces us to ignore comments and dependency operators and treat
2467 * semi-colons as semi-colons (by leaving semiNL FALSE). This also
2468 * discards completely blank lines.
2469 */
2470 for (;;) {
2471 c = ParseReadc();
2472
2473 if (c == '\t') {
2474 ignComment = ignDepOp = TRUE;
2475 break;
2476 } else if (c == '\n') {
2477 curFile.lineno++;
2478 } else if (c == '#') {
2479 ParseUnreadc(c);
2480 break;
2481 } else {
2482 /*
2483 * Anything else breaks out without doing anything
2484 */
2485 break;
2486 }
2487 }
2488
2489 if (c != EOF) {
2490 lastc = c;
2491 buf = Buf_Init(MAKE_BSIZE);
2492
2493 while (((c = ParseReadc()) != '\n' || (lastc == '\\')) &&
2494 (c != EOF))
2495 {
2496 test_char:
2497 switch(c) {
2498 case '\n':
2499 /*
2500 * Escaped newline: read characters until a non-space or an
2501 * unescaped newline and replace them all by a single space.
2502 * This is done by storing the space over the backslash and
2503 * dropping through with the next nonspace. If it is a
2504 * semi-colon and semiNL is TRUE, it will be recognized as a
2505 * newline in the code below this...
2506 */
2507 curFile.lineno++;
2508 lastc = ' ';
2509 while ((c = ParseReadc()) == ' ' || c == '\t') {
2510 continue;
2511 }
2512 if (c == EOF || c == '\n') {
2513 goto line_read;
2514 } else {
2515 /*
2516 * Check for comments, semiNL's, etc. -- easier than
2517 * ParseUnreadc(c); continue;
2518 */
2519 goto test_char;
2520 }
2521 /*NOTREACHED*/
2522 break;
2523
2524 case ';':
2525 /*
2526 * Semi-colon: Need to see if it should be interpreted as a
2527 * newline
2528 */
2529 if (semiNL) {
2530 /*
2531 * To make sure the command that may be following this
2532 * semi-colon begins with a tab, we push one back into the
2533 * input stream. This will overwrite the semi-colon in the
2534 * buffer. If there is no command following, this does no
2535 * harm, since the newline remains in the buffer and the
2536 * whole line is ignored.
2537 */
2538 ParseUnreadc('\t');
2539 goto line_read;
2540 }
2541 break;
2542 case '=':
2543 if (!semiNL) {
2544 /*
2545 * Haven't seen a dependency operator before this, so this
2546 * must be a variable assignment -- don't pay attention to
2547 * dependency operators after this.
2548 */
2549 ignDepOp = TRUE;
2550 } else if (lastc == ':' || lastc == '!') {
2551 /*
2552 * Well, we've seen a dependency operator already, but it
2553 * was the previous character, so this is really just an
2554 * expanded variable assignment. Revert semi-colons to
2555 * being just semi-colons again and ignore any more
2556 * dependency operators.
2557 *
2558 * XXX: Note that a line like "foo : a:=b" will blow up,
2559 * but who'd write a line like that anyway?
2560 */
2561 ignDepOp = TRUE; semiNL = FALSE;
2562 }
2563 break;
2564 case '#':
2565 if (!ignComment) {
2566 if (
2567 #if 0
2568 compatMake &&
2569 #endif
2570 (lastc != '\\')) {
2571 /*
2572 * If the character is a hash mark and it isn't escaped
2573 * (or we're being compatible), the thing is a comment.
2574 * Skip to the end of the line.
2575 */
2576 do {
2577 c = ParseReadc();
2578 /*
2579 * If we found a backslash not escaped
2580 * itself it means that the comment is
2581 * going to continue in the next line.
2582 */
2583 if (c == '\\')
2584 ParseReadc();
2585 } while ((c != '\n') && (c != EOF));
2586 goto line_read;
2587 } else {
2588 /*
2589 * Don't add the backslash. Just let the # get copied
2590 * over.
2591 */
2592 lastc = c;
2593 continue;
2594 }
2595 }
2596 break;
2597 case ':':
2598 case '!':
2599 if (!ignDepOp && (c == ':' || c == '!')) {
2600 /*
2601 * A semi-colon is recognized as a newline only on
2602 * dependency lines. Dependency lines are lines with a
2603 * colon or an exclamation point. Ergo...
2604 */
2605 semiNL = TRUE;
2606 }
2607 break;
2608 }
2609 /*
2610 * Copy in the previous character and save this one in lastc.
2611 */
2612 Buf_AddByte(buf, (Byte)lastc);
2613 lastc = c;
2614
2615 }
2616 line_read:
2617 curFile.lineno++;
2618
2619 if (lastc != '\0') {
2620 Buf_AddByte(buf, (Byte)lastc);
2621 }
2622 Buf_AddByte(buf, (Byte)'\0');
2623 line = (char *)Buf_GetAll(buf, &lineLength);
2624 Buf_Destroy(buf, FALSE);
2625
2626 /*
2627 * Strip trailing blanks and tabs from the line.
2628 * Do not strip a blank or tab that is preceded by
2629 * a '\'
2630 */
2631 ep = line;
2632 while (*ep)
2633 ++ep;
2634 while (ep > line + 1 && (ep[-1] == ' ' || ep[-1] == '\t')) {
2635 if (ep > line + 1 && ep[-2] == '\\')
2636 break;
2637 --ep;
2638 }
2639 *ep = 0;
2640
2641 if (line[0] == '.') {
2642 /*
2643 * The line might be a conditional. Ask the conditional module
2644 * about it and act accordingly
2645 */
2646 switch (Cond_Eval(line)) {
2647 case COND_SKIP:
2648 /*
2649 * Skip to next conditional that evaluates to COND_PARSE.
2650 */
2651 do {
2652 free(line);
2653 line = ParseSkipLine(1, 0);
2654 } while (line && Cond_Eval(line) != COND_PARSE);
2655 if (line == NULL)
2656 break;
2657 /*FALLTHRU*/
2658 case COND_PARSE:
2659 free(line);
2660 line = ParseReadLine();
2661 break;
2662 case COND_INVALID:
2663 lineno = curFile.lineno;
2664 if (For_Eval(line)) {
2665 int ok;
2666 free(line);
2667 do {
2668 /*
2669 * Skip after the matching end
2670 */
2671 line = ParseSkipLine(0, 1);
2672 if (line == NULL) {
2673 Parse_Error(PARSE_FATAL,
2674 "Unexpected end of file in for loop.\n");
2675 break;
2676 }
2677 ok = For_Eval(line);
2678 free(line);
2679 }
2680 while (ok);
2681 if (line != NULL)
2682 For_Run(lineno);
2683 line = ParseReadLine();
2684 }
2685 break;
2686 }
2687 }
2688 return (line);
2689
2690 } else {
2691 /*
2692 * Hit end-of-file, so return a NULL line to indicate this.
2693 */
2694 return(NULL);
2695 }
2696 }
2697
2698 /*-
2699 *-----------------------------------------------------------------------
2700 * ParseFinishLine --
2701 * Handle the end of a dependency group.
2702 *
2703 * Results:
2704 * Nothing.
2705 *
2706 * Side Effects:
2707 * inLine set FALSE. 'targets' list destroyed.
2708 *
2709 *-----------------------------------------------------------------------
2710 */
2711 static void
2712 ParseFinishLine(void)
2713 {
2714 if (inLine) {
2715 Lst_ForEach(targets, Suff_EndTransform, (ClientData)NULL);
2716 Lst_Destroy(targets, ParseHasCommands);
2717 targets = NULL;
2718 inLine = FALSE;
2719 }
2720 }
2721
2722
2723 /*-
2724 *---------------------------------------------------------------------
2725 * Parse_File --
2726 * Parse a file into its component parts, incorporating it into the
2727 * current dependency graph. This is the main function and controls
2728 * almost every other function in this module
2729 *
2730 * Input:
2731 * name the name of the file being read
2732 * stream Stream open to makefile to parse
2733 *
2734 * Results:
2735 * None
2736 *
2737 * Side Effects:
2738 * Loads. Nodes are added to the list of all targets, nodes and links
2739 * are added to the dependency graph. etc. etc. etc.
2740 *---------------------------------------------------------------------
2741 */
2742 void
2743 Parse_File(const char *name, FILE *stream)
2744 {
2745 char *cp, /* pointer into the line */
2746 *line; /* the line we're working on */
2747
2748 inLine = FALSE;
2749 fatals = 0;
2750
2751 curFile.fname = UNCONST(name);
2752 curFile.F = stream;
2753 curFile.lineno = 0;
2754
2755 ParseSetParseFile(curFile.fname);
2756
2757 do {
2758 while ((line = ParseReadLine()) != NULL) {
2759 if (*line == '.') {
2760 /*
2761 * Lines that begin with the special character are either
2762 * include or undef directives.
2763 */
2764 for (cp = line + 1; isspace ((unsigned char)*cp); cp++) {
2765 continue;
2766 }
2767 if (strncmp(cp, "include", 7) == 0 ||
2768 ((cp[0] == 's' || cp[0] == '-') &&
2769 strncmp(&cp[1], "include", 7) == 0)) {
2770 ParseDoInclude(cp);
2771 goto nextLine;
2772 } else if (strncmp(cp, "undef", 5) == 0) {
2773 char *cp2;
2774 for (cp += 5; isspace((unsigned char) *cp); cp++) {
2775 continue;
2776 }
2777
2778 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2779 (*cp2 != '\0'); cp2++) {
2780 continue;
2781 }
2782
2783 *cp2 = '\0';
2784
2785 Var_Delete(cp, VAR_GLOBAL);
2786 goto nextLine;
2787 }
2788 }
2789 if (*line == '#') {
2790 /* If we're this far, the line must be a comment. */
2791 goto nextLine;
2792 }
2793
2794 if (*line == '\t') {
2795 /*
2796 * If a line starts with a tab, it can only hope to be
2797 * a creation command.
2798 */
2799 #ifndef POSIX
2800 shellCommand:
2801 #endif
2802 for (cp = line + 1; isspace ((unsigned char)*cp); cp++) {
2803 continue;
2804 }
2805 if (*cp) {
2806 if (inLine) {
2807 /*
2808 * So long as it's not a blank line and we're actually
2809 * in a dependency spec, add the command to the list of
2810 * commands of all targets in the dependency spec
2811 */
2812 Lst_ForEach(targets, ParseAddCmd, cp);
2813 #ifdef CLEANUP
2814 Lst_AtEnd(targCmds, (ClientData) line);
2815 #endif
2816 continue;
2817 } else {
2818 Parse_Error(PARSE_FATAL,
2819 "Unassociated shell command \"%s\"",
2820 cp);
2821 }
2822 }
2823 #ifdef SYSVINCLUDE
2824 } else if (((strncmp(line, "include", 7) == 0 &&
2825 isspace((unsigned char) line[7])) ||
2826 ((line[0] == 's' || line[0] == '-') &&
2827 strncmp(&line[1], "include", 7) == 0 &&
2828 isspace((unsigned char) line[8]))) &&
2829 strchr(line, ':') == NULL) {
2830 /*
2831 * It's an S3/S5-style "include".
2832 */
2833 ParseTraditionalInclude(line);
2834 goto nextLine;
2835 #endif
2836 } else if (Parse_IsVar(line)) {
2837 ParseFinishLine();
2838 Parse_DoVar(line, VAR_GLOBAL);
2839 } else {
2840 /*
2841 * We now know it's a dependency line so it needs to have all
2842 * variables expanded before being parsed. Tell the variable
2843 * module to complain if some variable is undefined...
2844 * To make life easier on novices, if the line is indented we
2845 * first make sure the line has a dependency operator in it.
2846 * If it doesn't have an operator and we're in a dependency
2847 * line's script, we assume it's actually a shell command
2848 * and add it to the current list of targets.
2849 */
2850 #ifndef POSIX
2851 Boolean nonSpace = FALSE;
2852 #endif
2853
2854 cp = line;
2855 if (isspace((unsigned char) line[0])) {
2856 while ((*cp != '\0') && isspace((unsigned char) *cp)) {
2857 cp++;
2858 }
2859 if (*cp == '\0') {
2860 goto nextLine;
2861 }
2862 #ifndef POSIX
2863 while (*cp && (ParseIsEscaped(line, cp) ||
2864 (*cp != ':') && (*cp != '!'))) {
2865 nonSpace = TRUE;
2866 cp++;
2867 }
2868 #endif
2869 }
2870
2871 #ifndef POSIX
2872 if (*cp == '\0') {
2873 if (inLine) {
2874 Parse_Error(PARSE_WARNING,
2875 "Shell command needs a leading tab");
2876 goto shellCommand;
2877 } else if (nonSpace) {
2878 Parse_Error(PARSE_FATAL, "Missing operator");
2879 }
2880 } else {
2881 #endif
2882 ParseFinishLine();
2883
2884 cp = Var_Subst(NULL, line, VAR_CMD, TRUE);
2885 free(line);
2886 line = cp;
2887
2888 /*
2889 * Need a non-circular list for the target nodes
2890 */
2891 if (targets)
2892 Lst_Destroy(targets, NOFREE);
2893
2894 targets = Lst_Init(FALSE);
2895 inLine = TRUE;
2896
2897 ParseDoDependency(line);
2898 #ifndef POSIX
2899 }
2900 #endif
2901 }
2902
2903 nextLine:
2904
2905 free(line);
2906 }
2907 /*
2908 * Reached EOF, but it may be just EOF of an include file...
2909 */
2910 } while (ParseEOF(1) == CONTINUE);
2911
2912 /*
2913 * Make sure conditionals are clean
2914 */
2915 Cond_End();
2916
2917 if (fatals) {
2918 (void)fprintf(stderr,
2919 "%s: Fatal errors encountered -- cannot continue\n",
2920 progname);
2921 PrintOnError(NULL);
2922 exit(1);
2923 }
2924 }
2925
2926 /*-
2927 *---------------------------------------------------------------------
2928 * Parse_Init --
2929 * initialize the parsing module
2930 *
2931 * Results:
2932 * none
2933 *
2934 * Side Effects:
2935 * the parseIncPath list is initialized...
2936 *---------------------------------------------------------------------
2937 */
2938 void
2939 Parse_Init(void)
2940 {
2941 mainNode = NILGNODE;
2942 parseIncPath = Lst_Init(FALSE);
2943 sysIncPath = Lst_Init(FALSE);
2944 defIncPath = Lst_Init(FALSE);
2945 includes = Lst_Init(FALSE);
2946 #ifdef CLEANUP
2947 targCmds = Lst_Init(FALSE);
2948 #endif
2949 }
2950
2951 void
2952 Parse_End(void)
2953 {
2954 #ifdef CLEANUP
2955 Lst_Destroy(targCmds, (FreeProc *)free);
2956 if (targets)
2957 Lst_Destroy(targets, NOFREE);
2958 Lst_Destroy(defIncPath, Dir_Destroy);
2959 Lst_Destroy(sysIncPath, Dir_Destroy);
2960 Lst_Destroy(parseIncPath, Dir_Destroy);
2961 Lst_Destroy(includes, NOFREE); /* Should be empty now */
2962 #endif
2963 }
2964
2965
2966 /*-
2967 *-----------------------------------------------------------------------
2968 * Parse_MainName --
2969 * Return a Lst of the main target to create for main()'s sake. If
2970 * no such target exists, we Punt with an obnoxious error message.
2971 *
2972 * Results:
2973 * A Lst of the single node to create.
2974 *
2975 * Side Effects:
2976 * None.
2977 *
2978 *-----------------------------------------------------------------------
2979 */
2980 Lst
2981 Parse_MainName(void)
2982 {
2983 Lst mainList; /* result list */
2984
2985 mainList = Lst_Init(FALSE);
2986
2987 if (mainNode == NILGNODE) {
2988 Punt("no target to make.");
2989 /*NOTREACHED*/
2990 } else if (mainNode->type & OP_DOUBLEDEP) {
2991 (void)Lst_AtEnd(mainList, (ClientData)mainNode);
2992 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
2993 }
2994 else
2995 (void)Lst_AtEnd(mainList, (ClientData)mainNode);
2996 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
2997 return (mainList);
2998 }
2999
3000 /*-
3001 *-----------------------------------------------------------------------
3002 * ParseMark --
3003 * Add the filename and lineno to the GNode so that we remember
3004 * where it was first defined.
3005 *
3006 * Side Effects:
3007 * None.
3008 *
3009 *-----------------------------------------------------------------------
3010 */
3011 static void
3012 ParseMark(GNode *gn)
3013 {
3014 gn->fname = strdup(curFile.fname);
3015 gn->lineno = curFile.lineno;
3016 }
3017