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