Fix fat-finger bug that left implicit rules with identical stem lengths
[make.git] / read.c
blobcda9a28f5e9ce55a7abff5509aa5f395896181d9
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, 2009 Free Software
4 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 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 filename = strcache_add (filename);
328 ebuf.floc.filenm = filename;
329 ebuf.floc.lineno = 1;
331 if (ISDB (DB_VERBOSE))
333 printf (_("Reading makefile `%s'"), filename);
334 if (flags & RM_NO_DEFAULT_GOAL)
335 printf (_(" (no default goal)"));
336 if (flags & RM_INCLUDED)
337 printf (_(" (search path)"));
338 if (flags & RM_DONTCARE)
339 printf (_(" (don't care)"));
340 if (flags & RM_NO_TILDE)
341 printf (_(" (no ~ expansion)"));
342 puts ("...");
345 /* First, get a stream to read. */
347 /* Expand ~ in FILENAME unless it came from `include',
348 in which case it was already done. */
349 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
351 expanded = tilde_expand (filename);
352 if (expanded != 0)
353 filename = expanded;
356 ebuf.fp = fopen (filename, "r");
357 /* Save the error code so we print the right message later. */
358 makefile_errno = errno;
360 /* If the makefile wasn't found and it's either a makefile from
361 the `MAKEFILES' variable or an included makefile,
362 search the included makefile search path for this makefile. */
363 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
365 unsigned int i;
366 for (i = 0; include_directories[i] != 0; ++i)
368 const char *included = concat (3, include_directories[i],
369 "/", filename);
370 ebuf.fp = fopen (included, "r");
371 if (ebuf.fp)
373 filename = strcache_add (included);
374 break;
379 /* Add FILENAME to the chain of read makefiles. */
380 deps = alloc_dep ();
381 deps->next = read_makefiles;
382 read_makefiles = deps;
383 deps->file = lookup_file (filename);
384 if (deps->file == 0)
385 deps->file = enter_file (filename);
386 filename = deps->file->name;
387 deps->changed = flags;
388 if (flags & RM_DONTCARE)
389 deps->dontcare = 1;
391 if (expanded)
392 free (expanded);
394 /* If the makefile can't be found at all, give up entirely. */
396 if (ebuf.fp == 0)
398 /* If we did some searching, errno has the error from the last
399 attempt, rather from FILENAME itself. Restore it in case the
400 caller wants to use it in a message. */
401 errno = makefile_errno;
402 return 0;
405 /* Set close-on-exec to avoid leaking the makefile to children, such as
406 $(shell ...). */
407 #ifdef HAVE_FILENO
408 CLOSE_ON_EXEC (fileno (ebuf.fp));
409 #endif
411 /* Add this makefile to the list. */
412 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
413 f_append, 0);
415 /* Evaluate the makefile */
417 ebuf.size = 200;
418 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
420 curfile = reading_file;
421 reading_file = &ebuf.floc;
423 eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
425 reading_file = curfile;
427 fclose (ebuf.fp);
429 free (ebuf.bufstart);
430 alloca (0);
432 return 1;
435 void
436 eval_buffer (char *buffer)
438 struct ebuffer ebuf;
439 struct conditionals *saved;
440 struct conditionals new;
441 const struct floc *curfile;
443 /* Evaluate the buffer */
445 ebuf.size = strlen (buffer);
446 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
447 ebuf.fp = NULL;
449 if (reading_file)
450 ebuf.floc = *reading_file;
451 else
452 ebuf.floc.filenm = NULL;
454 curfile = reading_file;
455 reading_file = &ebuf.floc;
457 saved = install_conditionals (&new);
459 eval (&ebuf, 1);
461 restore_conditionals (saved);
463 reading_file = curfile;
465 alloca (0);
468 /* Check LINE to see if it's a variable assignment or undefine.
470 It might use one of the modifiers "export", "override", "private", or it
471 might be one of the conditional tokens like "ifdef", "include", etc.
473 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
474 Returns LINE.
476 Returns a pointer to the first non-modifier character, and sets VMOD
477 based on the modifiers found if any, plus V_ASSIGN is 1.
479 static char *
480 parse_var_assignment (const char *line, struct vmodifiers *vmod)
482 const char *p;
483 memset (vmod, '\0', sizeof (*vmod));
485 /* Find the start of the next token. If there isn't one we're done. */
486 line = next_token (line);
487 if (*line == '\0')
488 return (char *)line;
490 p = line;
491 while (1)
493 int wlen;
494 const char *p2;
495 enum variable_flavor flavor;
497 p2 = parse_variable_definition (p, &flavor);
499 /* If this is a variable assignment, we're done. */
500 if (p2)
501 break;
503 /* It's not a variable; see if it's a modifier. */
504 p2 = end_of_token (p);
505 wlen = p2 - p;
507 if (word1eq ("export"))
508 vmod->export_v = 1;
509 else if (word1eq ("override"))
510 vmod->override_v = 1;
511 else if (word1eq ("private"))
512 vmod->private_v = 1;
513 else if (word1eq ("define"))
515 /* We can't have modifiers after 'define' */
516 vmod->define_v = 1;
517 p = next_token (p2);
518 break;
520 else if (word1eq ("undefine"))
522 /* We can't have modifiers after 'undefine' */
523 vmod->undefine_v = 1;
524 p = next_token (p2);
525 break;
527 else
528 /* Not a variable or modifier: this is not a variable assignment. */
529 return (char *)line;
531 /* It was a modifier. Try the next word. */
532 p = next_token (p2);
533 if (*p == '\0')
534 return (char *)line;
537 /* Found a variable assignment or undefine. */
538 vmod->assign_v = 1;
539 return (char *)p;
543 /* Read file FILENAME as a makefile and add its contents to the data base.
545 SET_DEFAULT is true if we are allowed to set the default goal. */
547 static void
548 eval (struct ebuffer *ebuf, int set_default)
550 char *collapsed = 0;
551 unsigned int collapsed_length = 0;
552 unsigned int commands_len = 200;
553 char *commands;
554 unsigned int commands_idx = 0;
555 unsigned int cmds_started, tgts_started;
556 int ignoring = 0, in_ignored_define = 0;
557 int no_targets = 0; /* Set when reading a rule without targets. */
558 struct nameseq *filenames = 0;
559 char *depstr = 0;
560 long nlines = 0;
561 int two_colon = 0;
562 const char *pattern = 0;
563 const char *pattern_percent;
564 struct floc *fstart;
565 struct floc fi;
567 #define record_waiting_files() \
568 do \
570 if (filenames != 0) \
572 fi.lineno = tgts_started; \
573 record_files (filenames, pattern, pattern_percent, depstr, \
574 cmds_started, commands, commands_idx, two_colon, \
575 &fi); \
576 filenames = 0; \
578 commands_idx = 0; \
579 no_targets = 0; \
580 pattern = 0; \
581 } while (0)
583 pattern_percent = 0;
584 cmds_started = tgts_started = 1;
586 fstart = &ebuf->floc;
587 fi.filenm = ebuf->floc.filenm;
589 /* Loop over lines in the file.
590 The strategy is to accumulate target names in FILENAMES, dependencies
591 in DEPS and commands in COMMANDS. These are used to define a rule
592 when the start of the next rule (or eof) is encountered.
594 When you see a "continue" in the loop below, that means we are moving on
595 to the next line _without_ ending any rule that we happen to be working
596 with at the moment. If you see a "goto rule_complete", then the
597 statement we just parsed also finishes the previous rule. */
599 commands = xmalloc (200);
601 while (1)
603 unsigned int linelen;
604 char *line;
605 unsigned int wlen;
606 char *p;
607 char *p2;
608 struct vmodifiers vmod;
610 /* At the top of this loop, we are starting a brand new line. */
611 /* Grab the next line to be evaluated */
612 ebuf->floc.lineno += nlines;
613 nlines = readline (ebuf);
615 /* If there is nothing left to eval, we're done. */
616 if (nlines < 0)
617 break;
619 /* If this line is empty, skip it. */
620 line = ebuf->buffer;
621 if (line[0] == '\0')
622 continue;
624 linelen = strlen (line);
626 /* Check for a shell command line first.
627 If it is not one, we can stop treating tab specially. */
628 if (line[0] == cmd_prefix)
630 if (no_targets)
631 /* Ignore the commands in a rule with no targets. */
632 continue;
634 /* If there is no preceding rule line, don't treat this line
635 as a command, even though it begins with a recipe prefix.
636 SunOS 4 make appears to behave this way. */
638 if (filenames != 0)
640 if (ignoring)
641 /* Yep, this is a shell command, and we don't care. */
642 continue;
644 /* Append this command line to the line being accumulated.
645 Strip command prefix chars that appear after newlines. */
646 if (commands_idx == 0)
647 cmds_started = ebuf->floc.lineno;
649 if (linelen + commands_idx > commands_len)
651 commands_len = (linelen + commands_idx) * 2;
652 commands = xrealloc (commands, commands_len);
654 p = &commands[commands_idx];
655 p2 = line + 1;
656 while (--linelen)
658 ++commands_idx;
659 *(p++) = *p2;
660 if (p2[0] == '\n' && p2[1] == cmd_prefix)
662 ++p2;
663 --linelen;
665 ++p2;
667 *p = '\n';
668 ++commands_idx;
670 continue;
674 /* This line is not a shell command line. Don't worry about whitespace.
675 Get more space if we need it; we don't need to preserve the current
676 contents of the buffer. */
678 if (collapsed_length < linelen+1)
680 collapsed_length = linelen+1;
681 if (collapsed)
682 free (collapsed);
683 /* Don't need xrealloc: we don't need to preserve the content. */
684 collapsed = xmalloc (collapsed_length);
686 strcpy (collapsed, line);
687 /* Collapse continuation lines. */
688 collapse_continuations (collapsed);
689 remove_comments (collapsed);
691 /* Get rid if starting space (including formfeed, vtab, etc.) */
692 p = collapsed;
693 while (isspace ((unsigned char)*p))
694 ++p;
696 /* See if this is a variable assignment. We need to do this early, to
697 allow variables with names like 'ifdef', 'export', 'private', etc. */
698 p = parse_var_assignment(p, &vmod);
699 if (vmod.assign_v)
701 struct variable *v;
702 enum variable_origin origin = vmod.override_v ? o_override : o_file;
704 /* If we're ignoring then we're done now. */
705 if (ignoring)
707 if (vmod.define_v)
708 in_ignored_define = 1;
709 continue;
712 if (vmod.undefine_v)
714 do_undefine (p, origin, ebuf);
716 /* This line has been dealt with. */
717 goto rule_complete;
719 else if (vmod.define_v)
720 v = do_define (p, origin, ebuf);
721 else
722 v = try_variable_definition (fstart, p, origin, 0);
724 assert (v != NULL);
726 if (vmod.export_v)
727 v->export = v_export;
728 if (vmod.private_v)
729 v->private_var = 1;
731 /* This line has been dealt with. */
732 goto rule_complete;
735 /* If this line is completely empty, ignore it. */
736 if (*p == '\0')
737 continue;
739 p2 = end_of_token (p);
740 wlen = p2 - p;
741 p2 = next_token (p2);
743 /* If we're in an ignored define, skip this line (but maybe get out). */
744 if (in_ignored_define)
746 /* See if this is an endef line (plus optional comment). */
747 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
748 in_ignored_define = 0;
750 continue;
753 /* Check for conditional state changes. */
755 int i = conditional_line (p, wlen, fstart);
756 if (i != -2)
758 if (i == -1)
759 fatal (fstart, _("invalid syntax in conditional"));
761 ignoring = i;
762 continue;
766 /* Nothing to see here... move along. */
767 if (ignoring)
768 continue;
770 /* Manage the "export" keyword used outside of variable assignment
771 as well as "unexport". */
772 if (word1eq ("export") || word1eq ("unexport"))
774 int exporting = *p == 'u' ? 0 : 1;
776 /* (un)export by itself causes everything to be (un)exported. */
777 if (*p2 == '\0')
778 export_all_variables = exporting;
779 else
781 unsigned int l;
782 const char *cp;
783 char *ap;
785 /* Expand the line so we can use indirect and constructed
786 variable names in an (un)export command. */
787 cp = ap = allocated_variable_expand (p2);
789 for (p = find_next_token (&cp, &l); p != 0;
790 p = find_next_token (&cp, &l))
792 struct variable *v = lookup_variable (p, l);
793 if (v == 0)
794 v = define_variable_loc (p, l, "", o_file, 0, fstart);
795 v->export = exporting ? v_export : v_noexport;
798 free (ap);
800 goto rule_complete;
803 /* Handle the special syntax for vpath. */
804 if (word1eq ("vpath"))
806 const char *cp;
807 char *vpat;
808 unsigned int l;
809 cp = variable_expand (p2);
810 p = find_next_token (&cp, &l);
811 if (p != 0)
813 vpat = xstrndup (p, l);
814 p = find_next_token (&cp, &l);
815 /* No searchpath means remove all previous
816 selective VPATH's with the same pattern. */
818 else
819 /* No pattern means remove all previous selective VPATH's. */
820 vpat = 0;
821 construct_vpath_list (vpat, p);
822 if (vpat != 0)
823 free (vpat);
825 goto rule_complete;
828 /* Handle include and variants. */
829 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
831 /* We have found an `include' line specifying a nested
832 makefile to be read at this point. */
833 struct conditionals *save;
834 struct conditionals new_conditionals;
835 struct nameseq *files;
836 /* "-include" (vs "include") says no error if the file does not
837 exist. "sinclude" is an alias for this from SGI. */
838 int noerror = (p[0] != 'i');
840 p = allocated_variable_expand (p2);
842 /* If no filenames, it's a no-op. */
843 if (*p == '\0')
845 free (p);
846 continue;
849 /* Parse the list of file names. */
850 p2 = p;
851 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
852 free (p);
854 /* Save the state of conditionals and start
855 the included makefile with a clean slate. */
856 save = install_conditionals (&new_conditionals);
858 /* Record the rules that are waiting so they will determine
859 the default goal before those in the included makefile. */
860 record_waiting_files ();
862 /* Read each included makefile. */
863 while (files != 0)
865 struct nameseq *next = files->next;
866 const char *name = files->name;
867 int r;
869 free_ns (files);
870 files = next;
872 r = eval_makefile (name,
873 (RM_INCLUDED | RM_NO_TILDE
874 | (noerror ? RM_DONTCARE : 0)
875 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
876 if (!r && !noerror)
877 error (fstart, "%s: %s", name, strerror (errno));
880 /* Restore conditional state. */
881 restore_conditionals (save);
883 goto rule_complete;
886 /* This line starts with a tab but was not caught above because there
887 was no preceding target, and the line might have been usable as a
888 variable definition. But now we know it is definitely lossage. */
889 if (line[0] == cmd_prefix)
890 fatal(fstart, _("recipe commences before first target"));
892 /* This line describes some target files. This is complicated by
893 the existence of target-specific variables, because we can't
894 expand the entire line until we know if we have one or not. So
895 we expand the line word by word until we find the first `:',
896 then check to see if it's a target-specific variable.
898 In this algorithm, `lb_next' will point to the beginning of the
899 unexpanded parts of the input buffer, while `p2' points to the
900 parts of the expanded buffer we haven't searched yet. */
903 enum make_word_type wtype;
904 char *cmdleft, *semip, *lb_next;
905 unsigned int plen = 0;
906 char *colonp;
907 const char *end, *beg; /* Helpers for whitespace stripping. */
909 /* Record the previous rule. */
911 record_waiting_files ();
912 tgts_started = fstart->lineno;
914 /* Search the line for an unquoted ; that is not after an
915 unquoted #. */
916 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
917 if (cmdleft != 0 && *cmdleft == '#')
919 /* We found a comment before a semicolon. */
920 *cmdleft = '\0';
921 cmdleft = 0;
923 else if (cmdleft != 0)
924 /* Found one. Cut the line short there before expanding it. */
925 *(cmdleft++) = '\0';
926 semip = cmdleft;
928 collapse_continuations (line);
930 /* We can't expand the entire line, since if it's a per-target
931 variable we don't want to expand it. So, walk from the
932 beginning, expanding as we go, and looking for "interesting"
933 chars. The first word is always expandable. */
934 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
935 switch (wtype)
937 case w_eol:
938 if (cmdleft != 0)
939 fatal(fstart, _("missing rule before recipe"));
940 /* This line contained something but turned out to be nothing
941 but whitespace (a comment?). */
942 continue;
944 case w_colon:
945 case w_dcolon:
946 /* We accept and ignore rules without targets for
947 compatibility with SunOS 4 make. */
948 no_targets = 1;
949 continue;
951 default:
952 break;
955 p2 = variable_expand_string(NULL, lb_next, wlen);
957 while (1)
959 lb_next += wlen;
960 if (cmdleft == 0)
962 /* Look for a semicolon in the expanded line. */
963 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
965 if (cmdleft != 0)
967 unsigned long p2_off = p2 - variable_buffer;
968 unsigned long cmd_off = cmdleft - variable_buffer;
969 char *pend = p2 + strlen(p2);
971 /* Append any remnants of lb, then cut the line short
972 at the semicolon. */
973 *cmdleft = '\0';
975 /* One school of thought says that you shouldn't expand
976 here, but merely copy, since now you're beyond a ";"
977 and into a command script. However, the old parser
978 expanded the whole line, so we continue that for
979 backwards-compatiblity. Also, it wouldn't be
980 entirely consistent, since we do an unconditional
981 expand below once we know we don't have a
982 target-specific variable. */
983 (void)variable_expand_string(pend, lb_next, (long)-1);
984 lb_next += strlen(lb_next);
985 p2 = variable_buffer + p2_off;
986 cmdleft = variable_buffer + cmd_off + 1;
990 colonp = find_char_unquote(p2, ':', 0, 0, 0);
991 #ifdef HAVE_DOS_PATHS
992 /* The drive spec brain-damage strikes again... */
993 /* Note that the only separators of targets in this context
994 are whitespace and a left paren. If others are possible,
995 they should be added to the string in the call to index. */
996 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
997 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
998 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
999 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
1000 #endif
1001 if (colonp != 0)
1002 break;
1004 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
1005 if (wtype == w_eol)
1006 break;
1008 p2 += strlen(p2);
1009 *(p2++) = ' ';
1010 p2 = variable_expand_string(p2, lb_next, wlen);
1011 /* We don't need to worry about cmdleft here, because if it was
1012 found in the variable_buffer the entire buffer has already
1013 been expanded... we'll never get here. */
1016 p2 = next_token (variable_buffer);
1018 /* If the word we're looking at is EOL, see if there's _anything_
1019 on the line. If not, a variable expanded to nothing, so ignore
1020 it. If so, we can't parse this line so punt. */
1021 if (wtype == w_eol)
1023 if (*p2 != '\0')
1024 /* There's no need to be ivory-tower about this: check for
1025 one of the most common bugs found in makefiles... */
1026 fatal (fstart, _("missing separator%s"),
1027 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1028 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1029 continue;
1032 /* Make the colon the end-of-string so we know where to stop
1033 looking for targets. */
1034 *colonp = '\0';
1035 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1036 *p2 = ':';
1038 if (!filenames)
1040 /* We accept and ignore rules without targets for
1041 compatibility with SunOS 4 make. */
1042 no_targets = 1;
1043 continue;
1045 /* This should never be possible; we handled it above. */
1046 assert (*p2 != '\0');
1047 ++p2;
1049 /* Is this a one-colon or two-colon entry? */
1050 two_colon = *p2 == ':';
1051 if (two_colon)
1052 p2++;
1054 /* Test to see if it's a target-specific variable. Copy the rest
1055 of the buffer over, possibly temporarily (we'll expand it later
1056 if it's not a target-specific variable). PLEN saves the length
1057 of the unparsed section of p2, for later. */
1058 if (*lb_next != '\0')
1060 unsigned int l = p2 - variable_buffer;
1061 plen = strlen (p2);
1062 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1063 p2 = variable_buffer + l;
1066 p2 = parse_var_assignment (p2, &vmod);
1067 if (vmod.assign_v)
1069 /* If there was a semicolon found, add it back, plus anything
1070 after it. */
1071 if (semip)
1073 unsigned int l = p - variable_buffer;
1074 *(--semip) = ';';
1075 collapse_continuations (semip);
1076 variable_buffer_output (p2 + strlen (p2),
1077 semip, strlen (semip)+1);
1078 p = variable_buffer + l;
1080 record_target_var (filenames, p2,
1081 vmod.override_v ? o_override : o_file,
1082 &vmod, fstart);
1083 filenames = 0;
1084 continue;
1087 /* This is a normal target, _not_ a target-specific variable.
1088 Unquote any = in the dependency list. */
1089 find_char_unquote (lb_next, '=', 0, 0, 0);
1091 /* We have some targets, so don't ignore the following commands. */
1092 no_targets = 0;
1094 /* Expand the dependencies, etc. */
1095 if (*lb_next != '\0')
1097 unsigned int l = p2 - variable_buffer;
1098 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1099 p2 = variable_buffer + l;
1101 /* Look for a semicolon in the expanded line. */
1102 if (cmdleft == 0)
1104 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1105 if (cmdleft != 0)
1106 *(cmdleft++) = '\0';
1110 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1111 p = strchr (p2, ':');
1112 while (p != 0 && p[-1] == '\\')
1114 char *q = &p[-1];
1115 int backslash = 0;
1116 while (*q-- == '\\')
1117 backslash = !backslash;
1118 if (backslash)
1119 p = strchr (p + 1, ':');
1120 else
1121 break;
1123 #ifdef _AMIGA
1124 /* Here, the situation is quite complicated. Let's have a look
1125 at a couple of targets:
1127 install: dev:make
1129 dev:make: make
1131 dev:make:: xyz
1133 The rule is that it's only a target, if there are TWO :'s
1134 OR a space around the :.
1136 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1137 || isspace ((unsigned char)p[-1])))
1138 p = 0;
1139 #endif
1140 #ifdef HAVE_DOS_PATHS
1142 int check_again;
1143 do {
1144 check_again = 0;
1145 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1146 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1147 isalpha ((unsigned char)p[-1]) &&
1148 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1149 p = strchr (p + 1, ':');
1150 check_again = 1;
1152 } while (check_again);
1154 #endif
1155 if (p != 0)
1157 struct nameseq *target;
1158 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1159 PARSEFS_NOGLOB);
1160 ++p2;
1161 if (target == 0)
1162 fatal (fstart, _("missing target pattern"));
1163 else if (target->next != 0)
1164 fatal (fstart, _("multiple target patterns"));
1165 pattern_percent = find_percent_cached (&target->name);
1166 pattern = target->name;
1167 if (pattern_percent == 0)
1168 fatal (fstart, _("target pattern contains no `%%'"));
1169 free_ns (target);
1171 else
1172 pattern = 0;
1174 /* Strip leading and trailing whitespaces. */
1175 beg = p2;
1176 end = beg + strlen (beg) - 1;
1177 strip_whitespace (&beg, &end);
1179 /* Put all the prerequisites here; they'll be parsed later. */
1180 if (beg <= end && *beg != '\0')
1181 depstr = xstrndup (beg, end - beg + 1);
1182 else
1183 depstr = 0;
1185 commands_idx = 0;
1186 if (cmdleft != 0)
1188 /* Semicolon means rest of line is a command. */
1189 unsigned int l = strlen (cmdleft);
1191 cmds_started = fstart->lineno;
1193 /* Add this command line to the buffer. */
1194 if (l + 2 > commands_len)
1196 commands_len = (l + 2) * 2;
1197 commands = xrealloc (commands, commands_len);
1199 memcpy (commands, cmdleft, l);
1200 commands_idx += l;
1201 commands[commands_idx++] = '\n';
1204 /* Determine if this target should be made default. We used to do
1205 this in record_files() but because of the delayed target recording
1206 and because preprocessor directives are legal in target's commands
1207 it is too late. Consider this fragment for example:
1209 foo:
1211 ifeq ($(.DEFAULT_GOAL),foo)
1213 endif
1215 Because the target is not recorded until after ifeq directive is
1216 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1217 would expect. Because of this we have to move the logic here. */
1219 if (set_default && default_goal_var->value[0] == '\0')
1221 const char *name;
1222 struct dep *d;
1223 struct nameseq *t = filenames;
1225 for (; t != 0; t = t->next)
1227 int reject = 0;
1228 name = t->name;
1230 /* We have nothing to do if this is an implicit rule. */
1231 if (strchr (name, '%') != 0)
1232 break;
1234 /* See if this target's name does not start with a `.',
1235 unless it contains a slash. */
1236 if (*name == '.' && strchr (name, '/') == 0
1237 #ifdef HAVE_DOS_PATHS
1238 && strchr (name, '\\') == 0
1239 #endif
1241 continue;
1244 /* If this file is a suffix, don't let it be
1245 the default goal file. */
1246 for (d = suffix_file->deps; d != 0; d = d->next)
1248 register struct dep *d2;
1249 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1251 reject = 1;
1252 break;
1254 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1256 unsigned int l = strlen (dep_name (d2));
1257 if (!strneq (name, dep_name (d2), l))
1258 continue;
1259 if (streq (name + l, dep_name (d)))
1261 reject = 1;
1262 break;
1266 if (reject)
1267 break;
1270 if (!reject)
1272 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1273 o_file, 0, NILF);
1274 break;
1279 continue;
1282 /* We get here except in the case that we just read a rule line.
1283 Record now the last rule we read, so following spurious
1284 commands are properly diagnosed. */
1285 rule_complete:
1286 record_waiting_files ();
1289 #undef word1eq
1291 if (conditionals->if_cmds)
1292 fatal (fstart, _("missing `endif'"));
1294 /* At eof, record the last rule. */
1295 record_waiting_files ();
1297 if (collapsed)
1298 free (collapsed);
1299 free (commands);
1303 /* Remove comments from LINE.
1304 This is done by copying the text at LINE onto itself. */
1306 static void
1307 remove_comments (char *line)
1309 char *comment;
1311 comment = find_char_unquote (line, '#', 0, 0, 0);
1313 if (comment != 0)
1314 /* Cut off the line at the #. */
1315 *comment = '\0';
1318 /* Execute a `undefine' directive.
1319 The undefine line has already been read, and NAME is the name of
1320 the variable to be undefined. */
1322 static void
1323 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1325 char *p, *var;
1327 /* Expand the variable name and find the beginning (NAME) and end. */
1328 var = allocated_variable_expand (name);
1329 name = next_token (var);
1330 if (*name == '\0')
1331 fatal (&ebuf->floc, _("empty variable name"));
1332 p = name + strlen (name) - 1;
1333 while (p > name && isblank ((unsigned char)*p))
1334 --p;
1335 p[1] = '\0';
1337 undefine_variable_global (name, p - name + 1, origin);
1338 free (var);
1341 /* Execute a `define' directive.
1342 The first line has already been read, and NAME is the name of
1343 the variable to be defined. The following lines remain to be read. */
1345 static struct variable *
1346 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1348 struct variable *v;
1349 enum variable_flavor flavor;
1350 struct floc defstart;
1351 int nlevels = 1;
1352 unsigned int length = 100;
1353 char *definition = xmalloc (length);
1354 unsigned int idx = 0;
1355 char *p, *var;
1357 defstart = ebuf->floc;
1359 p = parse_variable_definition (name, &flavor);
1360 if (p == NULL)
1361 /* No assignment token, so assume recursive. */
1362 flavor = f_recursive;
1363 else
1365 if (*(next_token (p)) != '\0')
1366 error (&defstart, _("extraneous text after `define' directive"));
1368 /* Chop the string before the assignment token to get the name. */
1369 p[flavor == f_recursive ? -1 : -2] = '\0';
1372 /* Expand the variable name and find the beginning (NAME) and end. */
1373 var = allocated_variable_expand (name);
1374 name = next_token (var);
1375 if (*name == '\0')
1376 fatal (&defstart, _("empty variable name"));
1377 p = name + strlen (name) - 1;
1378 while (p > name && isblank ((unsigned char)*p))
1379 --p;
1380 p[1] = '\0';
1382 /* Now read the value of the variable. */
1383 while (1)
1385 unsigned int len;
1386 char *line;
1387 long nlines = readline (ebuf);
1389 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1390 if (nlines < 0)
1391 fatal (&defstart, _("missing `endef', unterminated `define'"));
1393 ebuf->floc.lineno += nlines;
1394 line = ebuf->buffer;
1396 collapse_continuations (line);
1398 /* If the line doesn't begin with a tab, test to see if it introduces
1399 another define, or ends one. Stop if we find an 'endef' */
1400 if (line[0] != cmd_prefix)
1402 p = next_token (line);
1403 len = strlen (p);
1405 /* If this is another 'define', increment the level count. */
1406 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1407 && strneq (p, "define", 6))
1408 ++nlevels;
1410 /* If this is an 'endef', decrement the count. If it's now 0,
1411 we've found the last one. */
1412 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1413 && strneq (p, "endef", 5))
1415 p += 5;
1416 remove_comments (p);
1417 if (*(next_token (p)) != '\0')
1418 error (&ebuf->floc,
1419 _("extraneous text after `endef' directive"));
1421 if (--nlevels == 0)
1422 break;
1426 /* Add this line to the variable definition. */
1427 len = strlen (line);
1428 if (idx + len + 1 > length)
1430 length = (idx + len) * 2;
1431 definition = xrealloc (definition, length + 1);
1434 memcpy (&definition[idx], line, len);
1435 idx += len;
1436 /* Separate lines with a newline. */
1437 definition[idx++] = '\n';
1440 /* We've got what we need; define the variable. */
1441 if (idx == 0)
1442 definition[0] = '\0';
1443 else
1444 definition[idx - 1] = '\0';
1446 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1447 free (definition);
1448 free (var);
1449 return (v);
1452 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1453 "ifneq", "else" and "endif".
1454 LINE is the input line, with the command as its first word.
1456 FILENAME and LINENO are the filename and line number in the
1457 current makefile. They are used for error messages.
1459 Value is -2 if the line is not a conditional at all,
1460 -1 if the line is an invalid conditional,
1461 0 if following text should be interpreted,
1462 1 if following text should be ignored. */
1464 static int
1465 conditional_line (char *line, int len, const struct floc *flocp)
1467 char *cmdname;
1468 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1469 unsigned int i;
1470 unsigned int o;
1472 /* Compare a word, both length and contents. */
1473 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1474 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1476 /* Make sure this line is a conditional. */
1477 chkword ("ifdef", c_ifdef)
1478 else chkword ("ifndef", c_ifndef)
1479 else chkword ("ifeq", c_ifeq)
1480 else chkword ("ifneq", c_ifneq)
1481 else chkword ("else", c_else)
1482 else chkword ("endif", c_endif)
1483 else
1484 return -2;
1486 /* Found one: skip past it and any whitespace after it. */
1487 line = next_token (line + len);
1489 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1491 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1492 if (cmdtype == c_endif)
1494 if (*line != '\0')
1495 EXTRANEOUS ();
1497 if (!conditionals->if_cmds)
1498 fatal (flocp, _("extraneous `%s'"), cmdname);
1500 --conditionals->if_cmds;
1502 goto DONE;
1505 /* An 'else' statement can either be simple, or it can have another
1506 conditional after it. */
1507 if (cmdtype == c_else)
1509 const char *p;
1511 if (!conditionals->if_cmds)
1512 fatal (flocp, _("extraneous `%s'"), cmdname);
1514 o = conditionals->if_cmds - 1;
1516 if (conditionals->seen_else[o])
1517 fatal (flocp, _("only one `else' per conditional"));
1519 /* Change the state of ignorance. */
1520 switch (conditionals->ignoring[o])
1522 case 0:
1523 /* We've just been interpreting. Never do it again. */
1524 conditionals->ignoring[o] = 2;
1525 break;
1526 case 1:
1527 /* We've never interpreted yet. Maybe this time! */
1528 conditionals->ignoring[o] = 0;
1529 break;
1532 /* It's a simple 'else'. */
1533 if (*line == '\0')
1535 conditionals->seen_else[o] = 1;
1536 goto DONE;
1539 /* The 'else' has extra text. That text must be another conditional
1540 and cannot be an 'else' or 'endif'. */
1542 /* Find the length of the next word. */
1543 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1545 len = p - line;
1547 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1548 if (word1eq("else") || word1eq("endif")
1549 || conditional_line (line, len, flocp) < 0)
1550 EXTRANEOUS ();
1551 else
1553 /* conditional_line() created a new level of conditional.
1554 Raise it back to this level. */
1555 if (conditionals->ignoring[o] < 2)
1556 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1557 --conditionals->if_cmds;
1560 goto DONE;
1563 if (conditionals->allocated == 0)
1565 conditionals->allocated = 5;
1566 conditionals->ignoring = xmalloc (conditionals->allocated);
1567 conditionals->seen_else = xmalloc (conditionals->allocated);
1570 o = conditionals->if_cmds++;
1571 if (conditionals->if_cmds > conditionals->allocated)
1573 conditionals->allocated += 5;
1574 conditionals->ignoring = xrealloc (conditionals->ignoring,
1575 conditionals->allocated);
1576 conditionals->seen_else = xrealloc (conditionals->seen_else,
1577 conditionals->allocated);
1580 /* Record that we have seen an `if...' but no `else' so far. */
1581 conditionals->seen_else[o] = 0;
1583 /* Search through the stack to see if we're already ignoring. */
1584 for (i = 0; i < o; ++i)
1585 if (conditionals->ignoring[i])
1587 /* We are already ignoring, so just push a level to match the next
1588 "else" or "endif", and keep ignoring. We don't want to expand
1589 variables in the condition. */
1590 conditionals->ignoring[o] = 1;
1591 return 1;
1594 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1596 char *var;
1597 struct variable *v;
1598 char *p;
1600 /* Expand the thing we're looking up, so we can use indirect and
1601 constructed variable names. */
1602 var = allocated_variable_expand (line);
1604 /* Make sure there's only one variable name to test. */
1605 p = end_of_token (var);
1606 i = p - var;
1607 p = next_token (p);
1608 if (*p != '\0')
1609 return -1;
1611 var[i] = '\0';
1612 v = lookup_variable (var, i);
1614 conditionals->ignoring[o] =
1615 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1617 free (var);
1619 else
1621 /* "ifeq" or "ifneq". */
1622 char *s1, *s2;
1623 unsigned int l;
1624 char termin = *line == '(' ? ',' : *line;
1626 if (termin != ',' && termin != '"' && termin != '\'')
1627 return -1;
1629 s1 = ++line;
1630 /* Find the end of the first string. */
1631 if (termin == ',')
1633 int count = 0;
1634 for (; *line != '\0'; ++line)
1635 if (*line == '(')
1636 ++count;
1637 else if (*line == ')')
1638 --count;
1639 else if (*line == ',' && count <= 0)
1640 break;
1642 else
1643 while (*line != '\0' && *line != termin)
1644 ++line;
1646 if (*line == '\0')
1647 return -1;
1649 if (termin == ',')
1651 /* Strip blanks after the first string. */
1652 char *p = line++;
1653 while (isblank ((unsigned char)p[-1]))
1654 --p;
1655 *p = '\0';
1657 else
1658 *line++ = '\0';
1660 s2 = variable_expand (s1);
1661 /* We must allocate a new copy of the expanded string because
1662 variable_expand re-uses the same buffer. */
1663 l = strlen (s2);
1664 s1 = alloca (l + 1);
1665 memcpy (s1, s2, l + 1);
1667 if (termin != ',')
1668 /* Find the start of the second string. */
1669 line = next_token (line);
1671 termin = termin == ',' ? ')' : *line;
1672 if (termin != ')' && termin != '"' && termin != '\'')
1673 return -1;
1675 /* Find the end of the second string. */
1676 if (termin == ')')
1678 int count = 0;
1679 s2 = next_token (line);
1680 for (line = s2; *line != '\0'; ++line)
1682 if (*line == '(')
1683 ++count;
1684 else if (*line == ')')
1686 if (count <= 0)
1687 break;
1688 else
1689 --count;
1693 else
1695 ++line;
1696 s2 = line;
1697 while (*line != '\0' && *line != termin)
1698 ++line;
1701 if (*line == '\0')
1702 return -1;
1704 *line = '\0';
1705 line = next_token (++line);
1706 if (*line != '\0')
1707 EXTRANEOUS ();
1709 s2 = variable_expand (s2);
1710 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1713 DONE:
1714 /* Search through the stack to see if we're ignoring. */
1715 for (i = 0; i < conditionals->if_cmds; ++i)
1716 if (conditionals->ignoring[i])
1717 return 1;
1718 return 0;
1722 /* Record target-specific variable values for files FILENAMES.
1723 TWO_COLON is nonzero if a double colon was used.
1725 The links of FILENAMES are freed, and so are any names in it
1726 that are not incorporated into other data structures.
1728 If the target is a pattern, add the variable to the pattern-specific
1729 variable value list. */
1731 static void
1732 record_target_var (struct nameseq *filenames, char *defn,
1733 enum variable_origin origin, struct vmodifiers *vmod,
1734 const struct floc *flocp)
1736 struct nameseq *nextf;
1737 struct variable_set_list *global;
1739 global = current_variable_set_list;
1741 /* If the variable is an append version, store that but treat it as a
1742 normal recursive variable. */
1744 for (; filenames != 0; filenames = nextf)
1746 struct variable *v;
1747 const char *name = filenames->name;
1748 const char *fname;
1749 const char *percent;
1750 struct pattern_var *p;
1752 nextf = filenames->next;
1753 free_ns (filenames);
1755 /* If it's a pattern target, then add it to the pattern-specific
1756 variable list. */
1757 percent = find_percent_cached (&name);
1758 if (percent)
1760 /* Get a reference for this pattern-specific variable struct. */
1761 p = create_pattern_var (name, percent);
1762 p->variable.fileinfo = *flocp;
1763 /* I don't think this can fail since we already determined it was a
1764 variable definition. */
1765 v = assign_variable_definition (&p->variable, defn);
1766 assert (v != 0);
1768 v->origin = origin;
1769 if (v->flavor == f_simple)
1770 v->value = allocated_variable_expand (v->value);
1771 else
1772 v->value = xstrdup (v->value);
1774 fname = p->target;
1776 else
1778 struct file *f;
1780 /* Get a file reference for this file, and initialize it.
1781 We don't want to just call enter_file() because that allocates a
1782 new entry if the file is a double-colon, which we don't want in
1783 this situation. */
1784 f = lookup_file (name);
1785 if (!f)
1786 f = enter_file (strcache_add (name));
1787 else if (f->double_colon)
1788 f = f->double_colon;
1790 initialize_file_variables (f, 1);
1791 fname = f->name;
1793 current_variable_set_list = f->variables;
1794 v = try_variable_definition (flocp, defn, origin, 1);
1795 if (!v)
1796 fatal (flocp, _("Malformed target-specific variable definition"));
1797 current_variable_set_list = global;
1800 /* Set up the variable to be *-specific. */
1801 v->per_target = 1;
1802 v->private_var = vmod->private_v;
1803 v->export = vmod->export_v ? v_export : v_default;
1805 /* If it's not an override, check to see if there was a command-line
1806 setting. If so, reset the value. */
1807 if (v->origin != o_override)
1809 struct variable *gv;
1810 int len = strlen(v->name);
1812 gv = lookup_variable (v->name, len);
1813 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1815 if (v->value != 0)
1816 free (v->value);
1817 v->value = xstrdup (gv->value);
1818 v->origin = gv->origin;
1819 v->recursive = gv->recursive;
1820 v->append = 0;
1826 /* Record a description line for files FILENAMES,
1827 with dependencies DEPS, commands to execute described
1828 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1829 TWO_COLON is nonzero if a double colon was used.
1830 If not nil, PATTERN is the `%' pattern to make this
1831 a static pattern rule, and PATTERN_PERCENT is a pointer
1832 to the `%' within it.
1834 The links of FILENAMES are freed, and so are any names in it
1835 that are not incorporated into other data structures. */
1837 static void
1838 record_files (struct nameseq *filenames, const char *pattern,
1839 const char *pattern_percent, char *depstr,
1840 unsigned int cmds_started, char *commands,
1841 unsigned int commands_idx, int two_colon,
1842 const struct floc *flocp)
1844 struct commands *cmds;
1845 struct dep *deps;
1846 const char *implicit_percent;
1847 const char *name;
1849 /* If we've already snapped deps, that means we're in an eval being
1850 resolved after the makefiles have been read in. We can't add more rules
1851 at this time, since they won't get snapped and we'll get core dumps.
1852 See Savannah bug # 12124. */
1853 if (snapped_deps)
1854 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1856 /* Determine if this is a pattern rule or not. */
1857 name = filenames->name;
1858 implicit_percent = find_percent_cached (&name);
1860 /* If there's a recipe, set up a struct for it. */
1861 if (commands_idx > 0)
1863 cmds = xmalloc (sizeof (struct commands));
1864 cmds->fileinfo.filenm = flocp->filenm;
1865 cmds->fileinfo.lineno = cmds_started;
1866 cmds->commands = xstrndup (commands, commands_idx);
1867 cmds->command_lines = 0;
1869 else
1870 cmds = 0;
1872 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1873 expansion: if so, snap_deps() will do it. */
1874 if (depstr == 0)
1875 deps = 0;
1876 else if (second_expansion && strchr (depstr, '$'))
1878 deps = alloc_dep ();
1879 deps->name = depstr;
1880 deps->need_2nd_expansion = 1;
1881 deps->staticpattern = pattern != 0;
1883 else
1885 deps = split_prereqs (depstr);
1886 free (depstr);
1888 /* We'll enter static pattern prereqs later when we have the stem. We
1889 don't want to enter pattern rules at all so that we don't think that
1890 they ought to exist (make manual "Implicit Rule Search Algorithm",
1891 item 5c). */
1892 if (! pattern && ! implicit_percent)
1893 deps = enter_prereqs (deps, NULL);
1896 /* For implicit rules, _all_ the targets must have a pattern. That means we
1897 can test the first one to see if we're working with an implicit rule; if
1898 so we handle it specially. */
1900 if (implicit_percent)
1902 struct nameseq *nextf;
1903 const char **targets, **target_pats;
1904 unsigned int c;
1906 if (pattern != 0)
1907 fatal (flocp, _("mixed implicit and static pattern rules"));
1909 /* Count the targets to create an array of target names.
1910 We already have the first one. */
1911 nextf = filenames->next;
1912 free_ns (filenames);
1913 filenames = nextf;
1915 for (c = 1; nextf; ++c, nextf = nextf->next)
1917 targets = xmalloc (c * sizeof (const char *));
1918 target_pats = xmalloc (c * sizeof (const char *));
1920 targets[0] = name;
1921 target_pats[0] = implicit_percent;
1923 c = 1;
1924 while (filenames)
1926 name = filenames->name;
1927 implicit_percent = find_percent_cached (&name);
1929 if (implicit_percent == 0)
1930 fatal (flocp, _("mixed implicit and normal rules"));
1932 targets[c] = name;
1933 target_pats[c] = implicit_percent;
1934 ++c;
1936 nextf = filenames->next;
1937 free_ns (filenames);
1938 filenames = nextf;
1941 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1943 return;
1947 /* Walk through each target and create it in the database.
1948 We already set up the first target, above. */
1949 while (1)
1951 struct nameseq *nextf = filenames->next;
1952 struct file *f;
1953 struct dep *this = 0;
1955 free_ns (filenames);
1957 /* Check for special targets. Do it here instead of, say, snap_deps()
1958 so that we can immediately use the value. */
1959 if (streq (name, ".POSIX"))
1960 posix_pedantic = 1;
1961 else if (streq (name, ".SECONDEXPANSION"))
1962 second_expansion = 1;
1964 /* If this is a static pattern rule:
1965 `targets: target%pattern: prereq%pattern; recipe',
1966 make sure the pattern matches this target name. */
1967 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1968 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1969 else if (deps)
1970 /* If there are multiple targets, copy the chain DEPS for all but the
1971 last one. It is not safe for the same deps to go in more than one
1972 place in the database. */
1973 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1975 /* Find or create an entry in the file database for this target. */
1976 if (!two_colon)
1978 /* Single-colon. Combine this rule with the file's existing record,
1979 if any. */
1980 f = enter_file (strcache_add (name));
1981 if (f->double_colon)
1982 fatal (flocp,
1983 _("target file `%s' has both : and :: entries"), f->name);
1985 /* If CMDS == F->CMDS, this target was listed in this rule
1986 more than once. Just give a warning since this is harmless. */
1987 if (cmds != 0 && cmds == f->cmds)
1988 error (flocp,
1989 _("target `%s' given more than once in the same rule."),
1990 f->name);
1992 /* Check for two single-colon entries both with commands.
1993 Check is_target so that we don't lose on files such as .c.o
1994 whose commands were preinitialized. */
1995 else if (cmds != 0 && f->cmds != 0 && f->is_target)
1997 error (&cmds->fileinfo,
1998 _("warning: overriding recipe for target `%s'"),
1999 f->name);
2000 error (&f->cmds->fileinfo,
2001 _("warning: ignoring old recipe for target `%s'"),
2002 f->name);
2005 /* Defining .DEFAULT with no deps or cmds clears it. */
2006 if (f == default_file && this == 0 && cmds == 0)
2007 f->cmds = 0;
2008 if (cmds != 0)
2009 f->cmds = cmds;
2011 /* Defining .SUFFIXES with no dependencies clears out the list of
2012 suffixes. */
2013 if (f == suffix_file && this == 0)
2015 free_dep_chain (f->deps);
2016 f->deps = 0;
2019 else
2021 /* Double-colon. Make a new record even if there already is one. */
2022 f = lookup_file (name);
2024 /* Check for both : and :: rules. Check is_target so we don't lose
2025 on default suffix rules or makefiles. */
2026 if (f != 0 && f->is_target && !f->double_colon)
2027 fatal (flocp,
2028 _("target file `%s' has both : and :: entries"), f->name);
2030 f = enter_file (strcache_add (name));
2031 /* If there was an existing entry and it was a double-colon entry,
2032 enter_file will have returned a new one, making it the prev
2033 pointer of the old one, and setting its double_colon pointer to
2034 the first one. */
2035 if (f->double_colon == 0)
2036 /* This is the first entry for this name, so we must set its
2037 double_colon pointer to itself. */
2038 f->double_colon = f;
2040 f->cmds = cmds;
2043 f->is_target = 1;
2045 /* If this is a static pattern rule, set the stem to the part of its
2046 name that matched the `%' in the pattern, so you can use $* in the
2047 commands. If we didn't do it before, enter the prereqs now. */
2048 if (pattern)
2050 static const char *percent = "%";
2051 char *buffer = variable_expand ("");
2052 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2053 pattern_percent+1, percent+1);
2054 f->stem = strcache_add_len (buffer, o - buffer);
2055 if (this)
2057 if (! this->need_2nd_expansion)
2058 this = enter_prereqs (this, f->stem);
2059 else
2060 this->stem = f->stem;
2064 /* Add the dependencies to this file entry. */
2065 if (this != 0)
2067 /* Add the file's old deps and the new ones in THIS together. */
2068 if (f->deps == 0)
2069 f->deps = this;
2070 else if (cmds != 0)
2072 struct dep *d = this;
2074 /* If this rule has commands, put these deps first. */
2075 while (d->next != 0)
2076 d = d->next;
2078 d->next = f->deps;
2079 f->deps = this;
2081 else
2083 struct dep *d = f->deps;
2085 /* A rule without commands: put its prereqs at the end. */
2086 while (d->next != 0)
2087 d = d->next;
2089 d->next = this;
2093 name = f->name;
2095 /* All done! Set up for the next one. */
2096 if (nextf == 0)
2097 break;
2099 filenames = nextf;
2101 /* Reduce escaped percents. If there are any unescaped it's an error */
2102 name = filenames->name;
2103 if (find_percent_cached (&name))
2104 fatal (flocp, _("mixed implicit and normal rules"));
2108 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2109 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2110 Quoting backslashes are removed from STRING by compacting it into
2111 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2112 one, or nil if there are none. STOPCHARs inside variable references are
2113 ignored if IGNOREVARS is true.
2115 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2117 static char *
2118 find_char_unquote (char *string, int stop1, int stop2, int blank,
2119 int ignorevars)
2121 unsigned int string_len = 0;
2122 char *p = string;
2124 if (ignorevars)
2125 ignorevars = '$';
2127 while (1)
2129 if (stop2 && blank)
2130 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2131 && ! isblank ((unsigned char) *p))
2132 ++p;
2133 else if (stop2)
2134 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2135 ++p;
2136 else if (blank)
2137 while (*p != '\0' && *p != ignorevars && *p != stop1
2138 && ! isblank ((unsigned char) *p))
2139 ++p;
2140 else
2141 while (*p != '\0' && *p != ignorevars && *p != stop1)
2142 ++p;
2144 if (*p == '\0')
2145 break;
2147 /* If we stopped due to a variable reference, skip over its contents. */
2148 if (*p == ignorevars)
2150 char openparen = p[1];
2152 p += 2;
2154 /* Skip the contents of a non-quoted, multi-char variable ref. */
2155 if (openparen == '(' || openparen == '{')
2157 unsigned int pcount = 1;
2158 char closeparen = (openparen == '(' ? ')' : '}');
2160 while (*p)
2162 if (*p == openparen)
2163 ++pcount;
2164 else if (*p == closeparen)
2165 if (--pcount == 0)
2167 ++p;
2168 break;
2170 ++p;
2174 /* Skipped the variable reference: look for STOPCHARS again. */
2175 continue;
2178 if (p > string && p[-1] == '\\')
2180 /* Search for more backslashes. */
2181 int i = -2;
2182 while (&p[i] >= string && p[i] == '\\')
2183 --i;
2184 ++i;
2185 /* Only compute the length if really needed. */
2186 if (string_len == 0)
2187 string_len = strlen (string);
2188 /* The number of backslashes is now -I.
2189 Copy P over itself to swallow half of them. */
2190 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2191 p += i/2;
2192 if (i % 2 == 0)
2193 /* All the backslashes quoted each other; the STOPCHAR was
2194 unquoted. */
2195 return p;
2197 /* The STOPCHAR was quoted by a backslash. Look for another. */
2199 else
2200 /* No backslash in sight. */
2201 return p;
2204 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2205 return 0;
2208 /* Search PATTERN for an unquoted % and handle quoting. */
2210 char *
2211 find_percent (char *pattern)
2213 return find_char_unquote (pattern, '%', 0, 0, 0);
2216 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2217 the % or NULL if no % was found.
2218 This version is used with strings in the string cache: if there's a need to
2219 modify the string a new version will be added to the string cache and
2220 *STRING will be set to that. */
2222 const char *
2223 find_percent_cached (const char **string)
2225 const char *p = *string;
2226 char *new = 0;
2227 int slen = 0;
2229 /* If the first char is a % return now. This lets us avoid extra tests
2230 inside the loop. */
2231 if (*p == '%')
2232 return p;
2234 while (1)
2236 while (*p != '\0' && *p != '%')
2237 ++p;
2239 if (*p == '\0')
2240 break;
2242 /* See if this % is escaped with a backslash; if not we're done. */
2243 if (p[-1] != '\\')
2244 break;
2247 /* Search for more backslashes. */
2248 char *pv;
2249 int i = -2;
2251 while (&p[i] >= *string && p[i] == '\\')
2252 --i;
2253 ++i;
2255 /* At this point we know we'll need to allocate a new string.
2256 Make a copy if we haven't yet done so. */
2257 if (! new)
2259 slen = strlen (*string);
2260 new = alloca (slen + 1);
2261 memcpy (new, *string, slen + 1);
2262 p = new + (p - *string);
2263 *string = new;
2266 /* At this point *string, p, and new all point into the same string.
2267 Get a non-const version of p so we can modify new. */
2268 pv = new + (p - *string);
2270 /* The number of backslashes is now -I.
2271 Copy P over itself to swallow half of them. */
2272 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2273 p += i/2;
2275 /* If the backslashes quoted each other; the % was unquoted. */
2276 if (i % 2 == 0)
2277 break;
2281 /* If we had to change STRING, add it to the strcache. */
2282 if (new)
2284 *string = strcache_add (*string);
2285 p = *string + (p - new);
2288 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2289 return (*p == '\0') ? NULL : p;
2292 /* Find the next line of text in an eval buffer, combining continuation lines
2293 into one line.
2294 Return the number of actual lines read (> 1 if continuation lines).
2295 Returns -1 if there's nothing left in the buffer.
2297 After this function, ebuf->buffer points to the first character of the
2298 line we just found.
2301 /* Read a line of text from a STRING.
2302 Since we aren't really reading from a file, don't bother with linenumbers.
2305 static unsigned long
2306 readstring (struct ebuffer *ebuf)
2308 char *eol;
2310 /* If there is nothing left in this buffer, return 0. */
2311 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2312 return -1;
2314 /* Set up a new starting point for the buffer, and find the end of the
2315 next logical line (taking into account backslash/newline pairs). */
2317 eol = ebuf->buffer = ebuf->bufnext;
2319 while (1)
2321 int backslash = 0;
2322 const char *bol = eol;
2323 const char *p;
2325 /* Find the next newline. At EOS, stop. */
2326 p = eol = strchr (eol , '\n');
2327 if (!eol)
2329 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2330 return 0;
2333 /* Found a newline; if it's escaped continue; else we're done. */
2334 while (p > bol && *(--p) == '\\')
2335 backslash = !backslash;
2336 if (!backslash)
2337 break;
2338 ++eol;
2341 /* Overwrite the newline char. */
2342 *eol = '\0';
2343 ebuf->bufnext = eol+1;
2345 return 0;
2348 static long
2349 readline (struct ebuffer *ebuf)
2351 char *p;
2352 char *end;
2353 char *start;
2354 long nlines = 0;
2356 /* The behaviors between string and stream buffers are different enough to
2357 warrant different functions. Do the Right Thing. */
2359 if (!ebuf->fp)
2360 return readstring (ebuf);
2362 /* When reading from a file, we always start over at the beginning of the
2363 buffer for each new line. */
2365 p = start = ebuf->bufstart;
2366 end = p + ebuf->size;
2367 *p = '\0';
2369 while (fgets (p, end - p, ebuf->fp) != 0)
2371 char *p2;
2372 unsigned long len;
2373 int backslash;
2375 len = strlen (p);
2376 if (len == 0)
2378 /* This only happens when the first thing on the line is a '\0'.
2379 It is a pretty hopeless case, but (wonder of wonders) Athena
2380 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2381 There is nothing really to be done; we synthesize a newline so
2382 the following line doesn't appear to be part of this line. */
2383 error (&ebuf->floc,
2384 _("warning: NUL character seen; rest of line ignored"));
2385 p[0] = '\n';
2386 len = 1;
2389 /* Jump past the text we just read. */
2390 p += len;
2392 /* If the last char isn't a newline, the whole line didn't fit into the
2393 buffer. Get some more buffer and try again. */
2394 if (p[-1] != '\n')
2395 goto more_buffer;
2397 /* We got a newline, so add one to the count of lines. */
2398 ++nlines;
2400 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2401 /* Check to see if the line was really ended with CRLF; if so ignore
2402 the CR. */
2403 if ((p - start) > 1 && p[-2] == '\r')
2405 --p;
2406 p[-1] = '\n';
2408 #endif
2410 backslash = 0;
2411 for (p2 = p - 2; p2 >= start; --p2)
2413 if (*p2 != '\\')
2414 break;
2415 backslash = !backslash;
2418 if (!backslash)
2420 p[-1] = '\0';
2421 break;
2424 /* It was a backslash/newline combo. If we have more space, read
2425 another line. */
2426 if (end - p >= 80)
2427 continue;
2429 /* We need more space at the end of our buffer, so realloc it.
2430 Make sure to preserve the current offset of p. */
2431 more_buffer:
2433 unsigned long off = p - start;
2434 ebuf->size *= 2;
2435 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2436 p = start + off;
2437 end = start + ebuf->size;
2438 *p = '\0';
2442 if (ferror (ebuf->fp))
2443 pfatal_with_name (ebuf->floc.filenm);
2445 /* If we found some lines, return how many.
2446 If we didn't, but we did find _something_, that indicates we read the last
2447 line of a file with no final newline; return 1.
2448 If we read nothing, we're at EOF; return -1. */
2450 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2453 /* Parse the next "makefile word" from the input buffer, and return info
2454 about it.
2456 A "makefile word" is one of:
2458 w_bogus Should never happen
2459 w_eol End of input
2460 w_static A static word; cannot be expanded
2461 w_variable A word containing one or more variables/functions
2462 w_colon A colon
2463 w_dcolon A double-colon
2464 w_semicolon A semicolon
2465 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2467 Note that this function is only used when reading certain parts of the
2468 makefile. Don't use it where special rules hold sway (RHS of a variable,
2469 in a command list, etc.) */
2471 static enum make_word_type
2472 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2474 enum make_word_type wtype = w_bogus;
2475 char *p = buffer, *beg;
2476 char c;
2478 /* Skip any leading whitespace. */
2479 while (isblank ((unsigned char)*p))
2480 ++p;
2482 beg = p;
2483 c = *(p++);
2484 switch (c)
2486 case '\0':
2487 wtype = w_eol;
2488 break;
2490 case ';':
2491 wtype = w_semicolon;
2492 break;
2494 case '=':
2495 wtype = w_varassign;
2496 break;
2498 case ':':
2499 wtype = w_colon;
2500 switch (*p)
2502 case ':':
2503 ++p;
2504 wtype = w_dcolon;
2505 break;
2507 case '=':
2508 ++p;
2509 wtype = w_varassign;
2510 break;
2512 break;
2514 case '+':
2515 case '?':
2516 if (*p == '=')
2518 ++p;
2519 wtype = w_varassign;
2520 break;
2523 default:
2524 if (delim && strchr (delim, c))
2525 wtype = w_static;
2526 break;
2529 /* Did we find something? If so, return now. */
2530 if (wtype != w_bogus)
2531 goto done;
2533 /* This is some non-operator word. A word consists of the longest
2534 string of characters that doesn't contain whitespace, one of [:=#],
2535 or [?+]=, or one of the chars in the DELIM string. */
2537 /* We start out assuming a static word; if we see a variable we'll
2538 adjust our assumptions then. */
2539 wtype = w_static;
2541 /* We already found the first value of "c", above. */
2542 while (1)
2544 char closeparen;
2545 int count;
2547 switch (c)
2549 case '\0':
2550 case ' ':
2551 case '\t':
2552 case '=':
2553 goto done_word;
2555 case ':':
2556 #ifdef HAVE_DOS_PATHS
2557 /* A word CAN include a colon in its drive spec. The drive
2558 spec is allowed either at the beginning of a word, or as part
2559 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2560 if (!(p - beg >= 2
2561 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2562 && (p - beg == 2 || p[-3] == '(')))
2563 #endif
2564 goto done_word;
2566 case '$':
2567 c = *(p++);
2568 if (c == '$')
2569 break;
2571 /* This is a variable reference, so note that it's expandable.
2572 Then read it to the matching close paren. */
2573 wtype = w_variable;
2575 if (c == '(')
2576 closeparen = ')';
2577 else if (c == '{')
2578 closeparen = '}';
2579 else
2580 /* This is a single-letter variable reference. */
2581 break;
2583 for (count=0; *p != '\0'; ++p)
2585 if (*p == c)
2586 ++count;
2587 else if (*p == closeparen && --count < 0)
2589 ++p;
2590 break;
2593 break;
2595 case '?':
2596 case '+':
2597 if (*p == '=')
2598 goto done_word;
2599 break;
2601 case '\\':
2602 switch (*p)
2604 case ':':
2605 case ';':
2606 case '=':
2607 case '\\':
2608 ++p;
2609 break;
2611 break;
2613 default:
2614 if (delim && strchr (delim, c))
2615 goto done_word;
2616 break;
2619 c = *(p++);
2621 done_word:
2622 --p;
2624 done:
2625 if (startp)
2626 *startp = beg;
2627 if (length)
2628 *length = p - beg;
2629 return wtype;
2632 /* Construct the list of include directories
2633 from the arguments and the default list. */
2635 void
2636 construct_include_path (const char **arg_dirs)
2638 #ifdef VAXC /* just don't ask ... */
2639 stat_t stbuf;
2640 #else
2641 struct stat stbuf;
2642 #endif
2643 const char **dirs;
2644 const char **cpp;
2645 unsigned int idx;
2647 /* Compute the number of pointers we need in the table. */
2648 idx = sizeof (default_include_directories) / sizeof (const char *);
2649 if (arg_dirs)
2650 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2651 ++idx;
2653 #ifdef __MSDOS__
2654 /* Add one for $DJDIR. */
2655 ++idx;
2656 #endif
2658 dirs = xmalloc (idx * sizeof (const char *));
2660 idx = 0;
2661 max_incl_len = 0;
2663 /* First consider any dirs specified with -I switches.
2664 Ignore any that don't exist. Remember the maximum string length. */
2666 if (arg_dirs)
2667 while (*arg_dirs != 0)
2669 const char *dir = *(arg_dirs++);
2670 char *expanded = 0;
2671 int e;
2673 if (dir[0] == '~')
2675 expanded = tilde_expand (dir);
2676 if (expanded != 0)
2677 dir = expanded;
2680 EINTRLOOP (e, stat (dir, &stbuf));
2681 if (e == 0 && S_ISDIR (stbuf.st_mode))
2683 unsigned int len = strlen (dir);
2684 /* If dir name is written with trailing slashes, discard them. */
2685 while (len > 1 && dir[len - 1] == '/')
2686 --len;
2687 if (len > max_incl_len)
2688 max_incl_len = len;
2689 dirs[idx++] = strcache_add_len (dir, len);
2692 if (expanded)
2693 free (expanded);
2696 /* Now add the standard default dirs at the end. */
2698 #ifdef __MSDOS__
2700 /* The environment variable $DJDIR holds the root of the DJGPP directory
2701 tree; add ${DJDIR}/include. */
2702 struct variable *djdir = lookup_variable ("DJDIR", 5);
2704 if (djdir)
2706 unsigned int len = strlen (djdir->value) + 8;
2707 char *defdir = alloca (len + 1);
2709 strcat (strcpy (defdir, djdir->value), "/include");
2710 dirs[idx++] = strcache_add (defdir);
2712 if (len > max_incl_len)
2713 max_incl_len = len;
2716 #endif
2718 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2720 int e;
2722 EINTRLOOP (e, stat (*cpp, &stbuf));
2723 if (e == 0 && S_ISDIR (stbuf.st_mode))
2725 unsigned int len = strlen (*cpp);
2726 /* If dir name is written with trailing slashes, discard them. */
2727 while (len > 1 && (*cpp)[len - 1] == '/')
2728 --len;
2729 if (len > max_incl_len)
2730 max_incl_len = len;
2731 dirs[idx++] = strcache_add_len (*cpp, len);
2735 dirs[idx] = 0;
2737 /* Now add each dir to the .INCLUDE_DIRS variable. */
2739 for (cpp = dirs; *cpp != 0; ++cpp)
2740 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2741 o_default, f_append, 0);
2743 include_directories = dirs;
2746 /* Expand ~ or ~USER at the beginning of NAME.
2747 Return a newly malloc'd string or 0. */
2749 char *
2750 tilde_expand (const char *name)
2752 #ifndef VMS
2753 if (name[1] == '/' || name[1] == '\0')
2755 extern char *getenv ();
2756 char *home_dir;
2757 int is_variable;
2760 /* Turn off --warn-undefined-variables while we expand HOME. */
2761 int save = warn_undefined_variables_flag;
2762 warn_undefined_variables_flag = 0;
2764 home_dir = allocated_variable_expand ("$(HOME)");
2766 warn_undefined_variables_flag = save;
2769 is_variable = home_dir[0] != '\0';
2770 if (!is_variable)
2772 free (home_dir);
2773 home_dir = getenv ("HOME");
2775 # if !defined(_AMIGA) && !defined(WINDOWS32)
2776 if (home_dir == 0 || home_dir[0] == '\0')
2778 extern char *getlogin ();
2779 char *logname = getlogin ();
2780 home_dir = 0;
2781 if (logname != 0)
2783 struct passwd *p = getpwnam (logname);
2784 if (p != 0)
2785 home_dir = p->pw_dir;
2788 # endif /* !AMIGA && !WINDOWS32 */
2789 if (home_dir != 0)
2791 char *new = xstrdup (concat (2, home_dir, name + 1));
2792 if (is_variable)
2793 free (home_dir);
2794 return new;
2797 # if !defined(_AMIGA) && !defined(WINDOWS32)
2798 else
2800 struct passwd *pwent;
2801 char *userend = strchr (name + 1, '/');
2802 if (userend != 0)
2803 *userend = '\0';
2804 pwent = getpwnam (name + 1);
2805 if (pwent != 0)
2807 if (userend == 0)
2808 return xstrdup (pwent->pw_dir);
2809 else
2810 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2812 else if (userend != 0)
2813 *userend = '/';
2815 # endif /* !AMIGA && !WINDOWS32 */
2816 #endif /* !VMS */
2817 return 0;
2820 /* Parse a string into a sequence of filenames represented as a chain of
2821 struct nameseq's and return that chain. Optionally expand the strings via
2822 glob().
2824 The string is passed as STRINGP, the address of a string pointer.
2825 The string pointer is updated to point at the first character
2826 not parsed, which either is a null char or equals STOPCHAR.
2828 SIZE is how big to construct chain elements.
2829 This is useful if we want them actually to be other structures
2830 that have room for additional info.
2832 PREFIX, if non-null, is added to the beginning of each filename.
2834 FLAGS allows one or more of the following bitflags to be set:
2835 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2836 PARSEFS_NOGLOB - Do not expand globbing characters
2837 PARSEFS_EXISTS - Only return globbed files that actually exist
2838 (cannot also set NOGLOB)
2839 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2842 void *
2843 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2844 const char *prefix, int flags)
2846 extern void dir_setup_glob (glob_t *glob);
2848 /* tmp points to tmpbuf after the prefix, if any.
2849 tp is the end of the buffer. */
2850 static char *tmpbuf = NULL;
2851 static int tmpbuf_len = 0;
2853 int cachep = (! (flags & PARSEFS_NOCACHE));
2855 struct nameseq *new = 0;
2856 struct nameseq **newp = &new;
2857 #define NEWELT(_n) do { \
2858 const char *__n = (_n); \
2859 *newp = xcalloc (size); \
2860 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2861 newp = &(*newp)->next; \
2862 } while(0)
2864 char *p;
2865 glob_t gl;
2866 char *tp;
2868 #ifdef VMS
2869 # define VMS_COMMA ','
2870 #else
2871 # define VMS_COMMA 0
2872 #endif
2874 if (size < sizeof (struct nameseq))
2875 size = sizeof (struct nameseq);
2877 if (! (flags & PARSEFS_NOGLOB))
2878 dir_setup_glob (&gl);
2880 /* Get enough temporary space to construct the largest possible target. */
2882 int l = strlen (*stringp) + 1;
2883 if (l > tmpbuf_len)
2885 tmpbuf = xrealloc (tmpbuf, l);
2886 tmpbuf_len = l;
2889 tp = tmpbuf;
2891 /* Parse STRING. P will always point to the end of the parsed content. */
2892 p = *stringp;
2893 while (1)
2895 const char *name;
2896 const char **nlist = 0;
2897 char *tildep = 0;
2898 #ifndef NO_ARCHIVES
2899 char *arname = 0;
2900 char *memname = 0;
2901 #endif
2902 char *s;
2903 int nlen;
2904 int i;
2906 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2907 p = next_token (p);
2908 if (*p == '\0' || *p == stopchar)
2909 break;
2911 /* There are names left, so find the end of the next name.
2912 Throughout this iteration S points to the start. */
2913 s = p;
2914 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2915 #ifdef VMS
2916 /* convert comma separated list to space separated */
2917 if (p && *p == ',')
2918 *p =' ';
2919 #endif
2920 #ifdef _AMIGA
2921 if (stopchar == ':' && p && *p == ':'
2922 && !(isspace ((unsigned char)p[1]) || !p[1]
2923 || isspace ((unsigned char)p[-1])))
2924 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2925 #endif
2926 #ifdef HAVE_DOS_PATHS
2927 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2928 first colon which isn't followed by a slash or a backslash.
2929 Note that tokens separated by spaces should be treated as separate
2930 tokens since make doesn't allow path names with spaces */
2931 if (stopchar == ':')
2932 while (p != 0 && !isspace ((unsigned char)*p) &&
2933 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2934 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2935 #endif
2936 if (p == 0)
2937 p = s + strlen (s);
2939 /* Strip leading "this directory" references. */
2940 if (! (flags & PARSEFS_NOSTRIP))
2941 #ifdef VMS
2942 /* Skip leading `[]'s. */
2943 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2944 #else
2945 /* Skip leading `./'s. */
2946 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2947 #endif
2949 /* Skip "./" and all following slashes. */
2950 s += 2;
2951 while (*s == '/')
2952 ++s;
2955 /* Extract the filename just found, and skip it.
2956 Set NAME to the string, and NLEN to its length. */
2958 if (s == p)
2960 /* The name was stripped to empty ("./"). */
2961 #if defined(VMS)
2962 continue;
2963 #elif defined(_AMIGA)
2964 /* PDS-- This cannot be right!! */
2965 tp[0] = '\0';
2966 nlen = 0;
2967 #else
2968 tp[0] = '.';
2969 tp[1] = '/';
2970 tp[2] = '\0';
2971 nlen = 2;
2972 #endif
2974 else
2976 #ifdef VMS
2977 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2978 * to remove this '\' before we can use the filename.
2979 * xstrdup called because S may be read-only string constant.
2981 char *n = tp;
2982 while (s < p)
2984 if (s[0] == '\\' && s[1] == ':')
2985 ++s;
2986 *(n++) = *(s++);
2988 n[0] = '\0';
2989 nlen = strlen (tp);
2990 #else
2991 nlen = p - s;
2992 memcpy (tp, s, nlen);
2993 tp[nlen] = '\0';
2994 #endif
2997 /* At this point, TP points to the element and NLEN is its length. */
2999 #ifndef NO_ARCHIVES
3000 /* If this is the start of an archive group that isn't complete, set up
3001 to add the archive prefix for future files.
3003 TP == TMP means we're not already in an archive group. Ignore
3004 something starting with `(', as that cannot actually be an
3005 archive-member reference (and treating it as such results in an empty
3006 file name, which causes much lossage). Also if it ends in ")" then
3007 it's a complete reference so we don't need to treat it specially. */
3009 if (tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3011 char *n = strchr (tp, '(');
3012 if (n)
3014 /* This is the first element in an open archive group. It looks
3015 like "lib(mem". Remember the close paren. */
3016 nlen -= (n + 1) - tp;
3017 tp = n + 1;
3019 /* If we have just "lib(", part of something like "lib( a b)",
3020 go to the next item. */
3021 if (! nlen)
3022 continue;
3026 /* If we are inside an archive group, make sure it has an end. */
3027 if (tp > tmpbuf)
3029 if (tp[nlen-1] == ')')
3031 /* This is the natural end; reset TP. */
3032 tp = tmpbuf;
3034 /* This is just ")", something like "lib(a b )": skip it. */
3035 if (nlen == 1)
3036 continue;
3038 else
3040 /* Not the end, so add a "fake" end. */
3041 tp[nlen++] = ')';
3042 tp[nlen] = '\0';
3045 #endif
3047 /* If we're not globbing we're done: add it to the end of the chain.
3048 Go to the next item in the string. */
3049 if (flags & PARSEFS_NOGLOB)
3051 NEWELT (concat (2, prefix, tp));
3052 continue;
3055 /* If we get here we know we're doing glob expansion.
3056 TP is a string in tmpbuf. NLEN is no longer used.
3057 We may need to do more work: after this NAME will be set. */
3058 name = tp;
3060 /* Expand tilde if applicable. */
3061 if (tp[0] == '~')
3063 tildep = tilde_expand (tp);
3064 if (tildep != 0)
3065 name = tildep;
3068 #ifndef NO_ARCHIVES
3069 /* If NAME is an archive member reference replace it with the archive
3070 file name, and save the member name in MEMNAME. We will glob on the
3071 archive name and then reattach MEMNAME later. */
3072 if (ar_name (name))
3074 ar_parse_name (name, &arname, &memname);
3075 name = arname;
3077 #endif /* !NO_ARCHIVES */
3079 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3081 case GLOB_NOSPACE:
3082 fatal (NILF, _("virtual memory exhausted"));
3084 case 0:
3085 /* Success. */
3086 i = gl.gl_pathc;
3087 nlist = (const char **)gl.gl_pathv;
3088 break;
3090 case GLOB_NOMATCH:
3091 /* If we want only existing items, skip this one. */
3092 if (flags & PARSEFS_EXISTS)
3094 i = 0;
3095 break;
3097 /* FALLTHROUGH */
3099 default:
3100 /* By default keep this name. */
3101 i = 1;
3102 nlist = &name;
3103 break;
3106 /* For each matched element, add it to the list. */
3107 while (i-- > 0)
3108 #ifndef NO_ARCHIVES
3109 if (memname != 0)
3111 /* Try to glob on MEMNAME within the archive. */
3112 struct nameseq *found = ar_glob (nlist[i], memname, size);
3113 if (! found)
3114 /* No matches. Use MEMNAME as-is. */
3115 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3116 else
3118 /* We got a chain of items. Attach them. */
3119 (*newp)->next = found;
3121 /* Find and set the new end. Massage names if necessary. */
3122 while (1)
3124 if (! cachep)
3125 found->name = xstrdup (concat (2, prefix, name));
3126 else if (prefix)
3127 found->name = strcache_add (concat (2, prefix, name));
3129 if (found->next == 0)
3130 break;
3132 found = found->next;
3134 newp = &found->next;
3137 else
3138 #endif /* !NO_ARCHIVES */
3139 NEWELT (concat (2, prefix, nlist[i]));
3141 globfree (&gl);
3143 #ifndef NO_ARCHIVES
3144 if (arname)
3145 free (arname);
3146 #endif
3148 if (tildep)
3149 free (tildep);
3152 *stringp = p;
3153 return new;