Add a test for another (still open) bug.
[make.git] / read.c
blob7dd5090a3546f196d3eea56c06b9d7e193c9fe8a
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 export_v:1;
66 unsigned int override_v:1;
67 unsigned int private_v:1;
70 /* Types of "words" that can be read in a makefile. */
71 enum make_word_type
73 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
74 w_varassign
78 /* A `struct conditionals' contains the information describing
79 all the active conditionals in a makefile.
81 The global variable `conditionals' contains the conditionals
82 information for the current makefile. It is initialized from
83 the static structure `toplevel_conditionals' and is later changed
84 to new structures for included makefiles. */
86 struct conditionals
88 unsigned int if_cmds; /* Depth of conditional nesting. */
89 unsigned int allocated; /* Elts allocated in following arrays. */
90 char *ignoring; /* Are we ignoring or interpreting?
91 0=interpreting, 1=not yet interpreted,
92 2=already interpreted */
93 char *seen_else; /* Have we already seen an `else'? */
96 static struct conditionals toplevel_conditionals;
97 static struct conditionals *conditionals = &toplevel_conditionals;
100 /* Default directories to search for include files in */
102 static const char *default_include_directories[] =
104 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
105 /* This completely up to the user when they install MSVC or other packages.
106 This is defined as a placeholder. */
107 # define INCLUDEDIR "."
108 #endif
109 INCLUDEDIR,
110 #ifndef _AMIGA
111 "/usr/gnu/include",
112 "/usr/local/include",
113 "/usr/include",
114 #endif
118 /* List of directories to search for include files in */
120 static const char **include_directories;
122 /* Maximum length of an element of the above. */
124 static unsigned int max_incl_len;
126 /* The filename and pointer to line number of the
127 makefile currently being read in. */
129 const struct floc *reading_file = 0;
131 /* The chain of makefiles read by read_makefile. */
133 static struct dep *read_makefiles = 0;
135 static int eval_makefile (const char *filename, int flags);
136 static int eval (struct ebuffer *buffer, int flags);
138 static long readline (struct ebuffer *ebuf);
139 static struct variable *do_define (char *name, enum variable_origin origin,
140 struct ebuffer *ebuf);
141 static int conditional_line (char *line, int len, const struct floc *flocp);
142 static void record_files (struct nameseq *filenames, const char *pattern,
143 const char *pattern_percent, char *depstr,
144 unsigned int cmds_started, char *commands,
145 unsigned int commands_idx, int two_colon,
146 const struct floc *flocp);
147 static void record_target_var (struct nameseq *filenames, char *defn,
148 enum variable_origin origin,
149 struct vmodifiers *vmod,
150 const struct floc *flocp);
151 static enum make_word_type get_next_mword (char *buffer, char *delim,
152 char **startp, unsigned int *length);
153 static void remove_comments (char *line);
154 static char *find_char_unquote (char *string, int stop1, int stop2,
155 int blank, int ignorevars);
158 /* Compare a word, both length and contents.
159 P must point to the word to be tested, and WLEN must be the length.
161 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
164 /* Read in all the makefiles and return the chain of their names. */
166 struct dep *
167 read_all_makefiles (const char **makefiles)
169 unsigned int num_makefiles = 0;
171 /* Create *_LIST variables, to hold the makefiles, targets, and variables
172 we will be reading. */
174 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
176 DB (DB_BASIC, (_("Reading makefiles...\n")));
178 /* If there's a non-null variable MAKEFILES, its value is a list of
179 files to read first thing. But don't let it prevent reading the
180 default makefiles and don't let the default goal come from there. */
183 char *value;
184 char *name, *p;
185 unsigned int length;
188 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
189 int save = warn_undefined_variables_flag;
190 warn_undefined_variables_flag = 0;
192 value = allocated_variable_expand ("$(MAKEFILES)");
194 warn_undefined_variables_flag = save;
197 /* Set NAME to the start of next token and LENGTH to its length.
198 MAKEFILES is updated for finding remaining tokens. */
199 p = value;
201 while ((name = find_next_token ((const char **)&p, &length)) != 0)
203 if (*p != '\0')
204 *p++ = '\0';
205 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
208 free (value);
211 /* Read makefiles specified with -f switches. */
213 if (makefiles != 0)
214 while (*makefiles != 0)
216 struct dep *tail = read_makefiles;
217 register struct dep *d;
219 if (! eval_makefile (*makefiles, 0))
220 perror_with_name ("", *makefiles);
222 /* Find the right element of read_makefiles. */
223 d = read_makefiles;
224 while (d->next != tail)
225 d = d->next;
227 /* Use the storage read_makefile allocates. */
228 *makefiles = dep_name (d);
229 ++num_makefiles;
230 ++makefiles;
233 /* If there were no -f switches, try the default names. */
235 if (num_makefiles == 0)
237 static char *default_makefiles[] =
238 #ifdef VMS
239 /* all lower case since readdir() (the vms version) 'lowercasifies' */
240 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
241 #else
242 #ifdef _AMIGA
243 { "GNUmakefile", "Makefile", "SMakefile", 0 };
244 #else /* !Amiga && !VMS */
245 { "GNUmakefile", "makefile", "Makefile", 0 };
246 #endif /* AMIGA */
247 #endif /* VMS */
248 register char **p = default_makefiles;
249 while (*p != 0 && !file_exists_p (*p))
250 ++p;
252 if (*p != 0)
254 if (! eval_makefile (*p, 0))
255 perror_with_name ("", *p);
257 else
259 /* No default makefile was found. Add the default makefiles to the
260 `read_makefiles' chain so they will be updated if possible. */
261 struct dep *tail = read_makefiles;
262 /* Add them to the tail, after any MAKEFILES variable makefiles. */
263 while (tail != 0 && tail->next != 0)
264 tail = tail->next;
265 for (p = default_makefiles; *p != 0; ++p)
267 struct dep *d = alloc_dep ();
268 d->file = enter_file (strcache_add (*p));
269 d->file->dontcare = 1;
270 /* Tell update_goal_chain to bail out as soon as this file is
271 made, and main not to die if we can't make this file. */
272 d->changed = RM_DONTCARE;
273 if (tail == 0)
274 read_makefiles = d;
275 else
276 tail->next = d;
277 tail = d;
279 if (tail != 0)
280 tail->next = 0;
284 return read_makefiles;
287 /* Install a new conditional and return the previous one. */
289 static struct conditionals *
290 install_conditionals (struct conditionals *new)
292 struct conditionals *save = conditionals;
294 memset (new, '\0', sizeof (*new));
295 conditionals = new;
297 return save;
300 /* Free the current conditionals and reinstate a saved one. */
302 static void
303 restore_conditionals (struct conditionals *saved)
305 /* Free any space allocated by conditional_line. */
306 if (conditionals->ignoring)
307 free (conditionals->ignoring);
308 if (conditionals->seen_else)
309 free (conditionals->seen_else);
311 /* Restore state. */
312 conditionals = saved;
315 static int
316 eval_makefile (const char *filename, int flags)
318 struct dep *deps;
319 struct ebuffer ebuf;
320 const struct floc *curfile;
321 char *expanded = 0;
322 int makefile_errno;
323 int r;
325 filename = strcache_add (filename);
326 ebuf.floc.filenm = filename;
327 ebuf.floc.lineno = 1;
329 if (ISDB (DB_VERBOSE))
331 printf (_("Reading makefile `%s'"), filename);
332 if (flags & RM_NO_DEFAULT_GOAL)
333 printf (_(" (no default goal)"));
334 if (flags & RM_INCLUDED)
335 printf (_(" (search path)"));
336 if (flags & RM_DONTCARE)
337 printf (_(" (don't care)"));
338 if (flags & RM_NO_TILDE)
339 printf (_(" (no ~ expansion)"));
340 puts ("...");
343 /* First, get a stream to read. */
345 /* Expand ~ in FILENAME unless it came from `include',
346 in which case it was already done. */
347 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
349 expanded = tilde_expand (filename);
350 if (expanded != 0)
351 filename = expanded;
354 ebuf.fp = fopen (filename, "r");
355 /* Save the error code so we print the right message later. */
356 makefile_errno = errno;
358 /* If the makefile wasn't found and it's either a makefile from
359 the `MAKEFILES' variable or an included makefile,
360 search the included makefile search path for this makefile. */
361 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
363 unsigned int i;
364 for (i = 0; include_directories[i] != 0; ++i)
366 const char *included = concat (3, include_directories[i],
367 "/", filename);
368 ebuf.fp = fopen (included, "r");
369 if (ebuf.fp)
371 filename = strcache_add (included);
372 break;
377 /* Add FILENAME to the chain of read makefiles. */
378 deps = alloc_dep ();
379 deps->next = read_makefiles;
380 read_makefiles = deps;
381 deps->file = lookup_file (filename);
382 if (deps->file == 0)
383 deps->file = enter_file (filename);
384 filename = deps->file->name;
385 deps->changed = flags;
386 if (flags & RM_DONTCARE)
387 deps->dontcare = 1;
389 if (expanded)
390 free (expanded);
392 /* If the makefile can't be found at all, give up entirely. */
394 if (ebuf.fp == 0)
396 /* If we did some searching, errno has the error from the last
397 attempt, rather from FILENAME itself. Restore it in case the
398 caller wants to use it in a message. */
399 errno = makefile_errno;
400 return 0;
403 /* Set close-on-exec to avoid leaking the makefile to children, such as
404 $(shell ...). */
405 #ifdef HAVE_FILENO
406 CLOSE_ON_EXEC (fileno (ebuf.fp));
407 #endif
409 /* Add this makefile to the list. */
410 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
411 f_append, 0);
413 /* Evaluate the makefile */
415 ebuf.size = 200;
416 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
418 curfile = reading_file;
419 reading_file = &ebuf.floc;
421 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
423 reading_file = curfile;
425 fclose (ebuf.fp);
427 free (ebuf.bufstart);
428 alloca (0);
429 return r;
433 eval_buffer (char *buffer)
435 struct ebuffer ebuf;
436 struct conditionals *saved;
437 struct conditionals new;
438 const struct floc *curfile;
439 int r;
441 /* Evaluate the buffer */
443 ebuf.size = strlen (buffer);
444 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
445 ebuf.fp = NULL;
447 if (reading_file)
448 ebuf.floc = *reading_file;
449 else
450 ebuf.floc.filenm = NULL;
452 curfile = reading_file;
453 reading_file = &ebuf.floc;
455 saved = install_conditionals (&new);
457 r = eval (&ebuf, 1);
459 restore_conditionals (saved);
461 reading_file = curfile;
463 alloca (0);
464 return r;
467 /* Check LINE to see if it's a variable assignment.
469 It might use one of the modifiers "export", "override", "private", or it
470 might be one of the conditional tokens like "ifdef", "include", etc.
472 If it's not a variable assignment, VMOD.V_ASSIGN is 0. Returns LINE.
474 Returns a pointer to the first non-modifier character, and sets VMOD
475 based on the modifiers found if any, plus V_ASSIGN is 1.
477 static char *
478 parse_var_assignment (const char *line, struct vmodifiers *vmod)
480 const char *p;
481 memset (vmod, '\0', sizeof (*vmod));
483 /* Find the start of the next token. If there isn't one we're done. */
484 line = next_token (line);
485 if (*line == '\0')
486 return (char *)line;
488 p = line;
489 while (1)
491 int wlen;
492 const char *p2;
493 enum variable_flavor flavor;
495 p2 = parse_variable_definition (p, &flavor);
497 /* If this is a variable assignment, we're done. */
498 if (p2)
499 break;
501 /* It's not a variable; see if it's a modifier. */
502 p2 = end_of_token (p);
503 wlen = p2 - p;
505 if (word1eq ("export"))
506 vmod->export_v = 1;
507 else if (word1eq ("override"))
508 vmod->override_v = 1;
509 else if (word1eq ("private"))
510 vmod->private_v = 1;
511 else if (word1eq ("define"))
513 /* We can't have modifiers after 'define' */
514 vmod->define_v = 1;
515 p = next_token (p2);
516 break;
518 else
519 /* Not a variable or modifier: this is not a variable assignment. */
520 return (char *)line;
522 /* It was a modifier. Try the next word. */
523 p = next_token (p2);
524 if (*p == '\0')
525 return (char *)line;
528 /* Found a variable assignment. */
529 vmod->assign_v = 1;
530 return (char *)p;
535 /* Read file FILENAME as a makefile and add its contents to the data base.
537 SET_DEFAULT is true if we are allowed to set the default goal. */
540 static int
541 eval (struct ebuffer *ebuf, int set_default)
543 char *collapsed = 0;
544 unsigned int collapsed_length = 0;
545 unsigned int commands_len = 200;
546 char *commands;
547 unsigned int commands_idx = 0;
548 unsigned int cmds_started, tgts_started;
549 int ignoring = 0, in_ignored_define = 0;
550 int no_targets = 0; /* Set when reading a rule without targets. */
551 struct nameseq *filenames = 0;
552 char *depstr = 0;
553 long nlines = 0;
554 int two_colon = 0;
555 const char *pattern = 0;
556 const char *pattern_percent;
557 struct floc *fstart;
558 struct floc fi;
560 #define record_waiting_files() \
561 do \
563 if (filenames != 0) \
565 fi.lineno = tgts_started; \
566 record_files (filenames, pattern, pattern_percent, depstr, \
567 cmds_started, commands, commands_idx, two_colon, \
568 &fi); \
569 filenames = 0; \
571 commands_idx = 0; \
572 no_targets = 0; \
573 pattern = 0; \
574 } while (0)
576 pattern_percent = 0;
577 cmds_started = tgts_started = 1;
579 fstart = &ebuf->floc;
580 fi.filenm = ebuf->floc.filenm;
582 /* Loop over lines in the file.
583 The strategy is to accumulate target names in FILENAMES, dependencies
584 in DEPS and commands in COMMANDS. These are used to define a rule
585 when the start of the next rule (or eof) is encountered.
587 When you see a "continue" in the loop below, that means we are moving on
588 to the next line _without_ ending any rule that we happen to be working
589 with at the moment. If you see a "goto rule_complete", then the
590 statement we just parsed also finishes the previous rule. */
592 commands = xmalloc (200);
594 while (1)
596 unsigned int linelen;
597 char *line;
598 unsigned int wlen;
599 char *p;
600 char *p2;
601 struct vmodifiers vmod;
603 /* At the top of this loop, we are starting a brand new line. */
604 /* Grab the next line to be evaluated */
605 ebuf->floc.lineno += nlines;
606 nlines = readline (ebuf);
608 /* If there is nothing left to eval, we're done. */
609 if (nlines < 0)
610 break;
612 /* If this line is empty, skip it. */
613 line = ebuf->buffer;
614 if (line[0] == '\0')
615 continue;
617 linelen = strlen (line);
619 /* Check for a shell command line first.
620 If it is not one, we can stop treating tab specially. */
621 if (line[0] == cmd_prefix)
623 if (no_targets)
624 /* Ignore the commands in a rule with no targets. */
625 continue;
627 /* If there is no preceding rule line, don't treat this line
628 as a command, even though it begins with a recipe prefix.
629 SunOS 4 make appears to behave this way. */
631 if (filenames != 0)
633 if (ignoring)
634 /* Yep, this is a shell command, and we don't care. */
635 continue;
637 /* Append this command line to the line being accumulated.
638 Strip command prefix chars that appear after newlines. */
639 if (commands_idx == 0)
640 cmds_started = ebuf->floc.lineno;
642 if (linelen + commands_idx > commands_len)
644 commands_len = (linelen + commands_idx) * 2;
645 commands = xrealloc (commands, commands_len);
647 p = &commands[commands_idx];
648 p2 = line + 1;
649 while (--linelen)
651 ++commands_idx;
652 *(p++) = *p2;
653 if (p2[0] == '\n' && p2[1] == cmd_prefix)
655 ++p2;
656 --linelen;
658 ++p2;
660 *p = '\n';
661 ++commands_idx;
663 continue;
667 /* This line is not a shell command line. Don't worry about whitespace.
668 Get more space if we need it; we don't need to preserve the current
669 contents of the buffer. */
671 if (collapsed_length < linelen+1)
673 collapsed_length = linelen+1;
674 if (collapsed)
675 free (collapsed);
676 /* Don't need xrealloc: we don't need to preserve the content. */
677 collapsed = xmalloc (collapsed_length);
679 strcpy (collapsed, line);
680 /* Collapse continuation lines. */
681 collapse_continuations (collapsed);
682 remove_comments (collapsed);
684 /* Get rid if starting space (including formfeed, vtab, etc.) */
685 p = collapsed;
686 while (isspace ((unsigned char)*p))
687 ++p;
689 /* See if this is a variable assignment. We need to do this early, to
690 allow variables with names like 'ifdef', 'export', 'private', etc. */
691 p = parse_var_assignment(p, &vmod);
692 if (vmod.assign_v)
694 struct variable *v;
695 enum variable_origin origin = vmod.override_v ? o_override : o_file;
697 /* If we're ignoring then we're done now. */
698 if (ignoring)
700 if (vmod.define_v)
701 in_ignored_define = 1;
702 continue;
705 if (vmod.define_v)
706 v = do_define (p, origin, ebuf);
707 else
708 v = try_variable_definition (fstart, p, origin, 0);
710 assert (v != NULL);
712 if (vmod.export_v)
713 v->export = v_export;
714 if (vmod.private_v)
715 v->private_var = 1;
717 /* This line has been dealt with. */
718 goto rule_complete;
721 /* If this line is completely empty, ignore it. */
722 if (*p == '\0')
723 continue;
725 p2 = end_of_token (p);
726 wlen = p2 - p;
727 p2 = next_token (p2);
729 /* If we're in an ignored define, skip this line (but maybe get out). */
730 if (in_ignored_define)
732 /* See if this is an endef line (plus optional comment). */
733 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
734 in_ignored_define = 0;
736 continue;
739 /* Check for conditional state changes. */
741 int i = conditional_line (p, wlen, fstart);
742 if (i != -2)
744 if (i == -1)
745 fatal (fstart, _("invalid syntax in conditional"));
747 ignoring = i;
748 continue;
752 /* Nothing to see here... move along. */
753 if (ignoring)
754 continue;
756 /* Manage the "export" keyword used outside of variable assignment
757 as well as "unexport". */
758 if (word1eq ("export") || word1eq ("unexport"))
760 int exporting = *p == 'u' ? 0 : 1;
762 /* (un)export by itself causes everything to be (un)exported. */
763 if (*p2 == '\0')
764 export_all_variables = exporting;
765 else
767 unsigned int l;
768 const char *cp;
769 char *ap;
771 /* Expand the line so we can use indirect and constructed
772 variable names in an (un)export command. */
773 cp = ap = allocated_variable_expand (p2);
775 for (p = find_next_token (&cp, &l); p != 0;
776 p = find_next_token (&cp, &l))
778 struct variable *v = lookup_variable (p, l);
779 if (v == 0)
780 v = define_variable_loc (p, l, "", o_file, 0, fstart);
781 v->export = exporting ? v_export : v_noexport;
784 free (ap);
786 goto rule_complete;
789 /* Handle the special syntax for vpath. */
790 if (word1eq ("vpath"))
792 const char *cp;
793 char *vpat;
794 unsigned int l;
795 cp = variable_expand (p2);
796 p = find_next_token (&cp, &l);
797 if (p != 0)
799 vpat = xstrndup (p, l);
800 p = find_next_token (&cp, &l);
801 /* No searchpath means remove all previous
802 selective VPATH's with the same pattern. */
804 else
805 /* No pattern means remove all previous selective VPATH's. */
806 vpat = 0;
807 construct_vpath_list (vpat, p);
808 if (vpat != 0)
809 free (vpat);
811 goto rule_complete;
814 /* Handle include and variants. */
815 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
817 /* We have found an `include' line specifying a nested
818 makefile to be read at this point. */
819 struct conditionals *save;
820 struct conditionals new_conditionals;
821 struct nameseq *files;
822 /* "-include" (vs "include") says no error if the file does not
823 exist. "sinclude" is an alias for this from SGI. */
824 int noerror = (p[0] != 'i');
826 p = allocated_variable_expand (p2);
828 /* If no filenames, it's a no-op. */
829 if (*p == '\0')
831 free (p);
832 continue;
835 /* Parse the list of file names. */
836 p2 = p;
837 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
838 free (p);
840 /* Save the state of conditionals and start
841 the included makefile with a clean slate. */
842 save = install_conditionals (&new_conditionals);
844 /* Record the rules that are waiting so they will determine
845 the default goal before those in the included makefile. */
846 record_waiting_files ();
848 /* Read each included makefile. */
849 while (files != 0)
851 struct nameseq *next = files->next;
852 const char *name = files->name;
853 int r;
855 free_ns (files);
856 files = next;
858 r = eval_makefile (name,
859 (RM_INCLUDED | RM_NO_TILDE
860 | (noerror ? RM_DONTCARE : 0)
861 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
862 if (!r && !noerror)
863 error (fstart, "%s: %s", name, strerror (errno));
866 /* Restore conditional state. */
867 restore_conditionals (save);
869 goto rule_complete;
872 /* This line starts with a tab but was not caught above because there
873 was no preceding target, and the line might have been usable as a
874 variable definition. But now we know it is definitely lossage. */
875 if (line[0] == cmd_prefix)
876 fatal(fstart, _("recipe commences before first target"));
878 /* This line describes some target files. This is complicated by
879 the existence of target-specific variables, because we can't
880 expand the entire line until we know if we have one or not. So
881 we expand the line word by word until we find the first `:',
882 then check to see if it's a target-specific variable.
884 In this algorithm, `lb_next' will point to the beginning of the
885 unexpanded parts of the input buffer, while `p2' points to the
886 parts of the expanded buffer we haven't searched yet. */
889 enum make_word_type wtype;
890 char *cmdleft, *semip, *lb_next;
891 unsigned int plen = 0;
892 char *colonp;
893 const char *end, *beg; /* Helpers for whitespace stripping. */
895 /* Record the previous rule. */
897 record_waiting_files ();
898 tgts_started = fstart->lineno;
900 /* Search the line for an unquoted ; that is not after an
901 unquoted #. */
902 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
903 if (cmdleft != 0 && *cmdleft == '#')
905 /* We found a comment before a semicolon. */
906 *cmdleft = '\0';
907 cmdleft = 0;
909 else if (cmdleft != 0)
910 /* Found one. Cut the line short there before expanding it. */
911 *(cmdleft++) = '\0';
912 semip = cmdleft;
914 collapse_continuations (line);
916 /* We can't expand the entire line, since if it's a per-target
917 variable we don't want to expand it. So, walk from the
918 beginning, expanding as we go, and looking for "interesting"
919 chars. The first word is always expandable. */
920 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
921 switch (wtype)
923 case w_eol:
924 if (cmdleft != 0)
925 fatal(fstart, _("missing rule before recipe"));
926 /* This line contained something but turned out to be nothing
927 but whitespace (a comment?). */
928 continue;
930 case w_colon:
931 case w_dcolon:
932 /* We accept and ignore rules without targets for
933 compatibility with SunOS 4 make. */
934 no_targets = 1;
935 continue;
937 default:
938 break;
941 p2 = variable_expand_string(NULL, lb_next, wlen);
943 while (1)
945 lb_next += wlen;
946 if (cmdleft == 0)
948 /* Look for a semicolon in the expanded line. */
949 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
951 if (cmdleft != 0)
953 unsigned long p2_off = p2 - variable_buffer;
954 unsigned long cmd_off = cmdleft - variable_buffer;
955 char *pend = p2 + strlen(p2);
957 /* Append any remnants of lb, then cut the line short
958 at the semicolon. */
959 *cmdleft = '\0';
961 /* One school of thought says that you shouldn't expand
962 here, but merely copy, since now you're beyond a ";"
963 and into a command script. However, the old parser
964 expanded the whole line, so we continue that for
965 backwards-compatiblity. Also, it wouldn't be
966 entirely consistent, since we do an unconditional
967 expand below once we know we don't have a
968 target-specific variable. */
969 (void)variable_expand_string(pend, lb_next, (long)-1);
970 lb_next += strlen(lb_next);
971 p2 = variable_buffer + p2_off;
972 cmdleft = variable_buffer + cmd_off + 1;
976 colonp = find_char_unquote(p2, ':', 0, 0, 0);
977 #ifdef HAVE_DOS_PATHS
978 /* The drive spec brain-damage strikes again... */
979 /* Note that the only separators of targets in this context
980 are whitespace and a left paren. If others are possible,
981 they should be added to the string in the call to index. */
982 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
983 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
984 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
985 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
986 #endif
987 if (colonp != 0)
988 break;
990 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
991 if (wtype == w_eol)
992 break;
994 p2 += strlen(p2);
995 *(p2++) = ' ';
996 p2 = variable_expand_string(p2, lb_next, wlen);
997 /* We don't need to worry about cmdleft here, because if it was
998 found in the variable_buffer the entire buffer has already
999 been expanded... we'll never get here. */
1002 p2 = next_token (variable_buffer);
1004 /* If the word we're looking at is EOL, see if there's _anything_
1005 on the line. If not, a variable expanded to nothing, so ignore
1006 it. If so, we can't parse this line so punt. */
1007 if (wtype == w_eol)
1009 if (*p2 != '\0')
1010 /* There's no need to be ivory-tower about this: check for
1011 one of the most common bugs found in makefiles... */
1012 fatal (fstart, _("missing separator%s"),
1013 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1014 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1015 continue;
1018 /* Make the colon the end-of-string so we know where to stop
1019 looking for targets. */
1020 *colonp = '\0';
1021 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1022 *p2 = ':';
1024 if (!filenames)
1026 /* We accept and ignore rules without targets for
1027 compatibility with SunOS 4 make. */
1028 no_targets = 1;
1029 continue;
1031 /* This should never be possible; we handled it above. */
1032 assert (*p2 != '\0');
1033 ++p2;
1035 /* Is this a one-colon or two-colon entry? */
1036 two_colon = *p2 == ':';
1037 if (two_colon)
1038 p2++;
1040 /* Test to see if it's a target-specific variable. Copy the rest
1041 of the buffer over, possibly temporarily (we'll expand it later
1042 if it's not a target-specific variable). PLEN saves the length
1043 of the unparsed section of p2, for later. */
1044 if (*lb_next != '\0')
1046 unsigned int l = p2 - variable_buffer;
1047 plen = strlen (p2);
1048 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1049 p2 = variable_buffer + l;
1052 p2 = parse_var_assignment (p2, &vmod);
1053 if (vmod.assign_v)
1055 /* If there was a semicolon found, add it back, plus anything
1056 after it. */
1057 if (semip)
1059 unsigned int l = p - variable_buffer;
1060 *(--semip) = ';';
1061 collapse_continuations (semip);
1062 variable_buffer_output (p2 + strlen (p2),
1063 semip, strlen (semip)+1);
1064 p = variable_buffer + l;
1066 record_target_var (filenames, p2,
1067 vmod.override_v ? o_override : o_file,
1068 &vmod, fstart);
1069 filenames = 0;
1070 continue;
1073 /* This is a normal target, _not_ a target-specific variable.
1074 Unquote any = in the dependency list. */
1075 find_char_unquote (lb_next, '=', 0, 0, 0);
1077 /* We have some targets, so don't ignore the following commands. */
1078 no_targets = 0;
1080 /* Expand the dependencies, etc. */
1081 if (*lb_next != '\0')
1083 unsigned int l = p2 - variable_buffer;
1084 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1085 p2 = variable_buffer + l;
1087 /* Look for a semicolon in the expanded line. */
1088 if (cmdleft == 0)
1090 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1091 if (cmdleft != 0)
1092 *(cmdleft++) = '\0';
1096 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1097 p = strchr (p2, ':');
1098 while (p != 0 && p[-1] == '\\')
1100 char *q = &p[-1];
1101 int backslash = 0;
1102 while (*q-- == '\\')
1103 backslash = !backslash;
1104 if (backslash)
1105 p = strchr (p + 1, ':');
1106 else
1107 break;
1109 #ifdef _AMIGA
1110 /* Here, the situation is quite complicated. Let's have a look
1111 at a couple of targets:
1113 install: dev:make
1115 dev:make: make
1117 dev:make:: xyz
1119 The rule is that it's only a target, if there are TWO :'s
1120 OR a space around the :.
1122 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1123 || isspace ((unsigned char)p[-1])))
1124 p = 0;
1125 #endif
1126 #ifdef HAVE_DOS_PATHS
1128 int check_again;
1129 do {
1130 check_again = 0;
1131 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1132 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1133 isalpha ((unsigned char)p[-1]) &&
1134 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1135 p = strchr (p + 1, ':');
1136 check_again = 1;
1138 } while (check_again);
1140 #endif
1141 if (p != 0)
1143 struct nameseq *target;
1144 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1145 PARSEFS_NOGLOB);
1146 ++p2;
1147 if (target == 0)
1148 fatal (fstart, _("missing target pattern"));
1149 else if (target->next != 0)
1150 fatal (fstart, _("multiple target patterns"));
1151 pattern_percent = find_percent_cached (&target->name);
1152 pattern = target->name;
1153 if (pattern_percent == 0)
1154 fatal (fstart, _("target pattern contains no `%%'"));
1155 free_ns (target);
1157 else
1158 pattern = 0;
1160 /* Strip leading and trailing whitespaces. */
1161 beg = p2;
1162 end = beg + strlen (beg) - 1;
1163 strip_whitespace (&beg, &end);
1165 /* Put all the prerequisites here; they'll be parsed later. */
1166 if (beg <= end && *beg != '\0')
1167 depstr = xstrndup (beg, end - beg + 1);
1168 else
1169 depstr = 0;
1171 commands_idx = 0;
1172 if (cmdleft != 0)
1174 /* Semicolon means rest of line is a command. */
1175 unsigned int l = strlen (cmdleft);
1177 cmds_started = fstart->lineno;
1179 /* Add this command line to the buffer. */
1180 if (l + 2 > commands_len)
1182 commands_len = (l + 2) * 2;
1183 commands = xrealloc (commands, commands_len);
1185 memcpy (commands, cmdleft, l);
1186 commands_idx += l;
1187 commands[commands_idx++] = '\n';
1190 /* Determine if this target should be made default. We used to do
1191 this in record_files() but because of the delayed target recording
1192 and because preprocessor directives are legal in target's commands
1193 it is too late. Consider this fragment for example:
1195 foo:
1197 ifeq ($(.DEFAULT_GOAL),foo)
1199 endif
1201 Because the target is not recorded until after ifeq directive is
1202 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1203 would expect. Because of this we have to move the logic here. */
1205 if (set_default && default_goal_var->value[0] == '\0')
1207 const char *name;
1208 struct dep *d;
1209 struct nameseq *t = filenames;
1211 for (; t != 0; t = t->next)
1213 int reject = 0;
1214 name = t->name;
1216 /* We have nothing to do if this is an implicit rule. */
1217 if (strchr (name, '%') != 0)
1218 break;
1220 /* See if this target's name does not start with a `.',
1221 unless it contains a slash. */
1222 if (*name == '.' && strchr (name, '/') == 0
1223 #ifdef HAVE_DOS_PATHS
1224 && strchr (name, '\\') == 0
1225 #endif
1227 continue;
1230 /* If this file is a suffix, don't let it be
1231 the default goal file. */
1232 for (d = suffix_file->deps; d != 0; d = d->next)
1234 register struct dep *d2;
1235 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1237 reject = 1;
1238 break;
1240 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1242 unsigned int l = strlen (dep_name (d2));
1243 if (!strneq (name, dep_name (d2), l))
1244 continue;
1245 if (streq (name + l, dep_name (d)))
1247 reject = 1;
1248 break;
1252 if (reject)
1253 break;
1256 if (!reject)
1258 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1259 o_file, 0, NILF);
1260 break;
1265 continue;
1268 /* We get here except in the case that we just read a rule line.
1269 Record now the last rule we read, so following spurious
1270 commands are properly diagnosed. */
1271 rule_complete:
1272 record_waiting_files ();
1275 #undef word1eq
1277 if (conditionals->if_cmds)
1278 fatal (fstart, _("missing `endif'"));
1280 /* At eof, record the last rule. */
1281 record_waiting_files ();
1283 if (collapsed)
1284 free (collapsed);
1285 free (commands);
1287 return 1;
1291 /* Remove comments from LINE.
1292 This is done by copying the text at LINE onto itself. */
1294 static void
1295 remove_comments (char *line)
1297 char *comment;
1299 comment = find_char_unquote (line, '#', 0, 0, 0);
1301 if (comment != 0)
1302 /* Cut off the line at the #. */
1303 *comment = '\0';
1306 /* Execute a `define' directive.
1307 The first line has already been read, and NAME is the name of
1308 the variable to be defined. The following lines remain to be read. */
1310 static struct variable *
1311 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1313 struct variable *v;
1314 enum variable_flavor flavor;
1315 struct floc defstart;
1316 int nlevels = 1;
1317 unsigned int length = 100;
1318 char *definition = xmalloc (length);
1319 unsigned int idx = 0;
1320 char *p, *var;
1322 defstart = ebuf->floc;
1324 p = parse_variable_definition (name, &flavor);
1325 if (p == NULL)
1326 /* No assignment token, so assume recursive. */
1327 flavor = f_recursive;
1328 else
1330 if (*(next_token (p)) != '\0')
1331 error (&defstart, _("extraneous text after `define' directive"));
1333 /* Chop the string before the assignment token to get the name. */
1334 p[flavor == f_recursive ? -1 : -2] = '\0';
1337 /* Expand the variable name and find the beginning (NAME) and end. */
1338 var = allocated_variable_expand (name);
1339 name = next_token (var);
1340 if (*name == '\0')
1341 fatal (&defstart, _("empty variable name"));
1342 p = name + strlen (name) - 1;
1343 while (p > name && isblank ((unsigned char)*p))
1344 --p;
1345 p[1] = '\0';
1347 /* Now read the value of the variable. */
1348 while (1)
1350 unsigned int len;
1351 char *line;
1352 long nlines = readline (ebuf);
1354 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1355 if (nlines < 0)
1356 fatal (&defstart, _("missing `endef', unterminated `define'"));
1358 ebuf->floc.lineno += nlines;
1359 line = ebuf->buffer;
1361 collapse_continuations (line);
1363 /* If the line doesn't begin with a tab, test to see if it introduces
1364 another define, or ends one. Stop if we find an 'endef' */
1365 if (line[0] != cmd_prefix)
1367 p = next_token (line);
1368 len = strlen (p);
1370 /* If this is another 'define', increment the level count. */
1371 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1372 && strneq (p, "define", 6))
1373 ++nlevels;
1375 /* If this is an 'endef', decrement the count. If it's now 0,
1376 we've found the last one. */
1377 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1378 && strneq (p, "endef", 5))
1380 p += 5;
1381 remove_comments (p);
1382 if (*(next_token (p)) != '\0')
1383 error (&ebuf->floc,
1384 _("extraneous text after `endef' directive"));
1386 if (--nlevels == 0)
1387 break;
1391 /* Add this line to the variable definition. */
1392 len = strlen (line);
1393 if (idx + len + 1 > length)
1395 length = (idx + len) * 2;
1396 definition = xrealloc (definition, length + 1);
1399 memcpy (&definition[idx], line, len);
1400 idx += len;
1401 /* Separate lines with a newline. */
1402 definition[idx++] = '\n';
1405 /* We've got what we need; define the variable. */
1406 if (idx == 0)
1407 definition[0] = '\0';
1408 else
1409 definition[idx - 1] = '\0';
1411 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1412 free (definition);
1413 free (var);
1414 return (v);
1417 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1418 "ifneq", "else" and "endif".
1419 LINE is the input line, with the command as its first word.
1421 FILENAME and LINENO are the filename and line number in the
1422 current makefile. They are used for error messages.
1424 Value is -2 if the line is not a conditional at all,
1425 -1 if the line is an invalid conditional,
1426 0 if following text should be interpreted,
1427 1 if following text should be ignored. */
1429 static int
1430 conditional_line (char *line, int len, const struct floc *flocp)
1432 char *cmdname;
1433 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1434 unsigned int i;
1435 unsigned int o;
1437 /* Compare a word, both length and contents. */
1438 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1439 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1441 /* Make sure this line is a conditional. */
1442 chkword ("ifdef", c_ifdef)
1443 else chkword ("ifndef", c_ifndef)
1444 else chkword ("ifeq", c_ifeq)
1445 else chkword ("ifneq", c_ifneq)
1446 else chkword ("else", c_else)
1447 else chkword ("endif", c_endif)
1448 else
1449 return -2;
1451 /* Found one: skip past it and any whitespace after it. */
1452 line = next_token (line + len);
1454 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1456 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1457 if (cmdtype == c_endif)
1459 if (*line != '\0')
1460 EXTRANEOUS ();
1462 if (!conditionals->if_cmds)
1463 fatal (flocp, _("extraneous `%s'"), cmdname);
1465 --conditionals->if_cmds;
1467 goto DONE;
1470 /* An 'else' statement can either be simple, or it can have another
1471 conditional after it. */
1472 if (cmdtype == c_else)
1474 const char *p;
1476 if (!conditionals->if_cmds)
1477 fatal (flocp, _("extraneous `%s'"), cmdname);
1479 o = conditionals->if_cmds - 1;
1481 if (conditionals->seen_else[o])
1482 fatal (flocp, _("only one `else' per conditional"));
1484 /* Change the state of ignorance. */
1485 switch (conditionals->ignoring[o])
1487 case 0:
1488 /* We've just been interpreting. Never do it again. */
1489 conditionals->ignoring[o] = 2;
1490 break;
1491 case 1:
1492 /* We've never interpreted yet. Maybe this time! */
1493 conditionals->ignoring[o] = 0;
1494 break;
1497 /* It's a simple 'else'. */
1498 if (*line == '\0')
1500 conditionals->seen_else[o] = 1;
1501 goto DONE;
1504 /* The 'else' has extra text. That text must be another conditional
1505 and cannot be an 'else' or 'endif'. */
1507 /* Find the length of the next word. */
1508 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1510 len = p - line;
1512 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1513 if (word1eq("else") || word1eq("endif")
1514 || conditional_line (line, len, flocp) < 0)
1515 EXTRANEOUS ();
1516 else
1518 /* conditional_line() created a new level of conditional.
1519 Raise it back to this level. */
1520 if (conditionals->ignoring[o] < 2)
1521 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1522 --conditionals->if_cmds;
1525 goto DONE;
1528 if (conditionals->allocated == 0)
1530 conditionals->allocated = 5;
1531 conditionals->ignoring = xmalloc (conditionals->allocated);
1532 conditionals->seen_else = xmalloc (conditionals->allocated);
1535 o = conditionals->if_cmds++;
1536 if (conditionals->if_cmds > conditionals->allocated)
1538 conditionals->allocated += 5;
1539 conditionals->ignoring = xrealloc (conditionals->ignoring,
1540 conditionals->allocated);
1541 conditionals->seen_else = xrealloc (conditionals->seen_else,
1542 conditionals->allocated);
1545 /* Record that we have seen an `if...' but no `else' so far. */
1546 conditionals->seen_else[o] = 0;
1548 /* Search through the stack to see if we're already ignoring. */
1549 for (i = 0; i < o; ++i)
1550 if (conditionals->ignoring[i])
1552 /* We are already ignoring, so just push a level to match the next
1553 "else" or "endif", and keep ignoring. We don't want to expand
1554 variables in the condition. */
1555 conditionals->ignoring[o] = 1;
1556 return 1;
1559 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1561 char *var;
1562 struct variable *v;
1563 char *p;
1565 /* Expand the thing we're looking up, so we can use indirect and
1566 constructed variable names. */
1567 var = allocated_variable_expand (line);
1569 /* Make sure there's only one variable name to test. */
1570 p = end_of_token (var);
1571 i = p - var;
1572 p = next_token (p);
1573 if (*p != '\0')
1574 return -1;
1576 var[i] = '\0';
1577 v = lookup_variable (var, i);
1579 conditionals->ignoring[o] =
1580 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1582 free (var);
1584 else
1586 /* "ifeq" or "ifneq". */
1587 char *s1, *s2;
1588 unsigned int l;
1589 char termin = *line == '(' ? ',' : *line;
1591 if (termin != ',' && termin != '"' && termin != '\'')
1592 return -1;
1594 s1 = ++line;
1595 /* Find the end of the first string. */
1596 if (termin == ',')
1598 int count = 0;
1599 for (; *line != '\0'; ++line)
1600 if (*line == '(')
1601 ++count;
1602 else if (*line == ')')
1603 --count;
1604 else if (*line == ',' && count <= 0)
1605 break;
1607 else
1608 while (*line != '\0' && *line != termin)
1609 ++line;
1611 if (*line == '\0')
1612 return -1;
1614 if (termin == ',')
1616 /* Strip blanks after the first string. */
1617 char *p = line++;
1618 while (isblank ((unsigned char)p[-1]))
1619 --p;
1620 *p = '\0';
1622 else
1623 *line++ = '\0';
1625 s2 = variable_expand (s1);
1626 /* We must allocate a new copy of the expanded string because
1627 variable_expand re-uses the same buffer. */
1628 l = strlen (s2);
1629 s1 = alloca (l + 1);
1630 memcpy (s1, s2, l + 1);
1632 if (termin != ',')
1633 /* Find the start of the second string. */
1634 line = next_token (line);
1636 termin = termin == ',' ? ')' : *line;
1637 if (termin != ')' && termin != '"' && termin != '\'')
1638 return -1;
1640 /* Find the end of the second string. */
1641 if (termin == ')')
1643 int count = 0;
1644 s2 = next_token (line);
1645 for (line = s2; *line != '\0'; ++line)
1647 if (*line == '(')
1648 ++count;
1649 else if (*line == ')')
1651 if (count <= 0)
1652 break;
1653 else
1654 --count;
1658 else
1660 ++line;
1661 s2 = line;
1662 while (*line != '\0' && *line != termin)
1663 ++line;
1666 if (*line == '\0')
1667 return -1;
1669 *line = '\0';
1670 line = next_token (++line);
1671 if (*line != '\0')
1672 EXTRANEOUS ();
1674 s2 = variable_expand (s2);
1675 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1678 DONE:
1679 /* Search through the stack to see if we're ignoring. */
1680 for (i = 0; i < conditionals->if_cmds; ++i)
1681 if (conditionals->ignoring[i])
1682 return 1;
1683 return 0;
1686 /* Remove duplicate dependencies in CHAIN. */
1688 static unsigned long
1689 dep_hash_1 (const void *key)
1691 return_STRING_HASH_1 (dep_name ((struct dep const *) key));
1694 static unsigned long
1695 dep_hash_2 (const void *key)
1697 return_STRING_HASH_2 (dep_name ((struct dep const *) key));
1700 static int
1701 dep_hash_cmp (const void *x, const void *y)
1703 struct dep *dx = (struct dep *) x;
1704 struct dep *dy = (struct dep *) y;
1705 int cmp = strcmp (dep_name (dx), dep_name (dy));
1707 /* If the names are the same but ignore_mtimes are not equal, one of these
1708 is an order-only prerequisite and one isn't. That means that we should
1709 remove the one that isn't and keep the one that is. */
1711 if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
1712 dx->ignore_mtime = dy->ignore_mtime = 0;
1714 return cmp;
1718 void
1719 uniquize_deps (struct dep *chain)
1721 struct hash_table deps;
1722 register struct dep **depp;
1724 hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
1726 /* Make sure that no dependencies are repeated. This does not
1727 really matter for the purpose of updating targets, but it
1728 might make some names be listed twice for $^ and $?. */
1730 depp = &chain;
1731 while (*depp)
1733 struct dep *dep = *depp;
1734 struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
1735 if (HASH_VACANT (*dep_slot))
1737 hash_insert_at (&deps, dep, dep_slot);
1738 depp = &dep->next;
1740 else
1742 /* Don't bother freeing duplicates.
1743 It's dangerous and little benefit accrues. */
1744 *depp = dep->next;
1748 hash_free (&deps, 0);
1751 /* Record target-specific variable values for files FILENAMES.
1752 TWO_COLON is nonzero if a double colon was used.
1754 The links of FILENAMES are freed, and so are any names in it
1755 that are not incorporated into other data structures.
1757 If the target is a pattern, add the variable to the pattern-specific
1758 variable value list. */
1760 static void
1761 record_target_var (struct nameseq *filenames, char *defn,
1762 enum variable_origin origin, struct vmodifiers *vmod,
1763 const struct floc *flocp)
1765 struct nameseq *nextf;
1766 struct variable_set_list *global;
1768 global = current_variable_set_list;
1770 /* If the variable is an append version, store that but treat it as a
1771 normal recursive variable. */
1773 for (; filenames != 0; filenames = nextf)
1775 struct variable *v;
1776 const char *name = filenames->name;
1777 const char *fname;
1778 const char *percent;
1779 struct pattern_var *p;
1781 nextf = filenames->next;
1782 free_ns (filenames);
1784 /* If it's a pattern target, then add it to the pattern-specific
1785 variable list. */
1786 percent = find_percent_cached (&name);
1787 if (percent)
1789 /* Get a reference for this pattern-specific variable struct. */
1790 p = create_pattern_var (name, percent);
1791 p->variable.fileinfo = *flocp;
1792 /* I don't think this can fail since we already determined it was a
1793 variable definition. */
1794 v = assign_variable_definition (&p->variable, defn);
1795 assert (v != 0);
1797 v->origin = origin;
1798 if (v->flavor == f_simple)
1799 v->value = allocated_variable_expand (v->value);
1800 else
1801 v->value = xstrdup (v->value);
1803 fname = p->target;
1805 else
1807 struct file *f;
1809 /* Get a file reference for this file, and initialize it.
1810 We don't want to just call enter_file() because that allocates a
1811 new entry if the file is a double-colon, which we don't want in
1812 this situation. */
1813 f = lookup_file (name);
1814 if (!f)
1815 f = enter_file (strcache_add (name));
1816 else if (f->double_colon)
1817 f = f->double_colon;
1819 initialize_file_variables (f, 1);
1820 fname = f->name;
1822 current_variable_set_list = f->variables;
1823 v = try_variable_definition (flocp, defn, origin, 1);
1824 if (!v)
1825 fatal (flocp, _("Malformed target-specific variable definition"));
1826 current_variable_set_list = global;
1829 /* Set up the variable to be *-specific. */
1830 v->per_target = 1;
1831 v->private_var = vmod->private_v;
1832 v->export = vmod->export_v ? v_export : v_default;
1834 /* If it's not an override, check to see if there was a command-line
1835 setting. If so, reset the value. */
1836 if (v->origin != o_override)
1838 struct variable *gv;
1839 int len = strlen(v->name);
1841 gv = lookup_variable (v->name, len);
1842 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1844 if (v->value != 0)
1845 free (v->value);
1846 v->value = xstrdup (gv->value);
1847 v->origin = gv->origin;
1848 v->recursive = gv->recursive;
1849 v->append = 0;
1855 /* Record a description line for files FILENAMES,
1856 with dependencies DEPS, commands to execute described
1857 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1858 TWO_COLON is nonzero if a double colon was used.
1859 If not nil, PATTERN is the `%' pattern to make this
1860 a static pattern rule, and PATTERN_PERCENT is a pointer
1861 to the `%' within it.
1863 The links of FILENAMES are freed, and so are any names in it
1864 that are not incorporated into other data structures. */
1866 static void
1867 record_files (struct nameseq *filenames, const char *pattern,
1868 const char *pattern_percent, char *depstr,
1869 unsigned int cmds_started, char *commands,
1870 unsigned int commands_idx, int two_colon,
1871 const struct floc *flocp)
1873 struct commands *cmds;
1874 struct dep *deps;
1875 const char *implicit_percent;
1876 const char *name;
1878 /* If we've already snapped deps, that means we're in an eval being
1879 resolved after the makefiles have been read in. We can't add more rules
1880 at this time, since they won't get snapped and we'll get core dumps.
1881 See Savannah bug # 12124. */
1882 if (snapped_deps)
1883 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1885 /* Determine if this is a pattern rule or not. */
1886 name = filenames->name;
1887 implicit_percent = find_percent_cached (&name);
1889 /* If there's a recipe, set up a struct for it. */
1890 if (commands_idx > 0)
1892 cmds = xmalloc (sizeof (struct commands));
1893 cmds->fileinfo.filenm = flocp->filenm;
1894 cmds->fileinfo.lineno = cmds_started;
1895 cmds->commands = xstrndup (commands, commands_idx);
1896 cmds->command_lines = 0;
1898 else
1899 cmds = 0;
1901 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1902 expansion: if so, snap_deps() will do it. */
1903 if (depstr == 0)
1904 deps = 0;
1905 else if (second_expansion && strchr (depstr, '$'))
1907 deps = alloc_dep ();
1908 deps->name = depstr;
1909 deps->need_2nd_expansion = 1;
1910 deps->staticpattern = pattern != 0;
1912 else
1914 deps = split_prereqs (depstr);
1915 free (depstr);
1917 /* We'll enter static pattern prereqs later when we have the stem. We
1918 don't want to enter pattern rules at all so that we don't think that
1919 they ought to exist (make manual "Implicit Rule Search Algorithm",
1920 item 5c). */
1921 if (! pattern && ! implicit_percent)
1922 deps = enter_prereqs (deps, NULL);
1925 /* For implicit rules, _all_ the targets must have a pattern. That means we
1926 can test the first one to see if we're working with an implicit rule; if
1927 so we handle it specially. */
1929 if (implicit_percent)
1931 struct nameseq *nextf;
1932 const char **targets, **target_pats;
1933 unsigned int c;
1935 if (pattern != 0)
1936 fatal (flocp, _("mixed implicit and static pattern rules"));
1938 /* Count the targets to create an array of target names.
1939 We already have the first one. */
1940 nextf = filenames->next;
1941 free_ns (filenames);
1942 filenames = nextf;
1944 for (c = 1; nextf; ++c, nextf = nextf->next)
1946 targets = xmalloc (c * sizeof (const char *));
1947 target_pats = xmalloc (c * sizeof (const char *));
1949 targets[0] = name;
1950 target_pats[0] = implicit_percent;
1952 c = 1;
1953 while (filenames)
1955 name = filenames->name;
1956 implicit_percent = find_percent_cached (&name);
1958 if (implicit_percent == 0)
1959 fatal (flocp, _("mixed implicit and normal rules"));
1961 targets[c] = name;
1962 target_pats[c] = implicit_percent;
1963 ++c;
1965 nextf = filenames->next;
1966 free_ns (filenames);
1967 filenames = nextf;
1970 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1972 return;
1976 /* Walk through each target and create it in the database.
1977 We already set up the first target, above. */
1978 while (1)
1980 struct nameseq *nextf = filenames->next;
1981 struct file *f;
1982 struct dep *this = 0;
1984 free_ns (filenames);
1986 /* Check for special targets. Do it here instead of, say, snap_deps()
1987 so that we can immediately use the value. */
1988 if (streq (name, ".POSIX"))
1989 posix_pedantic = 1;
1990 else if (streq (name, ".SECONDEXPANSION"))
1991 second_expansion = 1;
1993 /* If this is a static pattern rule:
1994 `targets: target%pattern: prereq%pattern; recipe',
1995 make sure the pattern matches this target name. */
1996 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1997 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1998 else if (deps)
1999 /* If there are multiple targets, copy the chain DEPS for all but the
2000 last one. It is not safe for the same deps to go in more than one
2001 place in the database. */
2002 this = nextf != 0 ? copy_dep_chain (deps) : deps;
2004 /* Find or create an entry in the file database for this target. */
2005 if (!two_colon)
2007 /* Single-colon. Combine this rule with the file's existing record,
2008 if any. */
2009 f = enter_file (strcache_add (name));
2010 if (f->double_colon)
2011 fatal (flocp,
2012 _("target file `%s' has both : and :: entries"), f->name);
2014 /* If CMDS == F->CMDS, this target was listed in this rule
2015 more than once. Just give a warning since this is harmless. */
2016 if (cmds != 0 && cmds == f->cmds)
2017 error (flocp,
2018 _("target `%s' given more than once in the same rule."),
2019 f->name);
2021 /* Check for two single-colon entries both with commands.
2022 Check is_target so that we don't lose on files such as .c.o
2023 whose commands were preinitialized. */
2024 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2026 error (&cmds->fileinfo,
2027 _("warning: overriding recipe for target `%s'"),
2028 f->name);
2029 error (&f->cmds->fileinfo,
2030 _("warning: ignoring old recipe for target `%s'"),
2031 f->name);
2034 /* Defining .DEFAULT with no deps or cmds clears it. */
2035 if (f == default_file && this == 0 && cmds == 0)
2036 f->cmds = 0;
2037 if (cmds != 0)
2038 f->cmds = cmds;
2040 /* Defining .SUFFIXES with no dependencies clears out the list of
2041 suffixes. */
2042 if (f == suffix_file && this == 0)
2044 free_dep_chain (f->deps);
2045 f->deps = 0;
2048 else
2050 /* Double-colon. Make a new record even if there already is one. */
2051 f = lookup_file (name);
2053 /* Check for both : and :: rules. Check is_target so we don't lose
2054 on default suffix rules or makefiles. */
2055 if (f != 0 && f->is_target && !f->double_colon)
2056 fatal (flocp,
2057 _("target file `%s' has both : and :: entries"), f->name);
2059 f = enter_file (strcache_add (name));
2060 /* If there was an existing entry and it was a double-colon entry,
2061 enter_file will have returned a new one, making it the prev
2062 pointer of the old one, and setting its double_colon pointer to
2063 the first one. */
2064 if (f->double_colon == 0)
2065 /* This is the first entry for this name, so we must set its
2066 double_colon pointer to itself. */
2067 f->double_colon = f;
2069 f->cmds = cmds;
2072 f->is_target = 1;
2074 /* If this is a static pattern rule, set the stem to the part of its
2075 name that matched the `%' in the pattern, so you can use $* in the
2076 commands. If we didn't do it before, enter the prereqs now. */
2077 if (pattern)
2079 static const char *percent = "%";
2080 char *buffer = variable_expand ("");
2081 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2082 pattern_percent+1, percent+1);
2083 f->stem = strcache_add_len (buffer, o - buffer);
2084 if (this)
2086 if (! this->need_2nd_expansion)
2087 this = enter_prereqs (this, f->stem);
2088 else
2089 this->stem = f->stem;
2093 /* Add the dependencies to this file entry. */
2094 if (this != 0)
2096 /* Add the file's old deps and the new ones in THIS together. */
2097 if (f->deps == 0)
2098 f->deps = this;
2099 else if (cmds != 0)
2101 struct dep *d = this;
2103 /* If this rule has commands, put these deps first. */
2104 while (d->next != 0)
2105 d = d->next;
2107 d->next = f->deps;
2108 f->deps = this;
2110 else
2112 struct dep *d = f->deps;
2114 /* A rule without commands: put its prereqs at the end. */
2115 while (d->next != 0)
2116 d = d->next;
2118 d->next = this;
2122 name = f->name;
2124 /* All done! Set up for the next one. */
2125 if (nextf == 0)
2126 break;
2128 filenames = nextf;
2130 /* Reduce escaped percents. If there are any unescaped it's an error */
2131 name = filenames->name;
2132 if (find_percent_cached (&name))
2133 fatal (flocp, _("mixed implicit and normal rules"));
2137 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2138 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2139 Quoting backslashes are removed from STRING by compacting it into
2140 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2141 one, or nil if there are none. STOPCHARs inside variable references are
2142 ignored if IGNOREVARS is true.
2144 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2146 static char *
2147 find_char_unquote (char *string, int stop1, int stop2, int blank,
2148 int ignorevars)
2150 unsigned int string_len = 0;
2151 char *p = string;
2153 if (ignorevars)
2154 ignorevars = '$';
2156 while (1)
2158 if (stop2 && blank)
2159 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2160 && ! isblank ((unsigned char) *p))
2161 ++p;
2162 else if (stop2)
2163 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2164 ++p;
2165 else if (blank)
2166 while (*p != '\0' && *p != ignorevars && *p != stop1
2167 && ! isblank ((unsigned char) *p))
2168 ++p;
2169 else
2170 while (*p != '\0' && *p != ignorevars && *p != stop1)
2171 ++p;
2173 if (*p == '\0')
2174 break;
2176 /* If we stopped due to a variable reference, skip over its contents. */
2177 if (*p == ignorevars)
2179 char openparen = p[1];
2181 p += 2;
2183 /* Skip the contents of a non-quoted, multi-char variable ref. */
2184 if (openparen == '(' || openparen == '{')
2186 unsigned int pcount = 1;
2187 char closeparen = (openparen == '(' ? ')' : '}');
2189 while (*p)
2191 if (*p == openparen)
2192 ++pcount;
2193 else if (*p == closeparen)
2194 if (--pcount == 0)
2196 ++p;
2197 break;
2199 ++p;
2203 /* Skipped the variable reference: look for STOPCHARS again. */
2204 continue;
2207 if (p > string && p[-1] == '\\')
2209 /* Search for more backslashes. */
2210 int i = -2;
2211 while (&p[i] >= string && p[i] == '\\')
2212 --i;
2213 ++i;
2214 /* Only compute the length if really needed. */
2215 if (string_len == 0)
2216 string_len = strlen (string);
2217 /* The number of backslashes is now -I.
2218 Copy P over itself to swallow half of them. */
2219 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2220 p += i/2;
2221 if (i % 2 == 0)
2222 /* All the backslashes quoted each other; the STOPCHAR was
2223 unquoted. */
2224 return p;
2226 /* The STOPCHAR was quoted by a backslash. Look for another. */
2228 else
2229 /* No backslash in sight. */
2230 return p;
2233 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2234 return 0;
2237 /* Search PATTERN for an unquoted % and handle quoting. */
2239 char *
2240 find_percent (char *pattern)
2242 return find_char_unquote (pattern, '%', 0, 0, 0);
2245 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2246 the % or NULL if no % was found.
2247 This version is used with strings in the string cache: if there's a need to
2248 modify the string a new version will be added to the string cache and
2249 *STRING will be set to that. */
2251 const char *
2252 find_percent_cached (const char **string)
2254 const char *p = *string;
2255 char *new = 0;
2256 int slen = 0;
2258 /* If the first char is a % return now. This lets us avoid extra tests
2259 inside the loop. */
2260 if (*p == '%')
2261 return p;
2263 while (1)
2265 while (*p != '\0' && *p != '%')
2266 ++p;
2268 if (*p == '\0')
2269 break;
2271 /* See if this % is escaped with a backslash; if not we're done. */
2272 if (p[-1] != '\\')
2273 break;
2276 /* Search for more backslashes. */
2277 char *pv;
2278 int i = -2;
2280 while (&p[i] >= *string && p[i] == '\\')
2281 --i;
2282 ++i;
2284 /* At this point we know we'll need to allocate a new string.
2285 Make a copy if we haven't yet done so. */
2286 if (! new)
2288 slen = strlen (*string);
2289 new = alloca (slen + 1);
2290 memcpy (new, *string, slen + 1);
2291 p = new + (p - *string);
2292 *string = new;
2295 /* At this point *string, p, and new all point into the same string.
2296 Get a non-const version of p so we can modify new. */
2297 pv = new + (p - *string);
2299 /* The number of backslashes is now -I.
2300 Copy P over itself to swallow half of them. */
2301 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2302 p += i/2;
2304 /* If the backslashes quoted each other; the % was unquoted. */
2305 if (i % 2 == 0)
2306 break;
2310 /* If we had to change STRING, add it to the strcache. */
2311 if (new)
2313 *string = strcache_add (*string);
2314 p = *string + (p - new);
2317 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2318 return (*p == '\0') ? NULL : p;
2321 /* Find the next line of text in an eval buffer, combining continuation lines
2322 into one line.
2323 Return the number of actual lines read (> 1 if continuation lines).
2324 Returns -1 if there's nothing left in the buffer.
2326 After this function, ebuf->buffer points to the first character of the
2327 line we just found.
2330 /* Read a line of text from a STRING.
2331 Since we aren't really reading from a file, don't bother with linenumbers.
2334 static unsigned long
2335 readstring (struct ebuffer *ebuf)
2337 char *eol;
2339 /* If there is nothing left in this buffer, return 0. */
2340 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2341 return -1;
2343 /* Set up a new starting point for the buffer, and find the end of the
2344 next logical line (taking into account backslash/newline pairs). */
2346 eol = ebuf->buffer = ebuf->bufnext;
2348 while (1)
2350 int backslash = 0;
2351 const char *bol = eol;
2352 const char *p;
2354 /* Find the next newline. At EOS, stop. */
2355 p = eol = strchr (eol , '\n');
2356 if (!eol)
2358 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2359 return 0;
2362 /* Found a newline; if it's escaped continue; else we're done. */
2363 while (p > bol && *(--p) == '\\')
2364 backslash = !backslash;
2365 if (!backslash)
2366 break;
2367 ++eol;
2370 /* Overwrite the newline char. */
2371 *eol = '\0';
2372 ebuf->bufnext = eol+1;
2374 return 0;
2377 static long
2378 readline (struct ebuffer *ebuf)
2380 char *p;
2381 char *end;
2382 char *start;
2383 long nlines = 0;
2385 /* The behaviors between string and stream buffers are different enough to
2386 warrant different functions. Do the Right Thing. */
2388 if (!ebuf->fp)
2389 return readstring (ebuf);
2391 /* When reading from a file, we always start over at the beginning of the
2392 buffer for each new line. */
2394 p = start = ebuf->bufstart;
2395 end = p + ebuf->size;
2396 *p = '\0';
2398 while (fgets (p, end - p, ebuf->fp) != 0)
2400 char *p2;
2401 unsigned long len;
2402 int backslash;
2404 len = strlen (p);
2405 if (len == 0)
2407 /* This only happens when the first thing on the line is a '\0'.
2408 It is a pretty hopeless case, but (wonder of wonders) Athena
2409 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2410 There is nothing really to be done; we synthesize a newline so
2411 the following line doesn't appear to be part of this line. */
2412 error (&ebuf->floc,
2413 _("warning: NUL character seen; rest of line ignored"));
2414 p[0] = '\n';
2415 len = 1;
2418 /* Jump past the text we just read. */
2419 p += len;
2421 /* If the last char isn't a newline, the whole line didn't fit into the
2422 buffer. Get some more buffer and try again. */
2423 if (p[-1] != '\n')
2424 goto more_buffer;
2426 /* We got a newline, so add one to the count of lines. */
2427 ++nlines;
2429 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2430 /* Check to see if the line was really ended with CRLF; if so ignore
2431 the CR. */
2432 if ((p - start) > 1 && p[-2] == '\r')
2434 --p;
2435 p[-1] = '\n';
2437 #endif
2439 backslash = 0;
2440 for (p2 = p - 2; p2 >= start; --p2)
2442 if (*p2 != '\\')
2443 break;
2444 backslash = !backslash;
2447 if (!backslash)
2449 p[-1] = '\0';
2450 break;
2453 /* It was a backslash/newline combo. If we have more space, read
2454 another line. */
2455 if (end - p >= 80)
2456 continue;
2458 /* We need more space at the end of our buffer, so realloc it.
2459 Make sure to preserve the current offset of p. */
2460 more_buffer:
2462 unsigned long off = p - start;
2463 ebuf->size *= 2;
2464 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2465 p = start + off;
2466 end = start + ebuf->size;
2467 *p = '\0';
2471 if (ferror (ebuf->fp))
2472 pfatal_with_name (ebuf->floc.filenm);
2474 /* If we found some lines, return how many.
2475 If we didn't, but we did find _something_, that indicates we read the last
2476 line of a file with no final newline; return 1.
2477 If we read nothing, we're at EOF; return -1. */
2479 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2482 /* Parse the next "makefile word" from the input buffer, and return info
2483 about it.
2485 A "makefile word" is one of:
2487 w_bogus Should never happen
2488 w_eol End of input
2489 w_static A static word; cannot be expanded
2490 w_variable A word containing one or more variables/functions
2491 w_colon A colon
2492 w_dcolon A double-colon
2493 w_semicolon A semicolon
2494 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2496 Note that this function is only used when reading certain parts of the
2497 makefile. Don't use it where special rules hold sway (RHS of a variable,
2498 in a command list, etc.) */
2500 static enum make_word_type
2501 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2503 enum make_word_type wtype = w_bogus;
2504 char *p = buffer, *beg;
2505 char c;
2507 /* Skip any leading whitespace. */
2508 while (isblank ((unsigned char)*p))
2509 ++p;
2511 beg = p;
2512 c = *(p++);
2513 switch (c)
2515 case '\0':
2516 wtype = w_eol;
2517 break;
2519 case ';':
2520 wtype = w_semicolon;
2521 break;
2523 case '=':
2524 wtype = w_varassign;
2525 break;
2527 case ':':
2528 wtype = w_colon;
2529 switch (*p)
2531 case ':':
2532 ++p;
2533 wtype = w_dcolon;
2534 break;
2536 case '=':
2537 ++p;
2538 wtype = w_varassign;
2539 break;
2541 break;
2543 case '+':
2544 case '?':
2545 if (*p == '=')
2547 ++p;
2548 wtype = w_varassign;
2549 break;
2552 default:
2553 if (delim && strchr (delim, c))
2554 wtype = w_static;
2555 break;
2558 /* Did we find something? If so, return now. */
2559 if (wtype != w_bogus)
2560 goto done;
2562 /* This is some non-operator word. A word consists of the longest
2563 string of characters that doesn't contain whitespace, one of [:=#],
2564 or [?+]=, or one of the chars in the DELIM string. */
2566 /* We start out assuming a static word; if we see a variable we'll
2567 adjust our assumptions then. */
2568 wtype = w_static;
2570 /* We already found the first value of "c", above. */
2571 while (1)
2573 char closeparen;
2574 int count;
2576 switch (c)
2578 case '\0':
2579 case ' ':
2580 case '\t':
2581 case '=':
2582 goto done_word;
2584 case ':':
2585 #ifdef HAVE_DOS_PATHS
2586 /* A word CAN include a colon in its drive spec. The drive
2587 spec is allowed either at the beginning of a word, or as part
2588 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2589 if (!(p - beg >= 2
2590 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2591 && (p - beg == 2 || p[-3] == '(')))
2592 #endif
2593 goto done_word;
2595 case '$':
2596 c = *(p++);
2597 if (c == '$')
2598 break;
2600 /* This is a variable reference, so note that it's expandable.
2601 Then read it to the matching close paren. */
2602 wtype = w_variable;
2604 if (c == '(')
2605 closeparen = ')';
2606 else if (c == '{')
2607 closeparen = '}';
2608 else
2609 /* This is a single-letter variable reference. */
2610 break;
2612 for (count=0; *p != '\0'; ++p)
2614 if (*p == c)
2615 ++count;
2616 else if (*p == closeparen && --count < 0)
2618 ++p;
2619 break;
2622 break;
2624 case '?':
2625 case '+':
2626 if (*p == '=')
2627 goto done_word;
2628 break;
2630 case '\\':
2631 switch (*p)
2633 case ':':
2634 case ';':
2635 case '=':
2636 case '\\':
2637 ++p;
2638 break;
2640 break;
2642 default:
2643 if (delim && strchr (delim, c))
2644 goto done_word;
2645 break;
2648 c = *(p++);
2650 done_word:
2651 --p;
2653 done:
2654 if (startp)
2655 *startp = beg;
2656 if (length)
2657 *length = p - beg;
2658 return wtype;
2661 /* Construct the list of include directories
2662 from the arguments and the default list. */
2664 void
2665 construct_include_path (const char **arg_dirs)
2667 #ifdef VAXC /* just don't ask ... */
2668 stat_t stbuf;
2669 #else
2670 struct stat stbuf;
2671 #endif
2672 const char **dirs;
2673 const char **cpp;
2674 unsigned int idx;
2676 /* Compute the number of pointers we need in the table. */
2677 idx = sizeof (default_include_directories) / sizeof (const char *);
2678 if (arg_dirs)
2679 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2680 ++idx;
2682 #ifdef __MSDOS__
2683 /* Add one for $DJDIR. */
2684 ++idx;
2685 #endif
2687 dirs = xmalloc (idx * sizeof (const char *));
2689 idx = 0;
2690 max_incl_len = 0;
2692 /* First consider any dirs specified with -I switches.
2693 Ignore any that don't exist. Remember the maximum string length. */
2695 if (arg_dirs)
2696 while (*arg_dirs != 0)
2698 const char *dir = *(arg_dirs++);
2699 char *expanded = 0;
2700 int e;
2702 if (dir[0] == '~')
2704 expanded = tilde_expand (dir);
2705 if (expanded != 0)
2706 dir = expanded;
2709 EINTRLOOP (e, stat (dir, &stbuf));
2710 if (e == 0 && S_ISDIR (stbuf.st_mode))
2712 unsigned int len = strlen (dir);
2713 /* If dir name is written with trailing slashes, discard them. */
2714 while (len > 1 && dir[len - 1] == '/')
2715 --len;
2716 if (len > max_incl_len)
2717 max_incl_len = len;
2718 dirs[idx++] = strcache_add_len (dir, len);
2721 if (expanded)
2722 free (expanded);
2725 /* Now add the standard default dirs at the end. */
2727 #ifdef __MSDOS__
2729 /* The environment variable $DJDIR holds the root of the DJGPP directory
2730 tree; add ${DJDIR}/include. */
2731 struct variable *djdir = lookup_variable ("DJDIR", 5);
2733 if (djdir)
2735 unsigned int len = strlen (djdir->value) + 8;
2736 char *defdir = alloca (len + 1);
2738 strcat (strcpy (defdir, djdir->value), "/include");
2739 dirs[idx++] = strcache_add (defdir);
2741 if (len > max_incl_len)
2742 max_incl_len = len;
2745 #endif
2747 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2749 int e;
2751 EINTRLOOP (e, stat (*cpp, &stbuf));
2752 if (e == 0 && S_ISDIR (stbuf.st_mode))
2754 unsigned int len = strlen (*cpp);
2755 /* If dir name is written with trailing slashes, discard them. */
2756 while (len > 1 && (*cpp)[len - 1] == '/')
2757 --len;
2758 if (len > max_incl_len)
2759 max_incl_len = len;
2760 dirs[idx++] = strcache_add_len (*cpp, len);
2764 dirs[idx] = 0;
2766 /* Now add each dir to the .INCLUDE_DIRS variable. */
2768 for (cpp = dirs; *cpp != 0; ++cpp)
2769 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2770 o_default, f_append, 0);
2772 include_directories = dirs;
2775 /* Expand ~ or ~USER at the beginning of NAME.
2776 Return a newly malloc'd string or 0. */
2778 char *
2779 tilde_expand (const char *name)
2781 #ifndef VMS
2782 if (name[1] == '/' || name[1] == '\0')
2784 extern char *getenv ();
2785 char *home_dir;
2786 int is_variable;
2789 /* Turn off --warn-undefined-variables while we expand HOME. */
2790 int save = warn_undefined_variables_flag;
2791 warn_undefined_variables_flag = 0;
2793 home_dir = allocated_variable_expand ("$(HOME)");
2795 warn_undefined_variables_flag = save;
2798 is_variable = home_dir[0] != '\0';
2799 if (!is_variable)
2801 free (home_dir);
2802 home_dir = getenv ("HOME");
2804 # if !defined(_AMIGA) && !defined(WINDOWS32)
2805 if (home_dir == 0 || home_dir[0] == '\0')
2807 extern char *getlogin ();
2808 char *logname = getlogin ();
2809 home_dir = 0;
2810 if (logname != 0)
2812 struct passwd *p = getpwnam (logname);
2813 if (p != 0)
2814 home_dir = p->pw_dir;
2817 # endif /* !AMIGA && !WINDOWS32 */
2818 if (home_dir != 0)
2820 char *new = xstrdup (concat (2, home_dir, name + 1));
2821 if (is_variable)
2822 free (home_dir);
2823 return new;
2826 # if !defined(_AMIGA) && !defined(WINDOWS32)
2827 else
2829 struct passwd *pwent;
2830 char *userend = strchr (name + 1, '/');
2831 if (userend != 0)
2832 *userend = '\0';
2833 pwent = getpwnam (name + 1);
2834 if (pwent != 0)
2836 if (userend == 0)
2837 return xstrdup (pwent->pw_dir);
2838 else
2839 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2841 else if (userend != 0)
2842 *userend = '/';
2844 # endif /* !AMIGA && !WINDOWS32 */
2845 #endif /* !VMS */
2846 return 0;
2849 /* Parse a string into a sequence of filenames represented as a chain of
2850 struct nameseq's and return that chain. Optionally expand the strings via
2851 glob().
2853 The string is passed as STRINGP, the address of a string pointer.
2854 The string pointer is updated to point at the first character
2855 not parsed, which either is a null char or equals STOPCHAR.
2857 SIZE is how big to construct chain elements.
2858 This is useful if we want them actually to be other structures
2859 that have room for additional info.
2861 PREFIX, if non-null, is added to the beginning of each filename.
2863 FLAGS allows one or more of the following bitflags to be set:
2864 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2865 PARSEFS_NOGLOB - Do not expand globbing characters
2866 PARSEFS_EXISTS - Only return globbed files that actually exist
2867 (cannot also set NOGLOB)
2868 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2871 void *
2872 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2873 const char *prefix, int flags)
2875 extern void dir_setup_glob (glob_t *glob);
2877 /* tmp points to tmpbuf after the prefix, if any.
2878 tp is the end of the buffer. */
2879 static char *tmpbuf = NULL;
2880 static int tmpbuf_len = 0;
2882 int cachep = (! (flags & PARSEFS_NOCACHE));
2884 struct nameseq *new = 0;
2885 struct nameseq **newp = &new;
2886 #define NEWELT(_n) do { \
2887 const char *__n = (_n); \
2888 *newp = xcalloc (size); \
2889 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2890 newp = &(*newp)->next; \
2891 } while(0)
2893 char *p;
2894 glob_t gl;
2895 char *tp;
2897 #ifdef VMS
2898 # define VMS_COMMA ','
2899 #else
2900 # define VMS_COMMA 0
2901 #endif
2903 if (size < sizeof (struct nameseq))
2904 size = sizeof (struct nameseq);
2906 if (! (flags & PARSEFS_NOGLOB))
2907 dir_setup_glob (&gl);
2909 /* Get enough temporary space to construct the largest possible target. */
2911 int l = strlen (*stringp) + 1;
2912 if (l > tmpbuf_len)
2914 tmpbuf = xrealloc (tmpbuf, l);
2915 tmpbuf_len = l;
2918 tp = tmpbuf;
2920 /* Parse STRING. P will always point to the end of the parsed content. */
2921 p = *stringp;
2922 while (1)
2924 const char *name;
2925 const char **nlist = 0;
2926 char *tildep = 0;
2927 #ifndef NO_ARCHIVES
2928 char *arname = 0;
2929 char *memname = 0;
2930 #endif
2931 char *s;
2932 int nlen;
2933 int i;
2935 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2936 p = next_token (p);
2937 if (*p == '\0' || *p == stopchar)
2938 break;
2940 /* There are names left, so find the end of the next name.
2941 Throughout this iteration S points to the start. */
2942 s = p;
2943 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2944 #ifdef VMS
2945 /* convert comma separated list to space separated */
2946 if (p && *p == ',')
2947 *p =' ';
2948 #endif
2949 #ifdef _AMIGA
2950 if (stopchar == ':' && p && *p == ':'
2951 && !(isspace ((unsigned char)p[1]) || !p[1]
2952 || isspace ((unsigned char)p[-1])))
2953 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2954 #endif
2955 #ifdef HAVE_DOS_PATHS
2956 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2957 first colon which isn't followed by a slash or a backslash.
2958 Note that tokens separated by spaces should be treated as separate
2959 tokens since make doesn't allow path names with spaces */
2960 if (stopchar == ':')
2961 while (p != 0 && !isspace ((unsigned char)*p) &&
2962 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2963 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2964 #endif
2965 if (p == 0)
2966 p = s + strlen (s);
2968 /* Strip leading "this directory" references. */
2969 if (! (flags & PARSEFS_NOSTRIP))
2970 #ifdef VMS
2971 /* Skip leading `[]'s. */
2972 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2973 #else
2974 /* Skip leading `./'s. */
2975 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2976 #endif
2978 /* Skip "./" and all following slashes. */
2979 s += 2;
2980 while (*s == '/')
2981 ++s;
2984 /* Extract the filename just found, and skip it.
2985 Set NAME to the string, and NLEN to its length. */
2987 if (s == p)
2989 /* The name was stripped to empty ("./"). */
2990 #if defined(VMS)
2991 continue;
2992 #elif defined(_AMIGA)
2993 /* PDS-- This cannot be right!! */
2994 tp[0] = '\0';
2995 nlen = 0;
2996 #else
2997 tp[0] = '.';
2998 tp[1] = '/';
2999 tp[2] = '\0';
3000 nlen = 2;
3001 #endif
3003 else
3005 #ifdef VMS
3006 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
3007 * to remove this '\' before we can use the filename.
3008 * xstrdup called because S may be read-only string constant.
3010 char *n = tp;
3011 while (s < p)
3013 if (s[0] == '\\' && s[1] == ':')
3014 ++s;
3015 *(n++) = *(s++);
3017 n[0] = '\0';
3018 nlen = strlen (tp);
3019 #else
3020 nlen = p - s;
3021 memcpy (tp, s, nlen);
3022 tp[nlen] = '\0';
3023 #endif
3026 /* At this point, TP points to the element and NLEN is its length. */
3028 #ifndef NO_ARCHIVES
3029 /* If this is the start of an archive group that isn't complete, set up
3030 to add the archive prefix for future files.
3032 TP == TMP means we're not already in an archive group. Ignore
3033 something starting with `(', as that cannot actually be an
3034 archive-member reference (and treating it as such results in an empty
3035 file name, which causes much lossage). Also if it ends in ")" then
3036 it's a complete reference so we don't need to treat it specially. */
3038 if (tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3040 char *n = strchr (tp, '(');
3041 if (n)
3043 /* This is the first element in an open archive group. It looks
3044 like "lib(mem". Remember the close paren. */
3045 nlen -= (n + 1) - tp;
3046 tp = n + 1;
3048 /* If we have just "lib(", part of something like "lib( a b)",
3049 go to the next item. */
3050 if (! nlen)
3051 continue;
3055 /* If we are inside an archive group, make sure it has an end. */
3056 if (tp > tmpbuf)
3058 if (tp[nlen-1] == ')')
3060 /* This is the natural end; reset TP. */
3061 tp = tmpbuf;
3063 /* This is just ")", something like "lib(a b )": skip it. */
3064 if (nlen == 1)
3065 continue;
3067 else
3069 /* Not the end, so add a "fake" end. */
3070 tp[nlen++] = ')';
3071 tp[nlen] = '\0';
3074 #endif
3076 /* If we're not globbing we're done: add it to the end of the chain.
3077 Go to the next item in the string. */
3078 if (flags & PARSEFS_NOGLOB)
3080 NEWELT (concat (2, prefix, tp));
3081 continue;
3084 /* If we get here we know we're doing glob expansion.
3085 TP is a string in tmpbuf. NLEN is no longer used.
3086 We may need to do more work: after this NAME will be set. */
3087 name = tp;
3089 /* Expand tilde if applicable. */
3090 if (tp[0] == '~')
3092 tildep = tilde_expand (tp);
3093 if (tildep != 0)
3094 name = tildep;
3097 #ifndef NO_ARCHIVES
3098 /* If NAME is an archive member reference replace it with the archive
3099 file name, and save the member name in MEMNAME. We will glob on the
3100 archive name and then reattach MEMNAME later. */
3101 if (ar_name (name))
3103 ar_parse_name (name, &arname, &memname);
3104 name = arname;
3106 #endif /* !NO_ARCHIVES */
3108 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3110 case GLOB_NOSPACE:
3111 fatal (NILF, _("virtual memory exhausted"));
3113 case 0:
3114 /* Success. */
3115 i = gl.gl_pathc;
3116 nlist = (const char **)gl.gl_pathv;
3117 break;
3119 case GLOB_NOMATCH:
3120 /* If we want only existing items, skip this one. */
3121 if (flags & PARSEFS_EXISTS)
3123 i = 0;
3124 break;
3126 /* FALLTHROUGH */
3128 default:
3129 /* By default keep this name. */
3130 i = 1;
3131 nlist = &name;
3132 break;
3135 /* For each matched element, add it to the list. */
3136 while (i-- > 0)
3137 #ifndef NO_ARCHIVES
3138 if (memname != 0)
3140 /* Try to glob on MEMNAME within the archive. */
3141 struct nameseq *found = ar_glob (nlist[i], memname, size);
3142 if (! found)
3143 /* No matches. Use MEMNAME as-is. */
3144 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3145 else
3147 /* We got a chain of items. Attach them. */
3148 (*newp)->next = found;
3150 /* Find and set the new end. Massage names if necessary. */
3151 while (1)
3153 if (! cachep)
3154 found->name = xstrdup (concat (2, prefix, name));
3155 else if (prefix)
3156 found->name = strcache_add (concat (2, prefix, name));
3158 if (found->next == 0)
3159 break;
3161 found = found->next;
3163 newp = &found->next;
3166 else
3167 #endif /* !NO_ARCHIVES */
3168 NEWELT (concat (2, prefix, nlist[i]));
3170 globfree (&gl);
3172 #ifndef NO_ARCHIVES
3173 if (arname)
3174 free (arname);
3175 #endif
3177 if (tildep)
3178 free (tildep);
3181 *stringp = p;
3182 return new;