In very obscure situations we may write the free token back to the pipe.
[make.git] / read.c
blob58423f52434ec017dbee1c0e037fa29e044f302a
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
21 #include <assert.h>
23 #include <glob.h>
25 #include "dep.h"
26 #include "filedef.h"
27 #include "job.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #include "debug.h"
32 #include "hash.h"
35 #ifndef WINDOWS32
36 #ifndef _AMIGA
37 #ifndef VMS
38 #include <pwd.h>
39 #else
40 struct passwd *getpwnam (char *name);
41 #endif
42 #endif
43 #endif /* !WINDOWS32 */
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
46 eval'ing.
49 struct ebuffer
51 char *buffer; /* Start of the current line in the buffer. */
52 char *bufnext; /* Start of the next line in the buffer. */
53 char *bufstart; /* Start of the entire buffer. */
54 unsigned int size; /* Malloc'd size of buffer. */
55 FILE *fp; /* File, or NULL if this is an internal buffer. */
56 struct floc floc; /* Info on the file in fp (if any). */
59 /* Track the modifiers we can have on variable assignments */
61 struct vmodifiers
63 unsigned int assign_v:1;
64 unsigned int define_v:1;
65 unsigned int undefine_v:1;
66 unsigned int export_v:1;
67 unsigned int override_v:1;
68 unsigned int private_v:1;
71 /* Types of "words" that can be read in a makefile. */
72 enum make_word_type
74 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
75 w_varassign
79 /* A `struct conditionals' contains the information describing
80 all the active conditionals in a makefile.
82 The global variable `conditionals' contains the conditionals
83 information for the current makefile. It is initialized from
84 the static structure `toplevel_conditionals' and is later changed
85 to new structures for included makefiles. */
87 struct conditionals
89 unsigned int if_cmds; /* Depth of conditional nesting. */
90 unsigned int allocated; /* Elts allocated in following arrays. */
91 char *ignoring; /* Are we ignoring or interpreting?
92 0=interpreting, 1=not yet interpreted,
93 2=already interpreted */
94 char *seen_else; /* Have we already seen an `else'? */
97 static struct conditionals toplevel_conditionals;
98 static struct conditionals *conditionals = &toplevel_conditionals;
101 /* Default directories to search for include files in */
103 static const char *default_include_directories[] =
105 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
106 /* This completely up to the user when they install MSVC or other packages.
107 This is defined as a placeholder. */
108 # define INCLUDEDIR "."
109 #endif
110 INCLUDEDIR,
111 #ifndef _AMIGA
112 "/usr/gnu/include",
113 "/usr/local/include",
114 "/usr/include",
115 #endif
119 /* List of directories to search for include files in */
121 static const char **include_directories;
123 /* Maximum length of an element of the above. */
125 static unsigned int max_incl_len;
127 /* The filename and pointer to line number of the
128 makefile currently being read in. */
130 const struct floc *reading_file = 0;
132 /* The chain of makefiles read by read_makefile. */
134 static struct dep *read_makefiles = 0;
136 static int eval_makefile (const char *filename, int flags);
137 static void eval (struct ebuffer *buffer, int flags);
139 static long readline (struct ebuffer *ebuf);
140 static void do_undefine (char *name, enum variable_origin origin,
141 struct ebuffer *ebuf);
142 static struct variable *do_define (char *name, enum variable_origin origin,
143 struct ebuffer *ebuf);
144 static int conditional_line (char *line, int len, const struct floc *flocp);
145 static void record_files (struct nameseq *filenames, const char *pattern,
146 const char *pattern_percent, char *depstr,
147 unsigned int cmds_started, char *commands,
148 unsigned int commands_idx, int two_colon,
149 char prefix, const struct floc *flocp);
150 static void record_target_var (struct nameseq *filenames, char *defn,
151 enum variable_origin origin,
152 struct vmodifiers *vmod,
153 const struct floc *flocp);
154 static enum make_word_type get_next_mword (char *buffer, char *delim,
155 char **startp, unsigned int *length);
156 static void remove_comments (char *line);
157 static char *find_char_unquote (char *string, int stop1, int stop2,
158 int blank, int ignorevars);
161 /* Compare a word, both length and contents.
162 P must point to the word to be tested, and WLEN must be the length.
164 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
167 /* Read in all the makefiles and return the chain of their names. */
169 struct dep *
170 read_all_makefiles (const char **makefiles)
172 unsigned int num_makefiles = 0;
174 /* Create *_LIST variables, to hold the makefiles, targets, and variables
175 we will be reading. */
177 define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
179 DB (DB_BASIC, (_("Reading makefiles...\n")));
181 /* If there's a non-null variable MAKEFILES, its value is a list of
182 files to read first thing. But don't let it prevent reading the
183 default makefiles and don't let the default goal come from there. */
186 char *value;
187 char *name, *p;
188 unsigned int length;
191 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
192 int save = warn_undefined_variables_flag;
193 warn_undefined_variables_flag = 0;
195 value = allocated_variable_expand ("$(MAKEFILES)");
197 warn_undefined_variables_flag = save;
200 /* Set NAME to the start of next token and LENGTH to its length.
201 MAKEFILES is updated for finding remaining tokens. */
202 p = value;
204 while ((name = find_next_token ((const char **)&p, &length)) != 0)
206 if (*p != '\0')
207 *p++ = '\0';
208 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
211 free (value);
214 /* Read makefiles specified with -f switches. */
216 if (makefiles != 0)
217 while (*makefiles != 0)
219 struct dep *tail = read_makefiles;
220 register struct dep *d;
222 if (! eval_makefile (*makefiles, 0))
223 perror_with_name ("", *makefiles);
225 /* Find the right element of read_makefiles. */
226 d = read_makefiles;
227 while (d->next != tail)
228 d = d->next;
230 /* Use the storage read_makefile allocates. */
231 *makefiles = dep_name (d);
232 ++num_makefiles;
233 ++makefiles;
236 /* If there were no -f switches, try the default names. */
238 if (num_makefiles == 0)
240 static char *default_makefiles[] =
241 #ifdef VMS
242 /* all lower case since readdir() (the vms version) 'lowercasifies' */
243 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
244 #else
245 #ifdef _AMIGA
246 { "GNUmakefile", "Makefile", "SMakefile", 0 };
247 #else /* !Amiga && !VMS */
248 { "GNUmakefile", "makefile", "Makefile", 0 };
249 #endif /* AMIGA */
250 #endif /* VMS */
251 register char **p = default_makefiles;
252 while (*p != 0 && !file_exists_p (*p))
253 ++p;
255 if (*p != 0)
257 if (! eval_makefile (*p, 0))
258 perror_with_name ("", *p);
260 else
262 /* No default makefile was found. Add the default makefiles to the
263 `read_makefiles' chain so they will be updated if possible. */
264 struct dep *tail = read_makefiles;
265 /* Add them to the tail, after any MAKEFILES variable makefiles. */
266 while (tail != 0 && tail->next != 0)
267 tail = tail->next;
268 for (p = default_makefiles; *p != 0; ++p)
270 struct dep *d = alloc_dep ();
271 d->file = enter_file (strcache_add (*p));
272 d->dontcare = 1;
273 /* Tell update_goal_chain to bail out as soon as this file is
274 made, and main not to die if we can't make this file. */
275 d->changed = RM_DONTCARE;
276 if (tail == 0)
277 read_makefiles = d;
278 else
279 tail->next = d;
280 tail = d;
282 if (tail != 0)
283 tail->next = 0;
287 return read_makefiles;
290 /* Install a new conditional and return the previous one. */
292 static struct conditionals *
293 install_conditionals (struct conditionals *new)
295 struct conditionals *save = conditionals;
297 memset (new, '\0', sizeof (*new));
298 conditionals = new;
300 return save;
303 /* Free the current conditionals and reinstate a saved one. */
305 static void
306 restore_conditionals (struct conditionals *saved)
308 /* Free any space allocated by conditional_line. */
309 if (conditionals->ignoring)
310 free (conditionals->ignoring);
311 if (conditionals->seen_else)
312 free (conditionals->seen_else);
314 /* Restore state. */
315 conditionals = saved;
318 static int
319 eval_makefile (const char *filename, int flags)
321 struct dep *deps;
322 struct ebuffer ebuf;
323 const struct floc *curfile;
324 char *expanded = 0;
325 int makefile_errno;
327 ebuf.floc.filenm = filename; /* Use the original file name. */
328 ebuf.floc.lineno = 1;
330 if (ISDB (DB_VERBOSE))
332 printf (_("Reading makefile `%s'"), filename);
333 if (flags & RM_NO_DEFAULT_GOAL)
334 printf (_(" (no default goal)"));
335 if (flags & RM_INCLUDED)
336 printf (_(" (search path)"));
337 if (flags & RM_DONTCARE)
338 printf (_(" (don't care)"));
339 if (flags & RM_NO_TILDE)
340 printf (_(" (no ~ expansion)"));
341 puts ("...");
344 /* First, get a stream to read. */
346 /* Expand ~ in FILENAME unless it came from `include',
347 in which case it was already done. */
348 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
350 expanded = tilde_expand (filename);
351 if (expanded != 0)
352 filename = expanded;
355 ebuf.fp = fopen (filename, "r");
356 /* Save the error code so we print the right message later. */
357 makefile_errno = errno;
359 /* If the makefile wasn't found and it's either a makefile from
360 the `MAKEFILES' variable or an included makefile,
361 search the included makefile search path for this makefile. */
362 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
364 unsigned int i;
365 for (i = 0; include_directories[i] != 0; ++i)
367 const char *included = concat (3, include_directories[i],
368 "/", filename);
369 ebuf.fp = fopen (included, "r");
370 if (ebuf.fp)
372 filename = included;
373 break;
378 /* Now we have the final name for this makefile. Enter it into
379 the cache. */
380 filename = strcache_add (filename);
382 /* Add FILENAME to the chain of read makefiles. */
383 deps = alloc_dep ();
384 deps->next = read_makefiles;
385 read_makefiles = deps;
386 deps->file = lookup_file (filename);
387 if (deps->file == 0)
388 deps->file = enter_file (filename);
389 filename = deps->file->name;
390 deps->changed = flags;
391 if (flags & RM_DONTCARE)
392 deps->dontcare = 1;
394 if (expanded)
395 free (expanded);
397 /* If the makefile can't be found at all, give up entirely. */
399 if (ebuf.fp == 0)
401 /* If we did some searching, errno has the error from the last
402 attempt, rather from FILENAME itself. Restore it in case the
403 caller wants to use it in a message. */
404 errno = makefile_errno;
405 return 0;
408 /* Set close-on-exec to avoid leaking the makefile to children, such as
409 $(shell ...). */
410 #ifdef HAVE_FILENO
411 CLOSE_ON_EXEC (fileno (ebuf.fp));
412 #endif
414 /* Add this makefile to the list. */
415 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
416 f_append, 0);
418 /* Evaluate the makefile */
420 ebuf.size = 200;
421 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
423 curfile = reading_file;
424 reading_file = &ebuf.floc;
426 eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
428 reading_file = curfile;
430 fclose (ebuf.fp);
432 free (ebuf.bufstart);
433 alloca (0);
435 return 1;
438 void
439 eval_buffer (char *buffer)
441 struct ebuffer ebuf;
442 struct conditionals *saved;
443 struct conditionals new;
444 const struct floc *curfile;
446 /* Evaluate the buffer */
448 ebuf.size = strlen (buffer);
449 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
450 ebuf.fp = NULL;
452 if (reading_file)
453 ebuf.floc = *reading_file;
454 else
455 ebuf.floc.filenm = NULL;
457 curfile = reading_file;
458 reading_file = &ebuf.floc;
460 saved = install_conditionals (&new);
462 eval (&ebuf, 1);
464 restore_conditionals (saved);
466 reading_file = curfile;
468 alloca (0);
471 /* Check LINE to see if it's a variable assignment or undefine.
473 It might use one of the modifiers "export", "override", "private", or it
474 might be one of the conditional tokens like "ifdef", "include", etc.
476 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
477 Returns LINE.
479 Returns a pointer to the first non-modifier character, and sets VMOD
480 based on the modifiers found if any, plus V_ASSIGN is 1.
482 static char *
483 parse_var_assignment (const char *line, struct vmodifiers *vmod)
485 const char *p;
486 memset (vmod, '\0', sizeof (*vmod));
488 /* Find the start of the next token. If there isn't one we're done. */
489 line = next_token (line);
490 if (*line == '\0')
491 return (char *)line;
493 p = line;
494 while (1)
496 int wlen;
497 const char *p2;
498 enum variable_flavor flavor;
500 p2 = parse_variable_definition (p, &flavor);
502 /* If this is a variable assignment, we're done. */
503 if (p2)
504 break;
506 /* It's not a variable; see if it's a modifier. */
507 p2 = end_of_token (p);
508 wlen = p2 - p;
510 if (word1eq ("export"))
511 vmod->export_v = 1;
512 else if (word1eq ("override"))
513 vmod->override_v = 1;
514 else if (word1eq ("private"))
515 vmod->private_v = 1;
516 else if (word1eq ("define"))
518 /* We can't have modifiers after 'define' */
519 vmod->define_v = 1;
520 p = next_token (p2);
521 break;
523 else if (word1eq ("undefine"))
525 /* We can't have modifiers after 'undefine' */
526 vmod->undefine_v = 1;
527 p = next_token (p2);
528 break;
530 else
531 /* Not a variable or modifier: this is not a variable assignment. */
532 return (char *)line;
534 /* It was a modifier. Try the next word. */
535 p = next_token (p2);
536 if (*p == '\0')
537 return (char *)line;
540 /* Found a variable assignment or undefine. */
541 vmod->assign_v = 1;
542 return (char *)p;
546 /* Read file FILENAME as a makefile and add its contents to the data base.
548 SET_DEFAULT is true if we are allowed to set the default goal. */
550 static void
551 eval (struct ebuffer *ebuf, int set_default)
553 char *collapsed = 0;
554 unsigned int collapsed_length = 0;
555 unsigned int commands_len = 200;
556 char *commands;
557 unsigned int commands_idx = 0;
558 unsigned int cmds_started, tgts_started;
559 int ignoring = 0, in_ignored_define = 0;
560 int no_targets = 0; /* Set when reading a rule without targets. */
561 struct nameseq *filenames = 0;
562 char *depstr = 0;
563 long nlines = 0;
564 int two_colon = 0;
565 char prefix;
566 const char *pattern = 0;
567 const char *pattern_percent;
568 struct floc *fstart;
569 struct floc fi;
571 #define record_waiting_files() \
572 do \
574 if (filenames != 0) \
576 fi.lineno = tgts_started; \
577 record_files (filenames, pattern, pattern_percent, depstr, \
578 cmds_started, commands, commands_idx, two_colon, \
579 prefix, &fi); \
580 filenames = 0; \
582 commands_idx = 0; \
583 no_targets = 0; \
584 pattern = 0; \
585 } while (0)
587 pattern_percent = 0;
588 cmds_started = tgts_started = 1;
590 fstart = &ebuf->floc;
591 fi.filenm = ebuf->floc.filenm;
593 /* Loop over lines in the file.
594 The strategy is to accumulate target names in FILENAMES, dependencies
595 in DEPS and commands in COMMANDS. These are used to define a rule
596 when the start of the next rule (or eof) is encountered.
598 When you see a "continue" in the loop below, that means we are moving on
599 to the next line _without_ ending any rule that we happen to be working
600 with at the moment. If you see a "goto rule_complete", then the
601 statement we just parsed also finishes the previous rule. */
603 commands = xmalloc (200);
605 while (1)
607 unsigned int linelen;
608 char *line;
609 unsigned int wlen;
610 char *p;
611 char *p2;
612 struct vmodifiers vmod;
614 /* At the top of this loop, we are starting a brand new line. */
615 /* Grab the next line to be evaluated */
616 ebuf->floc.lineno += nlines;
617 nlines = readline (ebuf);
619 /* If there is nothing left to eval, we're done. */
620 if (nlines < 0)
621 break;
623 /* If this line is empty, skip it. */
624 line = ebuf->buffer;
625 if (line[0] == '\0')
626 continue;
628 linelen = strlen (line);
630 /* Check for a shell command line first.
631 If it is not one, we can stop treating cmd_prefix specially. */
632 if (line[0] == cmd_prefix)
634 if (no_targets)
635 /* Ignore the commands in a rule with no targets. */
636 continue;
638 /* If there is no preceding rule line, don't treat this line
639 as a command, even though it begins with a recipe prefix.
640 SunOS 4 make appears to behave this way. */
642 if (filenames != 0)
644 if (ignoring)
645 /* Yep, this is a shell command, and we don't care. */
646 continue;
648 if (commands_idx == 0)
649 cmds_started = ebuf->floc.lineno;
651 /* Append this command line to the line being accumulated.
652 Skip the initial command prefix character. */
653 if (linelen + commands_idx > commands_len)
655 commands_len = (linelen + commands_idx) * 2;
656 commands = xrealloc (commands, commands_len);
658 memcpy (&commands[commands_idx], line + 1, linelen - 1);
659 commands_idx += linelen - 1;
660 commands[commands_idx++] = '\n';
661 continue;
665 /* This line is not a shell command line. Don't worry about whitespace.
666 Get more space if we need it; we don't need to preserve the current
667 contents of the buffer. */
669 if (collapsed_length < linelen+1)
671 collapsed_length = linelen+1;
672 if (collapsed)
673 free (collapsed);
674 /* Don't need xrealloc: we don't need to preserve the content. */
675 collapsed = xmalloc (collapsed_length);
677 strcpy (collapsed, line);
678 /* Collapse continuation lines. */
679 collapse_continuations (collapsed);
680 remove_comments (collapsed);
682 /* Get rid if starting space (including formfeed, vtab, etc.) */
683 p = collapsed;
684 while (isspace ((unsigned char)*p))
685 ++p;
687 /* See if this is a variable assignment. We need to do this early, to
688 allow variables with names like 'ifdef', 'export', 'private', etc. */
689 p = parse_var_assignment(p, &vmod);
690 if (vmod.assign_v)
692 struct variable *v;
693 enum variable_origin origin = vmod.override_v ? o_override : o_file;
695 /* If we're ignoring then we're done now. */
696 if (ignoring)
698 if (vmod.define_v)
699 in_ignored_define = 1;
700 continue;
703 if (vmod.undefine_v)
705 do_undefine (p, origin, ebuf);
707 /* This line has been dealt with. */
708 goto rule_complete;
710 else if (vmod.define_v)
711 v = do_define (p, origin, ebuf);
712 else
713 v = try_variable_definition (fstart, p, origin, 0);
715 assert (v != NULL);
717 if (vmod.export_v)
718 v->export = v_export;
719 if (vmod.private_v)
720 v->private_var = 1;
722 /* This line has been dealt with. */
723 goto rule_complete;
726 /* If this line is completely empty, ignore it. */
727 if (*p == '\0')
728 continue;
730 p2 = end_of_token (p);
731 wlen = p2 - p;
732 p2 = next_token (p2);
734 /* If we're in an ignored define, skip this line (but maybe get out). */
735 if (in_ignored_define)
737 /* See if this is an endef line (plus optional comment). */
738 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
739 in_ignored_define = 0;
741 continue;
744 /* Check for conditional state changes. */
746 int i = conditional_line (p, wlen, fstart);
747 if (i != -2)
749 if (i == -1)
750 fatal (fstart, _("invalid syntax in conditional"));
752 ignoring = i;
753 continue;
757 /* Nothing to see here... move along. */
758 if (ignoring)
759 continue;
761 /* Manage the "export" keyword used outside of variable assignment
762 as well as "unexport". */
763 if (word1eq ("export") || word1eq ("unexport"))
765 int exporting = *p == 'u' ? 0 : 1;
767 /* (un)export by itself causes everything to be (un)exported. */
768 if (*p2 == '\0')
769 export_all_variables = exporting;
770 else
772 unsigned int l;
773 const char *cp;
774 char *ap;
776 /* Expand the line so we can use indirect and constructed
777 variable names in an (un)export command. */
778 cp = ap = allocated_variable_expand (p2);
780 for (p = find_next_token (&cp, &l); p != 0;
781 p = find_next_token (&cp, &l))
783 struct variable *v = lookup_variable (p, l);
784 if (v == 0)
785 v = define_variable_global (p, l, "", o_file, 0, fstart);
786 v->export = exporting ? v_export : v_noexport;
789 free (ap);
791 goto rule_complete;
794 /* Handle the special syntax for vpath. */
795 if (word1eq ("vpath"))
797 const char *cp;
798 char *vpat;
799 unsigned int l;
800 cp = variable_expand (p2);
801 p = find_next_token (&cp, &l);
802 if (p != 0)
804 vpat = xstrndup (p, l);
805 p = find_next_token (&cp, &l);
806 /* No searchpath means remove all previous
807 selective VPATH's with the same pattern. */
809 else
810 /* No pattern means remove all previous selective VPATH's. */
811 vpat = 0;
812 construct_vpath_list (vpat, p);
813 if (vpat != 0)
814 free (vpat);
816 goto rule_complete;
819 /* Handle include and variants. */
820 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
822 /* We have found an `include' line specifying a nested
823 makefile to be read at this point. */
824 struct conditionals *save;
825 struct conditionals new_conditionals;
826 struct nameseq *files;
827 /* "-include" (vs "include") says no error if the file does not
828 exist. "sinclude" is an alias for this from SGI. */
829 int noerror = (p[0] != 'i');
831 p = allocated_variable_expand (p2);
833 /* If no filenames, it's a no-op. */
834 if (*p == '\0')
836 free (p);
837 continue;
840 /* Parse the list of file names. Don't expand archive references! */
841 p2 = p;
842 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
843 PARSEFS_NOAR);
844 free (p);
846 /* Save the state of conditionals and start
847 the included makefile with a clean slate. */
848 save = install_conditionals (&new_conditionals);
850 /* Record the rules that are waiting so they will determine
851 the default goal before those in the included makefile. */
852 record_waiting_files ();
854 /* Read each included makefile. */
855 while (files != 0)
857 struct nameseq *next = files->next;
858 const char *name = files->name;
859 int r;
861 free_ns (files);
862 files = next;
864 r = eval_makefile (name,
865 (RM_INCLUDED | RM_NO_TILDE
866 | (noerror ? RM_DONTCARE : 0)
867 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
868 if (!r && !noerror)
869 error (fstart, "%s: %s", name, strerror (errno));
872 /* Restore conditional state. */
873 restore_conditionals (save);
875 goto rule_complete;
878 /* This line starts with a tab but was not caught above because there
879 was no preceding target, and the line might have been usable as a
880 variable definition. But now we know it is definitely lossage. */
881 if (line[0] == cmd_prefix)
882 fatal(fstart, _("recipe commences before first target"));
884 /* This line describes some target files. This is complicated by
885 the existence of target-specific variables, because we can't
886 expand the entire line until we know if we have one or not. So
887 we expand the line word by word until we find the first `:',
888 then check to see if it's a target-specific variable.
890 In this algorithm, `lb_next' will point to the beginning of the
891 unexpanded parts of the input buffer, while `p2' points to the
892 parts of the expanded buffer we haven't searched yet. */
895 enum make_word_type wtype;
896 char *cmdleft, *semip, *lb_next;
897 unsigned int plen = 0;
898 char *colonp;
899 const char *end, *beg; /* Helpers for whitespace stripping. */
901 /* Record the previous rule. */
903 record_waiting_files ();
904 tgts_started = fstart->lineno;
906 /* Search the line for an unquoted ; that is not after an
907 unquoted #. */
908 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
909 if (cmdleft != 0 && *cmdleft == '#')
911 /* We found a comment before a semicolon. */
912 *cmdleft = '\0';
913 cmdleft = 0;
915 else if (cmdleft != 0)
916 /* Found one. Cut the line short there before expanding it. */
917 *(cmdleft++) = '\0';
918 semip = cmdleft;
920 collapse_continuations (line);
922 /* We can't expand the entire line, since if it's a per-target
923 variable we don't want to expand it. So, walk from the
924 beginning, expanding as we go, and looking for "interesting"
925 chars. The first word is always expandable. */
926 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
927 switch (wtype)
929 case w_eol:
930 if (cmdleft != 0)
931 fatal(fstart, _("missing rule before recipe"));
932 /* This line contained something but turned out to be nothing
933 but whitespace (a comment?). */
934 continue;
936 case w_colon:
937 case w_dcolon:
938 /* We accept and ignore rules without targets for
939 compatibility with SunOS 4 make. */
940 no_targets = 1;
941 continue;
943 default:
944 break;
947 p2 = variable_expand_string(NULL, lb_next, wlen);
949 while (1)
951 lb_next += wlen;
952 if (cmdleft == 0)
954 /* Look for a semicolon in the expanded line. */
955 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
957 if (cmdleft != 0)
959 unsigned long p2_off = p2 - variable_buffer;
960 unsigned long cmd_off = cmdleft - variable_buffer;
961 char *pend = p2 + strlen(p2);
963 /* Append any remnants of lb, then cut the line short
964 at the semicolon. */
965 *cmdleft = '\0';
967 /* One school of thought says that you shouldn't expand
968 here, but merely copy, since now you're beyond a ";"
969 and into a command script. However, the old parser
970 expanded the whole line, so we continue that for
971 backwards-compatiblity. Also, it wouldn't be
972 entirely consistent, since we do an unconditional
973 expand below once we know we don't have a
974 target-specific variable. */
975 (void)variable_expand_string(pend, lb_next, (long)-1);
976 lb_next += strlen(lb_next);
977 p2 = variable_buffer + p2_off;
978 cmdleft = variable_buffer + cmd_off + 1;
982 colonp = find_char_unquote(p2, ':', 0, 0, 0);
983 #ifdef HAVE_DOS_PATHS
984 /* The drive spec brain-damage strikes again... */
985 /* Note that the only separators of targets in this context
986 are whitespace and a left paren. If others are possible,
987 they should be added to the string in the call to index. */
988 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
989 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
990 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
991 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
992 #endif
993 if (colonp != 0)
994 break;
996 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
997 if (wtype == w_eol)
998 break;
1000 p2 += strlen(p2);
1001 *(p2++) = ' ';
1002 p2 = variable_expand_string(p2, lb_next, wlen);
1003 /* We don't need to worry about cmdleft here, because if it was
1004 found in the variable_buffer the entire buffer has already
1005 been expanded... we'll never get here. */
1008 p2 = next_token (variable_buffer);
1010 /* If the word we're looking at is EOL, see if there's _anything_
1011 on the line. If not, a variable expanded to nothing, so ignore
1012 it. If so, we can't parse this line so punt. */
1013 if (wtype == w_eol)
1015 if (*p2 != '\0')
1016 /* There's no need to be ivory-tower about this: check for
1017 one of the most common bugs found in makefiles... */
1018 fatal (fstart, _("missing separator%s"),
1019 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1020 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1021 continue;
1024 /* Make the colon the end-of-string so we know where to stop
1025 looking for targets. */
1026 *colonp = '\0';
1027 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1028 *p2 = ':';
1030 if (!filenames)
1032 /* We accept and ignore rules without targets for
1033 compatibility with SunOS 4 make. */
1034 no_targets = 1;
1035 continue;
1037 /* This should never be possible; we handled it above. */
1038 assert (*p2 != '\0');
1039 ++p2;
1041 /* Is this a one-colon or two-colon entry? */
1042 two_colon = *p2 == ':';
1043 if (two_colon)
1044 p2++;
1046 /* Test to see if it's a target-specific variable. Copy the rest
1047 of the buffer over, possibly temporarily (we'll expand it later
1048 if it's not a target-specific variable). PLEN saves the length
1049 of the unparsed section of p2, for later. */
1050 if (*lb_next != '\0')
1052 unsigned int l = p2 - variable_buffer;
1053 plen = strlen (p2);
1054 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1055 p2 = variable_buffer + l;
1058 p2 = parse_var_assignment (p2, &vmod);
1059 if (vmod.assign_v)
1061 /* If there was a semicolon found, add it back, plus anything
1062 after it. */
1063 if (semip)
1065 unsigned int l = p - variable_buffer;
1066 *(--semip) = ';';
1067 collapse_continuations (semip);
1068 variable_buffer_output (p2 + strlen (p2),
1069 semip, strlen (semip)+1);
1070 p = variable_buffer + l;
1072 record_target_var (filenames, p2,
1073 vmod.override_v ? o_override : o_file,
1074 &vmod, fstart);
1075 filenames = 0;
1076 continue;
1079 /* This is a normal target, _not_ a target-specific variable.
1080 Unquote any = in the dependency list. */
1081 find_char_unquote (lb_next, '=', 0, 0, 0);
1083 /* Remember the command prefix for this target. */
1084 prefix = cmd_prefix;
1086 /* We have some targets, so don't ignore the following commands. */
1087 no_targets = 0;
1089 /* Expand the dependencies, etc. */
1090 if (*lb_next != '\0')
1092 unsigned int l = p2 - variable_buffer;
1093 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1094 p2 = variable_buffer + l;
1096 /* Look for a semicolon in the expanded line. */
1097 if (cmdleft == 0)
1099 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1100 if (cmdleft != 0)
1101 *(cmdleft++) = '\0';
1105 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1106 p = strchr (p2, ':');
1107 while (p != 0 && p[-1] == '\\')
1109 char *q = &p[-1];
1110 int backslash = 0;
1111 while (*q-- == '\\')
1112 backslash = !backslash;
1113 if (backslash)
1114 p = strchr (p + 1, ':');
1115 else
1116 break;
1118 #ifdef _AMIGA
1119 /* Here, the situation is quite complicated. Let's have a look
1120 at a couple of targets:
1122 install: dev:make
1124 dev:make: make
1126 dev:make:: xyz
1128 The rule is that it's only a target, if there are TWO :'s
1129 OR a space around the :.
1131 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1132 || isspace ((unsigned char)p[-1])))
1133 p = 0;
1134 #endif
1135 #ifdef HAVE_DOS_PATHS
1137 int check_again;
1138 do {
1139 check_again = 0;
1140 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1141 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1142 isalpha ((unsigned char)p[-1]) &&
1143 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1144 p = strchr (p + 1, ':');
1145 check_again = 1;
1147 } while (check_again);
1149 #endif
1150 if (p != 0)
1152 struct nameseq *target;
1153 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1154 PARSEFS_NOGLOB);
1155 ++p2;
1156 if (target == 0)
1157 fatal (fstart, _("missing target pattern"));
1158 else if (target->next != 0)
1159 fatal (fstart, _("multiple target patterns"));
1160 pattern_percent = find_percent_cached (&target->name);
1161 pattern = target->name;
1162 if (pattern_percent == 0)
1163 fatal (fstart, _("target pattern contains no `%%'"));
1164 free_ns (target);
1166 else
1167 pattern = 0;
1169 /* Strip leading and trailing whitespaces. */
1170 beg = p2;
1171 end = beg + strlen (beg) - 1;
1172 strip_whitespace (&beg, &end);
1174 /* Put all the prerequisites here; they'll be parsed later. */
1175 if (beg <= end && *beg != '\0')
1176 depstr = xstrndup (beg, end - beg + 1);
1177 else
1178 depstr = 0;
1180 commands_idx = 0;
1181 if (cmdleft != 0)
1183 /* Semicolon means rest of line is a command. */
1184 unsigned int l = strlen (cmdleft);
1186 cmds_started = fstart->lineno;
1188 /* Add this command line to the buffer. */
1189 if (l + 2 > commands_len)
1191 commands_len = (l + 2) * 2;
1192 commands = xrealloc (commands, commands_len);
1194 memcpy (commands, cmdleft, l);
1195 commands_idx += l;
1196 commands[commands_idx++] = '\n';
1199 /* Determine if this target should be made default. We used to do
1200 this in record_files() but because of the delayed target recording
1201 and because preprocessor directives are legal in target's commands
1202 it is too late. Consider this fragment for example:
1204 foo:
1206 ifeq ($(.DEFAULT_GOAL),foo)
1208 endif
1210 Because the target is not recorded until after ifeq directive is
1211 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1212 would expect. Because of this we have to move the logic here. */
1214 if (set_default && default_goal_var->value[0] == '\0')
1216 const char *name;
1217 struct dep *d;
1218 struct nameseq *t = filenames;
1220 for (; t != 0; t = t->next)
1222 int reject = 0;
1223 name = t->name;
1225 /* We have nothing to do if this is an implicit rule. */
1226 if (strchr (name, '%') != 0)
1227 break;
1229 /* See if this target's name does not start with a `.',
1230 unless it contains a slash. */
1231 if (*name == '.' && strchr (name, '/') == 0
1232 #ifdef HAVE_DOS_PATHS
1233 && strchr (name, '\\') == 0
1234 #endif
1236 continue;
1239 /* If this file is a suffix, don't let it be
1240 the default goal file. */
1241 for (d = suffix_file->deps; d != 0; d = d->next)
1243 register struct dep *d2;
1244 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1246 reject = 1;
1247 break;
1249 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1251 unsigned int l = strlen (dep_name (d2));
1252 if (!strneq (name, dep_name (d2), l))
1253 continue;
1254 if (streq (name + l, dep_name (d)))
1256 reject = 1;
1257 break;
1261 if (reject)
1262 break;
1265 if (!reject)
1267 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1268 o_file, 0, NILF);
1269 break;
1274 continue;
1277 /* We get here except in the case that we just read a rule line.
1278 Record now the last rule we read, so following spurious
1279 commands are properly diagnosed. */
1280 rule_complete:
1281 record_waiting_files ();
1284 #undef word1eq
1286 if (conditionals->if_cmds)
1287 fatal (fstart, _("missing `endif'"));
1289 /* At eof, record the last rule. */
1290 record_waiting_files ();
1292 if (collapsed)
1293 free (collapsed);
1294 free (commands);
1298 /* Remove comments from LINE.
1299 This is done by copying the text at LINE onto itself. */
1301 static void
1302 remove_comments (char *line)
1304 char *comment;
1306 comment = find_char_unquote (line, '#', 0, 0, 0);
1308 if (comment != 0)
1309 /* Cut off the line at the #. */
1310 *comment = '\0';
1313 /* Execute a `undefine' directive.
1314 The undefine line has already been read, and NAME is the name of
1315 the variable to be undefined. */
1317 static void
1318 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1320 char *p, *var;
1322 /* Expand the variable name and find the beginning (NAME) and end. */
1323 var = allocated_variable_expand (name);
1324 name = next_token (var);
1325 if (*name == '\0')
1326 fatal (&ebuf->floc, _("empty variable name"));
1327 p = name + strlen (name) - 1;
1328 while (p > name && isblank ((unsigned char)*p))
1329 --p;
1330 p[1] = '\0';
1332 undefine_variable_global (name, p - name + 1, origin);
1333 free (var);
1336 /* Execute a `define' directive.
1337 The first line has already been read, and NAME is the name of
1338 the variable to be defined. The following lines remain to be read. */
1340 static struct variable *
1341 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1343 struct variable *v;
1344 enum variable_flavor flavor;
1345 struct floc defstart;
1346 int nlevels = 1;
1347 unsigned int length = 100;
1348 char *definition = xmalloc (length);
1349 unsigned int idx = 0;
1350 char *p, *var;
1352 defstart = ebuf->floc;
1354 p = parse_variable_definition (name, &flavor);
1355 if (p == NULL)
1356 /* No assignment token, so assume recursive. */
1357 flavor = f_recursive;
1358 else
1360 if (*(next_token (p)) != '\0')
1361 error (&defstart, _("extraneous text after `define' directive"));
1363 /* Chop the string before the assignment token to get the name. */
1364 p[flavor == f_recursive ? -1 : -2] = '\0';
1367 /* Expand the variable name and find the beginning (NAME) and end. */
1368 var = allocated_variable_expand (name);
1369 name = next_token (var);
1370 if (*name == '\0')
1371 fatal (&defstart, _("empty variable name"));
1372 p = name + strlen (name) - 1;
1373 while (p > name && isblank ((unsigned char)*p))
1374 --p;
1375 p[1] = '\0';
1377 /* Now read the value of the variable. */
1378 while (1)
1380 unsigned int len;
1381 char *line;
1382 long nlines = readline (ebuf);
1384 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1385 if (nlines < 0)
1386 fatal (&defstart, _("missing `endef', unterminated `define'"));
1388 ebuf->floc.lineno += nlines;
1389 line = ebuf->buffer;
1391 collapse_continuations (line);
1393 /* If the line doesn't begin with a tab, test to see if it introduces
1394 another define, or ends one. Stop if we find an 'endef' */
1395 if (line[0] != cmd_prefix)
1397 p = next_token (line);
1398 len = strlen (p);
1400 /* If this is another 'define', increment the level count. */
1401 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1402 && strneq (p, "define", 6))
1403 ++nlevels;
1405 /* If this is an 'endef', decrement the count. If it's now 0,
1406 we've found the last one. */
1407 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1408 && strneq (p, "endef", 5))
1410 p += 5;
1411 remove_comments (p);
1412 if (*(next_token (p)) != '\0')
1413 error (&ebuf->floc,
1414 _("extraneous text after `endef' directive"));
1416 if (--nlevels == 0)
1417 break;
1421 /* Add this line to the variable definition. */
1422 len = strlen (line);
1423 if (idx + len + 1 > length)
1425 length = (idx + len) * 2;
1426 definition = xrealloc (definition, length + 1);
1429 memcpy (&definition[idx], line, len);
1430 idx += len;
1431 /* Separate lines with a newline. */
1432 definition[idx++] = '\n';
1435 /* We've got what we need; define the variable. */
1436 if (idx == 0)
1437 definition[0] = '\0';
1438 else
1439 definition[idx - 1] = '\0';
1441 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1442 free (definition);
1443 free (var);
1444 return (v);
1447 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1448 "ifneq", "else" and "endif".
1449 LINE is the input line, with the command as its first word.
1451 FILENAME and LINENO are the filename and line number in the
1452 current makefile. They are used for error messages.
1454 Value is -2 if the line is not a conditional at all,
1455 -1 if the line is an invalid conditional,
1456 0 if following text should be interpreted,
1457 1 if following text should be ignored. */
1459 static int
1460 conditional_line (char *line, int len, const struct floc *flocp)
1462 char *cmdname;
1463 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1464 unsigned int i;
1465 unsigned int o;
1467 /* Compare a word, both length and contents. */
1468 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1469 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1471 /* Make sure this line is a conditional. */
1472 chkword ("ifdef", c_ifdef)
1473 else chkword ("ifndef", c_ifndef)
1474 else chkword ("ifeq", c_ifeq)
1475 else chkword ("ifneq", c_ifneq)
1476 else chkword ("else", c_else)
1477 else chkword ("endif", c_endif)
1478 else
1479 return -2;
1481 /* Found one: skip past it and any whitespace after it. */
1482 line = next_token (line + len);
1484 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1486 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1487 if (cmdtype == c_endif)
1489 if (*line != '\0')
1490 EXTRANEOUS ();
1492 if (!conditionals->if_cmds)
1493 fatal (flocp, _("extraneous `%s'"), cmdname);
1495 --conditionals->if_cmds;
1497 goto DONE;
1500 /* An 'else' statement can either be simple, or it can have another
1501 conditional after it. */
1502 if (cmdtype == c_else)
1504 const char *p;
1506 if (!conditionals->if_cmds)
1507 fatal (flocp, _("extraneous `%s'"), cmdname);
1509 o = conditionals->if_cmds - 1;
1511 if (conditionals->seen_else[o])
1512 fatal (flocp, _("only one `else' per conditional"));
1514 /* Change the state of ignorance. */
1515 switch (conditionals->ignoring[o])
1517 case 0:
1518 /* We've just been interpreting. Never do it again. */
1519 conditionals->ignoring[o] = 2;
1520 break;
1521 case 1:
1522 /* We've never interpreted yet. Maybe this time! */
1523 conditionals->ignoring[o] = 0;
1524 break;
1527 /* It's a simple 'else'. */
1528 if (*line == '\0')
1530 conditionals->seen_else[o] = 1;
1531 goto DONE;
1534 /* The 'else' has extra text. That text must be another conditional
1535 and cannot be an 'else' or 'endif'. */
1537 /* Find the length of the next word. */
1538 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1540 len = p - line;
1542 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1543 if (word1eq("else") || word1eq("endif")
1544 || conditional_line (line, len, flocp) < 0)
1545 EXTRANEOUS ();
1546 else
1548 /* conditional_line() created a new level of conditional.
1549 Raise it back to this level. */
1550 if (conditionals->ignoring[o] < 2)
1551 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1552 --conditionals->if_cmds;
1555 goto DONE;
1558 if (conditionals->allocated == 0)
1560 conditionals->allocated = 5;
1561 conditionals->ignoring = xmalloc (conditionals->allocated);
1562 conditionals->seen_else = xmalloc (conditionals->allocated);
1565 o = conditionals->if_cmds++;
1566 if (conditionals->if_cmds > conditionals->allocated)
1568 conditionals->allocated += 5;
1569 conditionals->ignoring = xrealloc (conditionals->ignoring,
1570 conditionals->allocated);
1571 conditionals->seen_else = xrealloc (conditionals->seen_else,
1572 conditionals->allocated);
1575 /* Record that we have seen an `if...' but no `else' so far. */
1576 conditionals->seen_else[o] = 0;
1578 /* Search through the stack to see if we're already ignoring. */
1579 for (i = 0; i < o; ++i)
1580 if (conditionals->ignoring[i])
1582 /* We are already ignoring, so just push a level to match the next
1583 "else" or "endif", and keep ignoring. We don't want to expand
1584 variables in the condition. */
1585 conditionals->ignoring[o] = 1;
1586 return 1;
1589 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1591 char *var;
1592 struct variable *v;
1593 char *p;
1595 /* Expand the thing we're looking up, so we can use indirect and
1596 constructed variable names. */
1597 var = allocated_variable_expand (line);
1599 /* Make sure there's only one variable name to test. */
1600 p = end_of_token (var);
1601 i = p - var;
1602 p = next_token (p);
1603 if (*p != '\0')
1604 return -1;
1606 var[i] = '\0';
1607 v = lookup_variable (var, i);
1609 conditionals->ignoring[o] =
1610 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1612 free (var);
1614 else
1616 /* "ifeq" or "ifneq". */
1617 char *s1, *s2;
1618 unsigned int l;
1619 char termin = *line == '(' ? ',' : *line;
1621 if (termin != ',' && termin != '"' && termin != '\'')
1622 return -1;
1624 s1 = ++line;
1625 /* Find the end of the first string. */
1626 if (termin == ',')
1628 int count = 0;
1629 for (; *line != '\0'; ++line)
1630 if (*line == '(')
1631 ++count;
1632 else if (*line == ')')
1633 --count;
1634 else if (*line == ',' && count <= 0)
1635 break;
1637 else
1638 while (*line != '\0' && *line != termin)
1639 ++line;
1641 if (*line == '\0')
1642 return -1;
1644 if (termin == ',')
1646 /* Strip blanks after the first string. */
1647 char *p = line++;
1648 while (isblank ((unsigned char)p[-1]))
1649 --p;
1650 *p = '\0';
1652 else
1653 *line++ = '\0';
1655 s2 = variable_expand (s1);
1656 /* We must allocate a new copy of the expanded string because
1657 variable_expand re-uses the same buffer. */
1658 l = strlen (s2);
1659 s1 = alloca (l + 1);
1660 memcpy (s1, s2, l + 1);
1662 if (termin != ',')
1663 /* Find the start of the second string. */
1664 line = next_token (line);
1666 termin = termin == ',' ? ')' : *line;
1667 if (termin != ')' && termin != '"' && termin != '\'')
1668 return -1;
1670 /* Find the end of the second string. */
1671 if (termin == ')')
1673 int count = 0;
1674 s2 = next_token (line);
1675 for (line = s2; *line != '\0'; ++line)
1677 if (*line == '(')
1678 ++count;
1679 else if (*line == ')')
1681 if (count <= 0)
1682 break;
1683 else
1684 --count;
1688 else
1690 ++line;
1691 s2 = line;
1692 while (*line != '\0' && *line != termin)
1693 ++line;
1696 if (*line == '\0')
1697 return -1;
1699 *line = '\0';
1700 line = next_token (++line);
1701 if (*line != '\0')
1702 EXTRANEOUS ();
1704 s2 = variable_expand (s2);
1705 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1708 DONE:
1709 /* Search through the stack to see if we're ignoring. */
1710 for (i = 0; i < conditionals->if_cmds; ++i)
1711 if (conditionals->ignoring[i])
1712 return 1;
1713 return 0;
1717 /* Record target-specific variable values for files FILENAMES.
1718 TWO_COLON is nonzero if a double colon was used.
1720 The links of FILENAMES are freed, and so are any names in it
1721 that are not incorporated into other data structures.
1723 If the target is a pattern, add the variable to the pattern-specific
1724 variable value list. */
1726 static void
1727 record_target_var (struct nameseq *filenames, char *defn,
1728 enum variable_origin origin, struct vmodifiers *vmod,
1729 const struct floc *flocp)
1731 struct nameseq *nextf;
1732 struct variable_set_list *global;
1734 global = current_variable_set_list;
1736 /* If the variable is an append version, store that but treat it as a
1737 normal recursive variable. */
1739 for (; filenames != 0; filenames = nextf)
1741 struct variable *v;
1742 const char *name = filenames->name;
1743 const char *fname;
1744 const char *percent;
1745 struct pattern_var *p;
1747 nextf = filenames->next;
1748 free_ns (filenames);
1750 /* If it's a pattern target, then add it to the pattern-specific
1751 variable list. */
1752 percent = find_percent_cached (&name);
1753 if (percent)
1755 /* Get a reference for this pattern-specific variable struct. */
1756 p = create_pattern_var (name, percent);
1757 p->variable.fileinfo = *flocp;
1758 /* I don't think this can fail since we already determined it was a
1759 variable definition. */
1760 v = assign_variable_definition (&p->variable, defn);
1761 assert (v != 0);
1763 v->origin = origin;
1764 if (v->flavor == f_simple)
1765 v->value = allocated_variable_expand (v->value);
1766 else
1767 v->value = xstrdup (v->value);
1769 fname = p->target;
1771 else
1773 struct file *f;
1775 /* Get a file reference for this file, and initialize it.
1776 We don't want to just call enter_file() because that allocates a
1777 new entry if the file is a double-colon, which we don't want in
1778 this situation. */
1779 f = lookup_file (name);
1780 if (!f)
1781 f = enter_file (strcache_add (name));
1782 else if (f->double_colon)
1783 f = f->double_colon;
1785 initialize_file_variables (f, 1);
1786 fname = f->name;
1788 current_variable_set_list = f->variables;
1789 v = try_variable_definition (flocp, defn, origin, 1);
1790 if (!v)
1791 fatal (flocp, _("Malformed target-specific variable definition"));
1792 current_variable_set_list = global;
1795 /* Set up the variable to be *-specific. */
1796 v->per_target = 1;
1797 v->private_var = vmod->private_v;
1798 v->export = vmod->export_v ? v_export : v_default;
1800 /* If it's not an override, check to see if there was a command-line
1801 setting. If so, reset the value. */
1802 if (v->origin != o_override)
1804 struct variable *gv;
1805 int len = strlen(v->name);
1807 gv = lookup_variable (v->name, len);
1808 if (gv && v != gv
1809 && (gv->origin == o_env_override || gv->origin == o_command))
1811 if (v->value != 0)
1812 free (v->value);
1813 v->value = xstrdup (gv->value);
1814 v->origin = gv->origin;
1815 v->recursive = gv->recursive;
1816 v->append = 0;
1822 /* Record a description line for files FILENAMES,
1823 with dependencies DEPS, commands to execute described
1824 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1825 TWO_COLON is nonzero if a double colon was used.
1826 If not nil, PATTERN is the `%' pattern to make this
1827 a static pattern rule, and PATTERN_PERCENT is a pointer
1828 to the `%' within it.
1830 The links of FILENAMES are freed, and so are any names in it
1831 that are not incorporated into other data structures. */
1833 static void
1834 record_files (struct nameseq *filenames, const char *pattern,
1835 const char *pattern_percent, char *depstr,
1836 unsigned int cmds_started, char *commands,
1837 unsigned int commands_idx, int two_colon,
1838 char prefix, const struct floc *flocp)
1840 struct commands *cmds;
1841 struct dep *deps;
1842 const char *implicit_percent;
1843 const char *name;
1845 /* If we've already snapped deps, that means we're in an eval being
1846 resolved after the makefiles have been read in. We can't add more rules
1847 at this time, since they won't get snapped and we'll get core dumps.
1848 See Savannah bug # 12124. */
1849 if (snapped_deps)
1850 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1852 /* Determine if this is a pattern rule or not. */
1853 name = filenames->name;
1854 implicit_percent = find_percent_cached (&name);
1856 /* If there's a recipe, set up a struct for it. */
1857 if (commands_idx > 0)
1859 cmds = xmalloc (sizeof (struct commands));
1860 cmds->fileinfo.filenm = flocp->filenm;
1861 cmds->fileinfo.lineno = cmds_started;
1862 cmds->commands = xstrndup (commands, commands_idx);
1863 cmds->command_lines = 0;
1864 cmds->recipe_prefix = prefix;
1866 else
1867 cmds = 0;
1869 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1870 expansion: if so, snap_deps() will do it. */
1871 if (depstr == 0)
1872 deps = 0;
1873 else if (second_expansion && strchr (depstr, '$'))
1875 deps = alloc_dep ();
1876 deps->name = depstr;
1877 deps->need_2nd_expansion = 1;
1878 deps->staticpattern = pattern != 0;
1880 else
1882 deps = split_prereqs (depstr);
1883 free (depstr);
1885 /* We'll enter static pattern prereqs later when we have the stem. We
1886 don't want to enter pattern rules at all so that we don't think that
1887 they ought to exist (make manual "Implicit Rule Search Algorithm",
1888 item 5c). */
1889 if (! pattern && ! implicit_percent)
1890 deps = enter_prereqs (deps, NULL);
1893 /* For implicit rules, _all_ the targets must have a pattern. That means we
1894 can test the first one to see if we're working with an implicit rule; if
1895 so we handle it specially. */
1897 if (implicit_percent)
1899 struct nameseq *nextf;
1900 const char **targets, **target_pats;
1901 unsigned int c;
1903 if (pattern != 0)
1904 fatal (flocp, _("mixed implicit and static pattern rules"));
1906 /* Count the targets to create an array of target names.
1907 We already have the first one. */
1908 nextf = filenames->next;
1909 free_ns (filenames);
1910 filenames = nextf;
1912 for (c = 1; nextf; ++c, nextf = nextf->next)
1914 targets = xmalloc (c * sizeof (const char *));
1915 target_pats = xmalloc (c * sizeof (const char *));
1917 targets[0] = name;
1918 target_pats[0] = implicit_percent;
1920 c = 1;
1921 while (filenames)
1923 name = filenames->name;
1924 implicit_percent = find_percent_cached (&name);
1926 if (implicit_percent == 0)
1927 fatal (flocp, _("mixed implicit and normal rules"));
1929 targets[c] = name;
1930 target_pats[c] = implicit_percent;
1931 ++c;
1933 nextf = filenames->next;
1934 free_ns (filenames);
1935 filenames = nextf;
1938 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1940 return;
1944 /* Walk through each target and create it in the database.
1945 We already set up the first target, above. */
1946 while (1)
1948 struct nameseq *nextf = filenames->next;
1949 struct file *f;
1950 struct dep *this = 0;
1952 free_ns (filenames);
1954 /* Check for special targets. Do it here instead of, say, snap_deps()
1955 so that we can immediately use the value. */
1956 if (streq (name, ".POSIX"))
1958 posix_pedantic = 1;
1959 define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
1961 else if (streq (name, ".SECONDEXPANSION"))
1962 second_expansion = 1;
1963 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
1964 else if (streq (name, ".ONESHELL"))
1965 one_shell = 1;
1966 #endif
1968 /* If this is a static pattern rule:
1969 `targets: target%pattern: prereq%pattern; recipe',
1970 make sure the pattern matches this target name. */
1971 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1972 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1973 else if (deps)
1974 /* If there are multiple targets, copy the chain DEPS for all but the
1975 last one. It is not safe for the same deps to go in more than one
1976 place in the database. */
1977 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1979 /* Find or create an entry in the file database for this target. */
1980 if (!two_colon)
1982 /* Single-colon. Combine this rule with the file's existing record,
1983 if any. */
1984 f = enter_file (strcache_add (name));
1985 if (f->double_colon)
1986 fatal (flocp,
1987 _("target file `%s' has both : and :: entries"), f->name);
1989 /* If CMDS == F->CMDS, this target was listed in this rule
1990 more than once. Just give a warning since this is harmless. */
1991 if (cmds != 0 && cmds == f->cmds)
1992 error (flocp,
1993 _("target `%s' given more than once in the same rule."),
1994 f->name);
1996 /* Check for two single-colon entries both with commands.
1997 Check is_target so that we don't lose on files such as .c.o
1998 whose commands were preinitialized. */
1999 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2001 error (&cmds->fileinfo,
2002 _("warning: overriding recipe for target `%s'"),
2003 f->name);
2004 error (&f->cmds->fileinfo,
2005 _("warning: ignoring old recipe for target `%s'"),
2006 f->name);
2009 /* Defining .DEFAULT with no deps or cmds clears it. */
2010 if (f == default_file && this == 0 && cmds == 0)
2011 f->cmds = 0;
2012 if (cmds != 0)
2013 f->cmds = cmds;
2015 /* Defining .SUFFIXES with no dependencies clears out the list of
2016 suffixes. */
2017 if (f == suffix_file && this == 0)
2019 free_dep_chain (f->deps);
2020 f->deps = 0;
2023 else
2025 /* Double-colon. Make a new record even if there already is one. */
2026 f = lookup_file (name);
2028 /* Check for both : and :: rules. Check is_target so we don't lose
2029 on default suffix rules or makefiles. */
2030 if (f != 0 && f->is_target && !f->double_colon)
2031 fatal (flocp,
2032 _("target file `%s' has both : and :: entries"), f->name);
2034 f = enter_file (strcache_add (name));
2035 /* If there was an existing entry and it was a double-colon entry,
2036 enter_file will have returned a new one, making it the prev
2037 pointer of the old one, and setting its double_colon pointer to
2038 the first one. */
2039 if (f->double_colon == 0)
2040 /* This is the first entry for this name, so we must set its
2041 double_colon pointer to itself. */
2042 f->double_colon = f;
2044 f->cmds = cmds;
2047 f->is_target = 1;
2049 /* If this is a static pattern rule, set the stem to the part of its
2050 name that matched the `%' in the pattern, so you can use $* in the
2051 commands. If we didn't do it before, enter the prereqs now. */
2052 if (pattern)
2054 static const char *percent = "%";
2055 char *buffer = variable_expand ("");
2056 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2057 pattern_percent+1, percent+1);
2058 f->stem = strcache_add_len (buffer, o - buffer);
2059 if (this)
2061 if (! this->need_2nd_expansion)
2062 this = enter_prereqs (this, f->stem);
2063 else
2064 this->stem = f->stem;
2068 /* Add the dependencies to this file entry. */
2069 if (this != 0)
2071 /* Add the file's old deps and the new ones in THIS together. */
2072 if (f->deps == 0)
2073 f->deps = this;
2074 else if (cmds != 0)
2076 struct dep *d = this;
2078 /* If this rule has commands, put these deps first. */
2079 while (d->next != 0)
2080 d = d->next;
2082 d->next = f->deps;
2083 f->deps = this;
2085 else
2087 struct dep *d = f->deps;
2089 /* A rule without commands: put its prereqs at the end. */
2090 while (d->next != 0)
2091 d = d->next;
2093 d->next = this;
2097 name = f->name;
2099 /* All done! Set up for the next one. */
2100 if (nextf == 0)
2101 break;
2103 filenames = nextf;
2105 /* Reduce escaped percents. If there are any unescaped it's an error */
2106 name = filenames->name;
2107 if (find_percent_cached (&name))
2108 fatal (flocp, _("mixed implicit and normal rules"));
2112 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2113 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2114 Quoting backslashes are removed from STRING by compacting it into
2115 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2116 one, or nil if there are none. STOPCHARs inside variable references are
2117 ignored if IGNOREVARS is true.
2119 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2121 static char *
2122 find_char_unquote (char *string, int stop1, int stop2, int blank,
2123 int ignorevars)
2125 unsigned int string_len = 0;
2126 char *p = string;
2128 if (ignorevars)
2129 ignorevars = '$';
2131 while (1)
2133 if (stop2 && blank)
2134 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2135 && ! isblank ((unsigned char) *p))
2136 ++p;
2137 else if (stop2)
2138 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2139 ++p;
2140 else if (blank)
2141 while (*p != '\0' && *p != ignorevars && *p != stop1
2142 && ! isblank ((unsigned char) *p))
2143 ++p;
2144 else
2145 while (*p != '\0' && *p != ignorevars && *p != stop1)
2146 ++p;
2148 if (*p == '\0')
2149 break;
2151 /* If we stopped due to a variable reference, skip over its contents. */
2152 if (*p == ignorevars)
2154 char openparen = p[1];
2156 p += 2;
2158 /* Skip the contents of a non-quoted, multi-char variable ref. */
2159 if (openparen == '(' || openparen == '{')
2161 unsigned int pcount = 1;
2162 char closeparen = (openparen == '(' ? ')' : '}');
2164 while (*p)
2166 if (*p == openparen)
2167 ++pcount;
2168 else if (*p == closeparen)
2169 if (--pcount == 0)
2171 ++p;
2172 break;
2174 ++p;
2178 /* Skipped the variable reference: look for STOPCHARS again. */
2179 continue;
2182 if (p > string && p[-1] == '\\')
2184 /* Search for more backslashes. */
2185 int i = -2;
2186 while (&p[i] >= string && p[i] == '\\')
2187 --i;
2188 ++i;
2189 /* Only compute the length if really needed. */
2190 if (string_len == 0)
2191 string_len = strlen (string);
2192 /* The number of backslashes is now -I.
2193 Copy P over itself to swallow half of them. */
2194 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2195 p += i/2;
2196 if (i % 2 == 0)
2197 /* All the backslashes quoted each other; the STOPCHAR was
2198 unquoted. */
2199 return p;
2201 /* The STOPCHAR was quoted by a backslash. Look for another. */
2203 else
2204 /* No backslash in sight. */
2205 return p;
2208 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2209 return 0;
2212 /* Search PATTERN for an unquoted % and handle quoting. */
2214 char *
2215 find_percent (char *pattern)
2217 return find_char_unquote (pattern, '%', 0, 0, 0);
2220 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2221 the % or NULL if no % was found.
2222 This version is used with strings in the string cache: if there's a need to
2223 modify the string a new version will be added to the string cache and
2224 *STRING will be set to that. */
2226 const char *
2227 find_percent_cached (const char **string)
2229 const char *p = *string;
2230 char *new = 0;
2231 int slen = 0;
2233 /* If the first char is a % return now. This lets us avoid extra tests
2234 inside the loop. */
2235 if (*p == '%')
2236 return p;
2238 while (1)
2240 while (*p != '\0' && *p != '%')
2241 ++p;
2243 if (*p == '\0')
2244 break;
2246 /* See if this % is escaped with a backslash; if not we're done. */
2247 if (p[-1] != '\\')
2248 break;
2251 /* Search for more backslashes. */
2252 char *pv;
2253 int i = -2;
2255 while (&p[i] >= *string && p[i] == '\\')
2256 --i;
2257 ++i;
2259 /* At this point we know we'll need to allocate a new string.
2260 Make a copy if we haven't yet done so. */
2261 if (! new)
2263 slen = strlen (*string);
2264 new = alloca (slen + 1);
2265 memcpy (new, *string, slen + 1);
2266 p = new + (p - *string);
2267 *string = new;
2270 /* At this point *string, p, and new all point into the same string.
2271 Get a non-const version of p so we can modify new. */
2272 pv = new + (p - *string);
2274 /* The number of backslashes is now -I.
2275 Copy P over itself to swallow half of them. */
2276 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2277 p += i/2;
2279 /* If the backslashes quoted each other; the % was unquoted. */
2280 if (i % 2 == 0)
2281 break;
2285 /* If we had to change STRING, add it to the strcache. */
2286 if (new)
2288 *string = strcache_add (*string);
2289 p = *string + (p - new);
2292 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2293 return (*p == '\0') ? NULL : p;
2296 /* Find the next line of text in an eval buffer, combining continuation lines
2297 into one line.
2298 Return the number of actual lines read (> 1 if continuation lines).
2299 Returns -1 if there's nothing left in the buffer.
2301 After this function, ebuf->buffer points to the first character of the
2302 line we just found.
2305 /* Read a line of text from a STRING.
2306 Since we aren't really reading from a file, don't bother with linenumbers.
2309 static unsigned long
2310 readstring (struct ebuffer *ebuf)
2312 char *eol;
2314 /* If there is nothing left in this buffer, return 0. */
2315 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2316 return -1;
2318 /* Set up a new starting point for the buffer, and find the end of the
2319 next logical line (taking into account backslash/newline pairs). */
2321 eol = ebuf->buffer = ebuf->bufnext;
2323 while (1)
2325 int backslash = 0;
2326 const char *bol = eol;
2327 const char *p;
2329 /* Find the next newline. At EOS, stop. */
2330 p = eol = strchr (eol , '\n');
2331 if (!eol)
2333 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2334 return 0;
2337 /* Found a newline; if it's escaped continue; else we're done. */
2338 while (p > bol && *(--p) == '\\')
2339 backslash = !backslash;
2340 if (!backslash)
2341 break;
2342 ++eol;
2345 /* Overwrite the newline char. */
2346 *eol = '\0';
2347 ebuf->bufnext = eol+1;
2349 return 0;
2352 static long
2353 readline (struct ebuffer *ebuf)
2355 char *p;
2356 char *end;
2357 char *start;
2358 long nlines = 0;
2360 /* The behaviors between string and stream buffers are different enough to
2361 warrant different functions. Do the Right Thing. */
2363 if (!ebuf->fp)
2364 return readstring (ebuf);
2366 /* When reading from a file, we always start over at the beginning of the
2367 buffer for each new line. */
2369 p = start = ebuf->bufstart;
2370 end = p + ebuf->size;
2371 *p = '\0';
2373 while (fgets (p, end - p, ebuf->fp) != 0)
2375 char *p2;
2376 unsigned long len;
2377 int backslash;
2379 len = strlen (p);
2380 if (len == 0)
2382 /* This only happens when the first thing on the line is a '\0'.
2383 It is a pretty hopeless case, but (wonder of wonders) Athena
2384 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2385 There is nothing really to be done; we synthesize a newline so
2386 the following line doesn't appear to be part of this line. */
2387 error (&ebuf->floc,
2388 _("warning: NUL character seen; rest of line ignored"));
2389 p[0] = '\n';
2390 len = 1;
2393 /* Jump past the text we just read. */
2394 p += len;
2396 /* If the last char isn't a newline, the whole line didn't fit into the
2397 buffer. Get some more buffer and try again. */
2398 if (p[-1] != '\n')
2399 goto more_buffer;
2401 /* We got a newline, so add one to the count of lines. */
2402 ++nlines;
2404 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2405 /* Check to see if the line was really ended with CRLF; if so ignore
2406 the CR. */
2407 if ((p - start) > 1 && p[-2] == '\r')
2409 --p;
2410 p[-1] = '\n';
2412 #endif
2414 backslash = 0;
2415 for (p2 = p - 2; p2 >= start; --p2)
2417 if (*p2 != '\\')
2418 break;
2419 backslash = !backslash;
2422 if (!backslash)
2424 p[-1] = '\0';
2425 break;
2428 /* It was a backslash/newline combo. If we have more space, read
2429 another line. */
2430 if (end - p >= 80)
2431 continue;
2433 /* We need more space at the end of our buffer, so realloc it.
2434 Make sure to preserve the current offset of p. */
2435 more_buffer:
2437 unsigned long off = p - start;
2438 ebuf->size *= 2;
2439 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2440 p = start + off;
2441 end = start + ebuf->size;
2442 *p = '\0';
2446 if (ferror (ebuf->fp))
2447 pfatal_with_name (ebuf->floc.filenm);
2449 /* If we found some lines, return how many.
2450 If we didn't, but we did find _something_, that indicates we read the last
2451 line of a file with no final newline; return 1.
2452 If we read nothing, we're at EOF; return -1. */
2454 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2457 /* Parse the next "makefile word" from the input buffer, and return info
2458 about it.
2460 A "makefile word" is one of:
2462 w_bogus Should never happen
2463 w_eol End of input
2464 w_static A static word; cannot be expanded
2465 w_variable A word containing one or more variables/functions
2466 w_colon A colon
2467 w_dcolon A double-colon
2468 w_semicolon A semicolon
2469 w_varassign A variable assignment operator (=, :=, +=, ?=, or !=)
2471 Note that this function is only used when reading certain parts of the
2472 makefile. Don't use it where special rules hold sway (RHS of a variable,
2473 in a command list, etc.) */
2475 static enum make_word_type
2476 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2478 enum make_word_type wtype = w_bogus;
2479 char *p = buffer, *beg;
2480 char c;
2482 /* Skip any leading whitespace. */
2483 while (isblank ((unsigned char)*p))
2484 ++p;
2486 beg = p;
2487 c = *(p++);
2488 switch (c)
2490 case '\0':
2491 wtype = w_eol;
2492 break;
2494 case ';':
2495 wtype = w_semicolon;
2496 break;
2498 case '=':
2499 wtype = w_varassign;
2500 break;
2502 case ':':
2503 wtype = w_colon;
2504 switch (*p)
2506 case ':':
2507 ++p;
2508 wtype = w_dcolon;
2509 break;
2511 case '=':
2512 ++p;
2513 wtype = w_varassign;
2514 break;
2516 break;
2518 case '+':
2519 case '?':
2520 case '!':
2521 if (*p == '=')
2523 ++p;
2524 wtype = w_varassign;
2525 break;
2528 default:
2529 if (delim && strchr (delim, c))
2530 wtype = w_static;
2531 break;
2534 /* Did we find something? If so, return now. */
2535 if (wtype != w_bogus)
2536 goto done;
2538 /* This is some non-operator word. A word consists of the longest
2539 string of characters that doesn't contain whitespace, one of [:=#],
2540 or [?+!]=, or one of the chars in the DELIM string. */
2542 /* We start out assuming a static word; if we see a variable we'll
2543 adjust our assumptions then. */
2544 wtype = w_static;
2546 /* We already found the first value of "c", above. */
2547 while (1)
2549 char closeparen;
2550 int count;
2552 switch (c)
2554 case '\0':
2555 case ' ':
2556 case '\t':
2557 case '=':
2558 goto done_word;
2560 case ':':
2561 #ifdef HAVE_DOS_PATHS
2562 /* A word CAN include a colon in its drive spec. The drive
2563 spec is allowed either at the beginning of a word, or as part
2564 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2565 if (!(p - beg >= 2
2566 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2567 && (p - beg == 2 || p[-3] == '(')))
2568 #endif
2569 goto done_word;
2571 case '$':
2572 c = *(p++);
2573 if (c == '$')
2574 break;
2576 /* This is a variable reference, so note that it's expandable.
2577 Then read it to the matching close paren. */
2578 wtype = w_variable;
2580 if (c == '(')
2581 closeparen = ')';
2582 else if (c == '{')
2583 closeparen = '}';
2584 else
2585 /* This is a single-letter variable reference. */
2586 break;
2588 for (count=0; *p != '\0'; ++p)
2590 if (*p == c)
2591 ++count;
2592 else if (*p == closeparen && --count < 0)
2594 ++p;
2595 break;
2598 break;
2600 case '?':
2601 case '+':
2602 if (*p == '=')
2603 goto done_word;
2604 break;
2606 case '\\':
2607 switch (*p)
2609 case ':':
2610 case ';':
2611 case '=':
2612 case '\\':
2613 ++p;
2614 break;
2616 break;
2618 default:
2619 if (delim && strchr (delim, c))
2620 goto done_word;
2621 break;
2624 c = *(p++);
2626 done_word:
2627 --p;
2629 done:
2630 if (startp)
2631 *startp = beg;
2632 if (length)
2633 *length = p - beg;
2634 return wtype;
2637 /* Construct the list of include directories
2638 from the arguments and the default list. */
2640 void
2641 construct_include_path (const char **arg_dirs)
2643 #ifdef VAXC /* just don't ask ... */
2644 stat_t stbuf;
2645 #else
2646 struct stat stbuf;
2647 #endif
2648 const char **dirs;
2649 const char **cpp;
2650 unsigned int idx;
2652 /* Compute the number of pointers we need in the table. */
2653 idx = sizeof (default_include_directories) / sizeof (const char *);
2654 if (arg_dirs)
2655 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2656 ++idx;
2658 #ifdef __MSDOS__
2659 /* Add one for $DJDIR. */
2660 ++idx;
2661 #endif
2663 dirs = xmalloc (idx * sizeof (const char *));
2665 idx = 0;
2666 max_incl_len = 0;
2668 /* First consider any dirs specified with -I switches.
2669 Ignore any that don't exist. Remember the maximum string length. */
2671 if (arg_dirs)
2672 while (*arg_dirs != 0)
2674 const char *dir = *(arg_dirs++);
2675 char *expanded = 0;
2676 int e;
2678 if (dir[0] == '~')
2680 expanded = tilde_expand (dir);
2681 if (expanded != 0)
2682 dir = expanded;
2685 EINTRLOOP (e, stat (dir, &stbuf));
2686 if (e == 0 && S_ISDIR (stbuf.st_mode))
2688 unsigned int len = strlen (dir);
2689 /* If dir name is written with trailing slashes, discard them. */
2690 while (len > 1 && dir[len - 1] == '/')
2691 --len;
2692 if (len > max_incl_len)
2693 max_incl_len = len;
2694 dirs[idx++] = strcache_add_len (dir, len);
2697 if (expanded)
2698 free (expanded);
2701 /* Now add the standard default dirs at the end. */
2703 #ifdef __MSDOS__
2705 /* The environment variable $DJDIR holds the root of the DJGPP directory
2706 tree; add ${DJDIR}/include. */
2707 struct variable *djdir = lookup_variable ("DJDIR", 5);
2709 if (djdir)
2711 unsigned int len = strlen (djdir->value) + 8;
2712 char *defdir = alloca (len + 1);
2714 strcat (strcpy (defdir, djdir->value), "/include");
2715 dirs[idx++] = strcache_add (defdir);
2717 if (len > max_incl_len)
2718 max_incl_len = len;
2721 #endif
2723 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2725 int e;
2727 EINTRLOOP (e, stat (*cpp, &stbuf));
2728 if (e == 0 && S_ISDIR (stbuf.st_mode))
2730 unsigned int len = strlen (*cpp);
2731 /* If dir name is written with trailing slashes, discard them. */
2732 while (len > 1 && (*cpp)[len - 1] == '/')
2733 --len;
2734 if (len > max_incl_len)
2735 max_incl_len = len;
2736 dirs[idx++] = strcache_add_len (*cpp, len);
2740 dirs[idx] = 0;
2742 /* Now add each dir to the .INCLUDE_DIRS variable. */
2744 for (cpp = dirs; *cpp != 0; ++cpp)
2745 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2746 o_default, f_append, 0);
2748 include_directories = dirs;
2751 /* Expand ~ or ~USER at the beginning of NAME.
2752 Return a newly malloc'd string or 0. */
2754 char *
2755 tilde_expand (const char *name)
2757 #ifndef VMS
2758 if (name[1] == '/' || name[1] == '\0')
2760 extern char *getenv ();
2761 char *home_dir;
2762 int is_variable;
2765 /* Turn off --warn-undefined-variables while we expand HOME. */
2766 int save = warn_undefined_variables_flag;
2767 warn_undefined_variables_flag = 0;
2769 home_dir = allocated_variable_expand ("$(HOME)");
2771 warn_undefined_variables_flag = save;
2774 is_variable = home_dir[0] != '\0';
2775 if (!is_variable)
2777 free (home_dir);
2778 home_dir = getenv ("HOME");
2780 # if !defined(_AMIGA) && !defined(WINDOWS32)
2781 if (home_dir == 0 || home_dir[0] == '\0')
2783 extern char *getlogin ();
2784 char *logname = getlogin ();
2785 home_dir = 0;
2786 if (logname != 0)
2788 struct passwd *p = getpwnam (logname);
2789 if (p != 0)
2790 home_dir = p->pw_dir;
2793 # endif /* !AMIGA && !WINDOWS32 */
2794 if (home_dir != 0)
2796 char *new = xstrdup (concat (2, home_dir, name + 1));
2797 if (is_variable)
2798 free (home_dir);
2799 return new;
2802 # if !defined(_AMIGA) && !defined(WINDOWS32)
2803 else
2805 struct passwd *pwent;
2806 char *userend = strchr (name + 1, '/');
2807 if (userend != 0)
2808 *userend = '\0';
2809 pwent = getpwnam (name + 1);
2810 if (pwent != 0)
2812 if (userend == 0)
2813 return xstrdup (pwent->pw_dir);
2814 else
2815 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2817 else if (userend != 0)
2818 *userend = '/';
2820 # endif /* !AMIGA && !WINDOWS32 */
2821 #endif /* !VMS */
2822 return 0;
2825 /* Parse a string into a sequence of filenames represented as a chain of
2826 struct nameseq's and return that chain. Optionally expand the strings via
2827 glob().
2829 The string is passed as STRINGP, the address of a string pointer.
2830 The string pointer is updated to point at the first character
2831 not parsed, which either is a null char or equals STOPCHAR.
2833 SIZE is how big to construct chain elements.
2834 This is useful if we want them actually to be other structures
2835 that have room for additional info.
2837 PREFIX, if non-null, is added to the beginning of each filename.
2839 FLAGS allows one or more of the following bitflags to be set:
2840 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2841 PARSEFS_NOAR - Do not check filenames for archive references
2842 PARSEFS_NOGLOB - Do not expand globbing characters
2843 PARSEFS_EXISTS - Only return globbed files that actually exist
2844 (cannot also set NOGLOB)
2845 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2848 void *
2849 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2850 const char *prefix, int flags)
2852 extern void dir_setup_glob (glob_t *glob);
2854 /* tmp points to tmpbuf after the prefix, if any.
2855 tp is the end of the buffer. */
2856 static char *tmpbuf = NULL;
2857 static int tmpbuf_len = 0;
2859 int cachep = (! (flags & PARSEFS_NOCACHE));
2861 struct nameseq *new = 0;
2862 struct nameseq **newp = &new;
2863 #define NEWELT(_n) do { \
2864 const char *__n = (_n); \
2865 *newp = xcalloc (size); \
2866 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2867 newp = &(*newp)->next; \
2868 } while(0)
2870 char *p;
2871 glob_t gl;
2872 char *tp;
2874 #ifdef VMS
2875 # define VMS_COMMA ','
2876 #else
2877 # define VMS_COMMA 0
2878 #endif
2880 if (size < sizeof (struct nameseq))
2881 size = sizeof (struct nameseq);
2883 if (! (flags & PARSEFS_NOGLOB))
2884 dir_setup_glob (&gl);
2886 /* Get enough temporary space to construct the largest possible target. */
2888 int l = strlen (*stringp) + 1;
2889 if (l > tmpbuf_len)
2891 tmpbuf = xrealloc (tmpbuf, l);
2892 tmpbuf_len = l;
2895 tp = tmpbuf;
2897 /* Parse STRING. P will always point to the end of the parsed content. */
2898 p = *stringp;
2899 while (1)
2901 const char *name;
2902 const char **nlist = 0;
2903 char *tildep = 0;
2904 int globme = 1;
2905 #ifndef NO_ARCHIVES
2906 char *arname = 0;
2907 char *memname = 0;
2908 #endif
2909 char *s;
2910 int nlen;
2911 int i;
2913 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2914 p = next_token (p);
2915 if (*p == '\0' || *p == stopchar)
2916 break;
2918 /* There are names left, so find the end of the next name.
2919 Throughout this iteration S points to the start. */
2920 s = p;
2921 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2922 #ifdef VMS
2923 /* convert comma separated list to space separated */
2924 if (p && *p == ',')
2925 *p =' ';
2926 #endif
2927 #ifdef _AMIGA
2928 if (stopchar == ':' && p && *p == ':'
2929 && !(isspace ((unsigned char)p[1]) || !p[1]
2930 || isspace ((unsigned char)p[-1])))
2931 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2932 #endif
2933 #ifdef HAVE_DOS_PATHS
2934 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2935 first colon which isn't followed by a slash or a backslash.
2936 Note that tokens separated by spaces should be treated as separate
2937 tokens since make doesn't allow path names with spaces */
2938 if (stopchar == ':')
2939 while (p != 0 && !isspace ((unsigned char)*p) &&
2940 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2941 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2942 #endif
2943 if (p == 0)
2944 p = s + strlen (s);
2946 /* Strip leading "this directory" references. */
2947 if (! (flags & PARSEFS_NOSTRIP))
2948 #ifdef VMS
2949 /* Skip leading `[]'s. */
2950 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2951 #else
2952 /* Skip leading `./'s. */
2953 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2954 #endif
2956 /* Skip "./" and all following slashes. */
2957 s += 2;
2958 while (*s == '/')
2959 ++s;
2962 /* Extract the filename just found, and skip it.
2963 Set NAME to the string, and NLEN to its length. */
2965 if (s == p)
2967 /* The name was stripped to empty ("./"). */
2968 #if defined(VMS)
2969 continue;
2970 #elif defined(_AMIGA)
2971 /* PDS-- This cannot be right!! */
2972 tp[0] = '\0';
2973 nlen = 0;
2974 #else
2975 tp[0] = '.';
2976 tp[1] = '/';
2977 tp[2] = '\0';
2978 nlen = 2;
2979 #endif
2981 else
2983 #ifdef VMS
2984 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2985 * to remove this '\' before we can use the filename.
2986 * xstrdup called because S may be read-only string constant.
2988 char *n = tp;
2989 while (s < p)
2991 if (s[0] == '\\' && s[1] == ':')
2992 ++s;
2993 *(n++) = *(s++);
2995 n[0] = '\0';
2996 nlen = strlen (tp);
2997 #else
2998 nlen = p - s;
2999 memcpy (tp, s, nlen);
3000 tp[nlen] = '\0';
3001 #endif
3004 /* At this point, TP points to the element and NLEN is its length. */
3006 #ifndef NO_ARCHIVES
3007 /* If this is the start of an archive group that isn't complete, set up
3008 to add the archive prefix for future files. A file list like:
3009 "libf.a(x.o y.o z.o)" needs to be expanded as:
3010 "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3012 TP == TMP means we're not already in an archive group. Ignore
3013 something starting with `(', as that cannot actually be an
3014 archive-member reference (and treating it as such results in an empty
3015 file name, which causes much lossage). Also if it ends in ")" then
3016 it's a complete reference so we don't need to treat it specially.
3018 Finally, note that archive groups must end with ')' as the last
3019 character, so ensure there's some word ending like that before
3020 considering this an archive group. */
3021 if (! (flags & PARSEFS_NOAR)
3022 && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3024 char *n = strchr (tp, '(');
3025 if (n)
3027 /* This looks like the first element in an open archive group.
3028 A valid group MUST have ')' as the last character. */
3029 const char *e = p;
3032 e = next_token (e);
3033 /* Find the end of this word. We don't want to unquote and
3034 we don't care about quoting since we're looking for the
3035 last char in the word. */
3036 while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
3037 && ! isblank ((unsigned char) *e))
3038 ++e;
3039 if (e[-1] == ')')
3041 /* Found the end, so this is the first element in an
3042 open archive group. It looks like "lib(mem".
3043 Reset TP past the open paren. */
3044 nlen -= (n + 1) - tp;
3045 tp = n + 1;
3047 /* We can stop looking now. */
3048 break;
3051 while (*e != '\0');
3053 /* If we have just "lib(", part of something like "lib( a b)",
3054 go to the next item. */
3055 if (! nlen)
3056 continue;
3060 /* If we are inside an archive group, make sure it has an end. */
3061 if (tp > tmpbuf)
3063 if (tp[nlen-1] == ')')
3065 /* This is the natural end; reset TP. */
3066 tp = tmpbuf;
3068 /* This is just ")", something like "lib(a b )": skip it. */
3069 if (nlen == 1)
3070 continue;
3072 else
3074 /* Not the end, so add a "fake" end. */
3075 tp[nlen++] = ')';
3076 tp[nlen] = '\0';
3079 #endif
3081 /* If we're not globbing we're done: add it to the end of the chain.
3082 Go to the next item in the string. */
3083 if (flags & PARSEFS_NOGLOB)
3085 NEWELT (concat (2, prefix, tmpbuf));
3086 continue;
3089 /* If we get here we know we're doing glob expansion.
3090 TP is a string in tmpbuf. NLEN is no longer used.
3091 We may need to do more work: after this NAME will be set. */
3092 name = tmpbuf;
3094 /* Expand tilde if applicable. */
3095 if (tmpbuf[0] == '~')
3097 tildep = tilde_expand (tmpbuf);
3098 if (tildep != 0)
3099 name = tildep;
3102 #ifndef NO_ARCHIVES
3103 /* If NAME is an archive member reference replace it with the archive
3104 file name, and save the member name in MEMNAME. We will glob on the
3105 archive name and then reattach MEMNAME later. */
3106 if (! (flags & PARSEFS_NOAR) && ar_name (name))
3108 ar_parse_name (name, &arname, &memname);
3109 name = arname;
3111 #endif /* !NO_ARCHIVES */
3113 /* glob() is expensive: don't call it unless we need to. */
3114 if (!(flags & PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
3116 globme = 0;
3117 i = 1;
3118 nlist = &name;
3120 else
3121 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3123 case GLOB_NOSPACE:
3124 fatal (NILF, _("virtual memory exhausted"));
3126 case 0:
3127 /* Success. */
3128 i = gl.gl_pathc;
3129 nlist = (const char **)gl.gl_pathv;
3130 break;
3132 case GLOB_NOMATCH:
3133 /* If we want only existing items, skip this one. */
3134 if (flags & PARSEFS_EXISTS)
3136 i = 0;
3137 break;
3139 /* FALLTHROUGH */
3141 default:
3142 /* By default keep this name. */
3143 i = 1;
3144 nlist = &name;
3145 break;
3148 /* For each matched element, add it to the list. */
3149 while (i-- > 0)
3150 #ifndef NO_ARCHIVES
3151 if (memname != 0)
3153 /* Try to glob on MEMNAME within the archive. */
3154 struct nameseq *found = ar_glob (nlist[i], memname, size);
3155 if (! found)
3156 /* No matches. Use MEMNAME as-is. */
3157 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3158 else
3160 /* We got a chain of items. Attach them. */
3161 if (*newp)
3162 (*newp)->next = found;
3163 else
3164 *newp = found;
3166 /* Find and set the new end. Massage names if necessary. */
3167 while (1)
3169 if (! cachep)
3170 found->name = xstrdup (concat (2, prefix, name));
3171 else if (prefix)
3172 found->name = strcache_add (concat (2, prefix, name));
3174 if (found->next == 0)
3175 break;
3177 found = found->next;
3179 newp = &found->next;
3182 else
3183 #endif /* !NO_ARCHIVES */
3184 NEWELT (concat (2, prefix, nlist[i]));
3186 if (globme)
3187 globfree (&gl);
3189 #ifndef NO_ARCHIVES
3190 if (arname)
3191 free (arname);
3192 #endif
3194 if (tildep)
3195 free (tildep);
3198 *stringp = p;
3199 return new;