- Fix broken handling of order-only prereqs in secondary expansion
[make.git] / read.c
blob87bb046a0235c68f65dd8374cb11042ac27300d5
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->file->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); \
570 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 (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|PARSEFS_NOCACHE);
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 (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 (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 /* Create an array of target names */
1939 for (c = 1, nextf = filenames->next; nextf; ++c, nextf = nextf->next)
1941 targets = xmalloc (c * sizeof (const char *));
1942 target_pats = xmalloc (c * sizeof (const char *));
1944 targets[0] = name;
1945 target_pats[0] = implicit_percent;
1947 for (c = 1, nextf = filenames->next; nextf; ++c, nextf = nextf->next)
1949 name = nextf->name;
1950 implicit_percent = find_percent_cached (&name);
1952 if (implicit_percent == 0)
1953 fatal (flocp, _("mixed implicit and normal rules"));
1955 targets[c] = name;
1956 target_pats[c] = implicit_percent;
1959 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1961 return;
1965 /* Walk through each target and create it in the database.
1966 We already set up the first target, above. */
1967 while (1)
1969 struct nameseq *nextf = filenames->next;
1970 struct file *f;
1971 struct dep *this = 0;
1973 free (filenames);
1975 /* Check for special targets. Do it here instead of, say, snap_deps()
1976 so that we can immediately use the value. */
1977 if (streq (name, ".POSIX"))
1978 posix_pedantic = 1;
1979 else if (streq (name, ".SECONDEXPANSION"))
1980 second_expansion = 1;
1982 /* If this is a static pattern rule:
1983 `targets: target%pattern: prereq%pattern; recipe',
1984 make sure the pattern matches this target name. */
1985 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1986 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1987 else if (deps)
1988 /* If there are multiple targets, copy the chain DEPS for all but the
1989 last one. It is not safe for the same deps to go in more than one
1990 place in the database. */
1991 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1993 /* Find or create an entry in the file database for this target. */
1994 if (!two_colon)
1996 /* Single-colon. Combine this rule with the file's existing record,
1997 if any. */
1998 f = enter_file (strcache_add (name));
1999 if (f->double_colon)
2000 fatal (flocp,
2001 _("target file `%s' has both : and :: entries"), f->name);
2003 /* If CMDS == F->CMDS, this target was listed in this rule
2004 more than once. Just give a warning since this is harmless. */
2005 if (cmds != 0 && cmds == f->cmds)
2006 error (flocp,
2007 _("target `%s' given more than once in the same rule."),
2008 f->name);
2010 /* Check for two single-colon entries both with commands.
2011 Check is_target so that we don't lose on files such as .c.o
2012 whose commands were preinitialized. */
2013 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2015 error (&cmds->fileinfo,
2016 _("warning: overriding recipe for target `%s'"),
2017 f->name);
2018 error (&f->cmds->fileinfo,
2019 _("warning: ignoring old recipe for target `%s'"),
2020 f->name);
2023 /* Defining .DEFAULT with no deps or cmds clears it. */
2024 if (f == default_file && this == 0 && cmds == 0)
2025 f->cmds = 0;
2026 if (cmds != 0)
2027 f->cmds = cmds;
2029 /* Defining .SUFFIXES with no dependencies clears out the list of
2030 suffixes. */
2031 if (f == suffix_file && this == 0)
2033 free_dep_chain (f->deps);
2034 f->deps = 0;
2037 else
2039 /* Double-colon. Make a new record even if there already is one. */
2040 f = lookup_file (name);
2042 /* Check for both : and :: rules. Check is_target so we don't lose
2043 on default suffix rules or makefiles. */
2044 if (f != 0 && f->is_target && !f->double_colon)
2045 fatal (flocp,
2046 _("target file `%s' has both : and :: entries"), f->name);
2048 f = enter_file (strcache_add (name));
2049 /* If there was an existing entry and it was a double-colon entry,
2050 enter_file will have returned a new one, making it the prev
2051 pointer of the old one, and setting its double_colon pointer to
2052 the first one. */
2053 if (f->double_colon == 0)
2054 /* This is the first entry for this name, so we must set its
2055 double_colon pointer to itself. */
2056 f->double_colon = f;
2058 f->cmds = cmds;
2061 f->is_target = 1;
2063 /* If this is a static pattern rule, set the stem to the part of its
2064 name that matched the `%' in the pattern, so you can use $* in the
2065 commands. If we didn't do it before, enter the prereqs now. */
2066 if (pattern)
2068 static const char *percent = "%";
2069 char *buffer = variable_expand ("");
2070 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2071 pattern_percent+1, percent+1);
2072 f->stem = strcache_add_len (buffer, o - buffer);
2073 if (this)
2075 if (! this->need_2nd_expansion)
2076 this = enter_prereqs (this, f->stem);
2077 else
2078 this->stem = f->stem;
2082 /* Add the dependencies to this file entry. */
2083 if (this != 0)
2085 /* Add the file's old deps and the new ones in THIS together. */
2086 if (f->deps == 0)
2087 f->deps = this;
2088 else if (cmds != 0)
2090 struct dep *d = this;
2092 /* If this rule has commands, put these deps first. */
2093 while (d->next != 0)
2094 d = d->next;
2096 d->next = f->deps;
2097 f->deps = this;
2099 else
2101 struct dep *d = f->deps;
2103 /* A rule without commands: put its prereqs at the end. */
2104 while (d->next != 0)
2105 d = d->next;
2107 d->next = this;
2111 name = f->name;
2113 /* All done! Set up for the next one. */
2114 if (nextf == 0)
2115 break;
2117 filenames = nextf;
2119 /* Reduce escaped percents. If there are any unescaped it's an error */
2120 name = filenames->name;
2121 if (find_percent_cached (&name))
2122 fatal (flocp, _("mixed implicit and normal rules"));
2126 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2127 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2128 Quoting backslashes are removed from STRING by compacting it into
2129 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2130 one, or nil if there are none. STOPCHARs inside variable references are
2131 ignored if IGNOREVARS is true.
2133 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2135 static char *
2136 find_char_unquote (char *string, int stop1, int stop2, int blank,
2137 int ignorevars)
2139 unsigned int string_len = 0;
2140 char *p = string;
2142 if (ignorevars)
2143 ignorevars = '$';
2145 while (1)
2147 if (stop2 && blank)
2148 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2149 && ! isblank ((unsigned char) *p))
2150 ++p;
2151 else if (stop2)
2152 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2153 ++p;
2154 else if (blank)
2155 while (*p != '\0' && *p != ignorevars && *p != stop1
2156 && ! isblank ((unsigned char) *p))
2157 ++p;
2158 else
2159 while (*p != '\0' && *p != ignorevars && *p != stop1)
2160 ++p;
2162 if (*p == '\0')
2163 break;
2165 /* If we stopped due to a variable reference, skip over its contents. */
2166 if (*p == ignorevars)
2168 char openparen = p[1];
2170 p += 2;
2172 /* Skip the contents of a non-quoted, multi-char variable ref. */
2173 if (openparen == '(' || openparen == '{')
2175 unsigned int pcount = 1;
2176 char closeparen = (openparen == '(' ? ')' : '}');
2178 while (*p)
2180 if (*p == openparen)
2181 ++pcount;
2182 else if (*p == closeparen)
2183 if (--pcount == 0)
2185 ++p;
2186 break;
2188 ++p;
2192 /* Skipped the variable reference: look for STOPCHARS again. */
2193 continue;
2196 if (p > string && p[-1] == '\\')
2198 /* Search for more backslashes. */
2199 int i = -2;
2200 while (&p[i] >= string && p[i] == '\\')
2201 --i;
2202 ++i;
2203 /* Only compute the length if really needed. */
2204 if (string_len == 0)
2205 string_len = strlen (string);
2206 /* The number of backslashes is now -I.
2207 Copy P over itself to swallow half of them. */
2208 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2209 p += i/2;
2210 if (i % 2 == 0)
2211 /* All the backslashes quoted each other; the STOPCHAR was
2212 unquoted. */
2213 return p;
2215 /* The STOPCHAR was quoted by a backslash. Look for another. */
2217 else
2218 /* No backslash in sight. */
2219 return p;
2222 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2223 return 0;
2226 /* Search PATTERN for an unquoted % and handle quoting. */
2228 char *
2229 find_percent (char *pattern)
2231 return find_char_unquote (pattern, '%', 0, 0, 0);
2234 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2235 the % or NULL if no % was found.
2236 This version is used with strings in the string cache: if there's a need to
2237 modify the string a new version will be added to the string cache and
2238 *STRING will be set to that. */
2240 const char *
2241 find_percent_cached (const char **string)
2243 const char *p = *string;
2244 char *new = 0;
2245 int slen = 0;
2247 /* If the first char is a % return now. This lets us avoid extra tests
2248 inside the loop. */
2249 if (*p == '%')
2250 return p;
2252 while (1)
2254 while (*p != '\0' && *p != '%')
2255 ++p;
2257 if (*p == '\0')
2258 break;
2260 /* See if this % is escaped with a backslash; if not we're done. */
2261 if (p[-1] != '\\')
2262 break;
2265 /* Search for more backslashes. */
2266 char *pv;
2267 int i = -2;
2269 while (&p[i] >= *string && p[i] == '\\')
2270 --i;
2271 ++i;
2273 /* At this point we know we'll need to allocate a new string.
2274 Make a copy if we haven't yet done so. */
2275 if (! new)
2277 slen = strlen (*string);
2278 new = alloca (slen + 1);
2279 memcpy (new, *string, slen + 1);
2280 p = new + (p - *string);
2281 *string = new;
2284 /* At this point *string, p, and new all point into the same string.
2285 Get a non-const version of p so we can modify new. */
2286 pv = new + (p - *string);
2288 /* The number of backslashes is now -I.
2289 Copy P over itself to swallow half of them. */
2290 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2291 p += i/2;
2293 /* If the backslashes quoted each other; the % was unquoted. */
2294 if (i % 2 == 0)
2295 break;
2299 /* If we had to change STRING, add it to the strcache. */
2300 if (new)
2302 *string = strcache_add (*string);
2303 p = *string + (p - new);
2306 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2307 return (*p == '\0') ? NULL : p;
2310 /* Find the next line of text in an eval buffer, combining continuation lines
2311 into one line.
2312 Return the number of actual lines read (> 1 if continuation lines).
2313 Returns -1 if there's nothing left in the buffer.
2315 After this function, ebuf->buffer points to the first character of the
2316 line we just found.
2319 /* Read a line of text from a STRING.
2320 Since we aren't really reading from a file, don't bother with linenumbers.
2323 static unsigned long
2324 readstring (struct ebuffer *ebuf)
2326 char *eol;
2328 /* If there is nothing left in this buffer, return 0. */
2329 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2330 return -1;
2332 /* Set up a new starting point for the buffer, and find the end of the
2333 next logical line (taking into account backslash/newline pairs). */
2335 eol = ebuf->buffer = ebuf->bufnext;
2337 while (1)
2339 int backslash = 0;
2340 const char *bol = eol;
2341 const char *p;
2343 /* Find the next newline. At EOS, stop. */
2344 p = eol = strchr (eol , '\n');
2345 if (!eol)
2347 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2348 return 0;
2351 /* Found a newline; if it's escaped continue; else we're done. */
2352 while (p > bol && *(--p) == '\\')
2353 backslash = !backslash;
2354 if (!backslash)
2355 break;
2356 ++eol;
2359 /* Overwrite the newline char. */
2360 *eol = '\0';
2361 ebuf->bufnext = eol+1;
2363 return 0;
2366 static long
2367 readline (struct ebuffer *ebuf)
2369 char *p;
2370 char *end;
2371 char *start;
2372 long nlines = 0;
2374 /* The behaviors between string and stream buffers are different enough to
2375 warrant different functions. Do the Right Thing. */
2377 if (!ebuf->fp)
2378 return readstring (ebuf);
2380 /* When reading from a file, we always start over at the beginning of the
2381 buffer for each new line. */
2383 p = start = ebuf->bufstart;
2384 end = p + ebuf->size;
2385 *p = '\0';
2387 while (fgets (p, end - p, ebuf->fp) != 0)
2389 char *p2;
2390 unsigned long len;
2391 int backslash;
2393 len = strlen (p);
2394 if (len == 0)
2396 /* This only happens when the first thing on the line is a '\0'.
2397 It is a pretty hopeless case, but (wonder of wonders) Athena
2398 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2399 There is nothing really to be done; we synthesize a newline so
2400 the following line doesn't appear to be part of this line. */
2401 error (&ebuf->floc,
2402 _("warning: NUL character seen; rest of line ignored"));
2403 p[0] = '\n';
2404 len = 1;
2407 /* Jump past the text we just read. */
2408 p += len;
2410 /* If the last char isn't a newline, the whole line didn't fit into the
2411 buffer. Get some more buffer and try again. */
2412 if (p[-1] != '\n')
2413 goto more_buffer;
2415 /* We got a newline, so add one to the count of lines. */
2416 ++nlines;
2418 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2419 /* Check to see if the line was really ended with CRLF; if so ignore
2420 the CR. */
2421 if ((p - start) > 1 && p[-2] == '\r')
2423 --p;
2424 p[-1] = '\n';
2426 #endif
2428 backslash = 0;
2429 for (p2 = p - 2; p2 >= start; --p2)
2431 if (*p2 != '\\')
2432 break;
2433 backslash = !backslash;
2436 if (!backslash)
2438 p[-1] = '\0';
2439 break;
2442 /* It was a backslash/newline combo. If we have more space, read
2443 another line. */
2444 if (end - p >= 80)
2445 continue;
2447 /* We need more space at the end of our buffer, so realloc it.
2448 Make sure to preserve the current offset of p. */
2449 more_buffer:
2451 unsigned long off = p - start;
2452 ebuf->size *= 2;
2453 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2454 p = start + off;
2455 end = start + ebuf->size;
2456 *p = '\0';
2460 if (ferror (ebuf->fp))
2461 pfatal_with_name (ebuf->floc.filenm);
2463 /* If we found some lines, return how many.
2464 If we didn't, but we did find _something_, that indicates we read the last
2465 line of a file with no final newline; return 1.
2466 If we read nothing, we're at EOF; return -1. */
2468 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2471 /* Parse the next "makefile word" from the input buffer, and return info
2472 about it.
2474 A "makefile word" is one of:
2476 w_bogus Should never happen
2477 w_eol End of input
2478 w_static A static word; cannot be expanded
2479 w_variable A word containing one or more variables/functions
2480 w_colon A colon
2481 w_dcolon A double-colon
2482 w_semicolon A semicolon
2483 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2485 Note that this function is only used when reading certain parts of the
2486 makefile. Don't use it where special rules hold sway (RHS of a variable,
2487 in a command list, etc.) */
2489 static enum make_word_type
2490 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2492 enum make_word_type wtype = w_bogus;
2493 char *p = buffer, *beg;
2494 char c;
2496 /* Skip any leading whitespace. */
2497 while (isblank ((unsigned char)*p))
2498 ++p;
2500 beg = p;
2501 c = *(p++);
2502 switch (c)
2504 case '\0':
2505 wtype = w_eol;
2506 break;
2508 case ';':
2509 wtype = w_semicolon;
2510 break;
2512 case '=':
2513 wtype = w_varassign;
2514 break;
2516 case ':':
2517 wtype = w_colon;
2518 switch (*p)
2520 case ':':
2521 ++p;
2522 wtype = w_dcolon;
2523 break;
2525 case '=':
2526 ++p;
2527 wtype = w_varassign;
2528 break;
2530 break;
2532 case '+':
2533 case '?':
2534 if (*p == '=')
2536 ++p;
2537 wtype = w_varassign;
2538 break;
2541 default:
2542 if (delim && strchr (delim, c))
2543 wtype = w_static;
2544 break;
2547 /* Did we find something? If so, return now. */
2548 if (wtype != w_bogus)
2549 goto done;
2551 /* This is some non-operator word. A word consists of the longest
2552 string of characters that doesn't contain whitespace, one of [:=#],
2553 or [?+]=, or one of the chars in the DELIM string. */
2555 /* We start out assuming a static word; if we see a variable we'll
2556 adjust our assumptions then. */
2557 wtype = w_static;
2559 /* We already found the first value of "c", above. */
2560 while (1)
2562 char closeparen;
2563 int count;
2565 switch (c)
2567 case '\0':
2568 case ' ':
2569 case '\t':
2570 case '=':
2571 goto done_word;
2573 case ':':
2574 #ifdef HAVE_DOS_PATHS
2575 /* A word CAN include a colon in its drive spec. The drive
2576 spec is allowed either at the beginning of a word, or as part
2577 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2578 if (!(p - beg >= 2
2579 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2580 && (p - beg == 2 || p[-3] == '(')))
2581 #endif
2582 goto done_word;
2584 case '$':
2585 c = *(p++);
2586 if (c == '$')
2587 break;
2589 /* This is a variable reference, so note that it's expandable.
2590 Then read it to the matching close paren. */
2591 wtype = w_variable;
2593 if (c == '(')
2594 closeparen = ')';
2595 else if (c == '{')
2596 closeparen = '}';
2597 else
2598 /* This is a single-letter variable reference. */
2599 break;
2601 for (count=0; *p != '\0'; ++p)
2603 if (*p == c)
2604 ++count;
2605 else if (*p == closeparen && --count < 0)
2607 ++p;
2608 break;
2611 break;
2613 case '?':
2614 case '+':
2615 if (*p == '=')
2616 goto done_word;
2617 break;
2619 case '\\':
2620 switch (*p)
2622 case ':':
2623 case ';':
2624 case '=':
2625 case '\\':
2626 ++p;
2627 break;
2629 break;
2631 default:
2632 if (delim && strchr (delim, c))
2633 goto done_word;
2634 break;
2637 c = *(p++);
2639 done_word:
2640 --p;
2642 done:
2643 if (startp)
2644 *startp = beg;
2645 if (length)
2646 *length = p - beg;
2647 return wtype;
2650 /* Construct the list of include directories
2651 from the arguments and the default list. */
2653 void
2654 construct_include_path (const char **arg_dirs)
2656 #ifdef VAXC /* just don't ask ... */
2657 stat_t stbuf;
2658 #else
2659 struct stat stbuf;
2660 #endif
2661 const char **dirs;
2662 const char **cpp;
2663 unsigned int idx;
2665 /* Compute the number of pointers we need in the table. */
2666 idx = sizeof (default_include_directories) / sizeof (const char *);
2667 if (arg_dirs)
2668 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2669 ++idx;
2671 #ifdef __MSDOS__
2672 /* Add one for $DJDIR. */
2673 ++idx;
2674 #endif
2676 dirs = xmalloc (idx * sizeof (const char *));
2678 idx = 0;
2679 max_incl_len = 0;
2681 /* First consider any dirs specified with -I switches.
2682 Ignore any that don't exist. Remember the maximum string length. */
2684 if (arg_dirs)
2685 while (*arg_dirs != 0)
2687 const char *dir = *(arg_dirs++);
2688 char *expanded = 0;
2689 int e;
2691 if (dir[0] == '~')
2693 expanded = tilde_expand (dir);
2694 if (expanded != 0)
2695 dir = expanded;
2698 EINTRLOOP (e, stat (dir, &stbuf));
2699 if (e == 0 && S_ISDIR (stbuf.st_mode))
2701 unsigned int len = strlen (dir);
2702 /* If dir name is written with trailing slashes, discard them. */
2703 while (len > 1 && dir[len - 1] == '/')
2704 --len;
2705 if (len > max_incl_len)
2706 max_incl_len = len;
2707 dirs[idx++] = strcache_add_len (dir, len);
2710 if (expanded)
2711 free (expanded);
2714 /* Now add the standard default dirs at the end. */
2716 #ifdef __MSDOS__
2718 /* The environment variable $DJDIR holds the root of the DJGPP directory
2719 tree; add ${DJDIR}/include. */
2720 struct variable *djdir = lookup_variable ("DJDIR", 5);
2722 if (djdir)
2724 unsigned int len = strlen (djdir->value) + 8;
2725 char *defdir = alloca (len + 1);
2727 strcat (strcpy (defdir, djdir->value), "/include");
2728 dirs[idx++] = strcache_add (defdir);
2730 if (len > max_incl_len)
2731 max_incl_len = len;
2734 #endif
2736 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2738 int e;
2740 EINTRLOOP (e, stat (*cpp, &stbuf));
2741 if (e == 0 && S_ISDIR (stbuf.st_mode))
2743 unsigned int len = strlen (*cpp);
2744 /* If dir name is written with trailing slashes, discard them. */
2745 while (len > 1 && (*cpp)[len - 1] == '/')
2746 --len;
2747 if (len > max_incl_len)
2748 max_incl_len = len;
2749 dirs[idx++] = strcache_add_len (*cpp, len);
2753 dirs[idx] = 0;
2755 /* Now add each dir to the .INCLUDE_DIRS variable. */
2757 for (cpp = dirs; *cpp != 0; ++cpp)
2758 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2759 o_default, f_append, 0);
2761 include_directories = dirs;
2764 /* Expand ~ or ~USER at the beginning of NAME.
2765 Return a newly malloc'd string or 0. */
2767 char *
2768 tilde_expand (const char *name)
2770 #ifndef VMS
2771 if (name[1] == '/' || name[1] == '\0')
2773 extern char *getenv ();
2774 char *home_dir;
2775 int is_variable;
2778 /* Turn off --warn-undefined-variables while we expand HOME. */
2779 int save = warn_undefined_variables_flag;
2780 warn_undefined_variables_flag = 0;
2782 home_dir = allocated_variable_expand ("$(HOME)");
2784 warn_undefined_variables_flag = save;
2787 is_variable = home_dir[0] != '\0';
2788 if (!is_variable)
2790 free (home_dir);
2791 home_dir = getenv ("HOME");
2793 # if !defined(_AMIGA) && !defined(WINDOWS32)
2794 if (home_dir == 0 || home_dir[0] == '\0')
2796 extern char *getlogin ();
2797 char *logname = getlogin ();
2798 home_dir = 0;
2799 if (logname != 0)
2801 struct passwd *p = getpwnam (logname);
2802 if (p != 0)
2803 home_dir = p->pw_dir;
2806 # endif /* !AMIGA && !WINDOWS32 */
2807 if (home_dir != 0)
2809 char *new = xstrdup (concat (2, home_dir, name + 1));
2810 if (is_variable)
2811 free (home_dir);
2812 return new;
2815 # if !defined(_AMIGA) && !defined(WINDOWS32)
2816 else
2818 struct passwd *pwent;
2819 char *userend = strchr (name + 1, '/');
2820 if (userend != 0)
2821 *userend = '\0';
2822 pwent = getpwnam (name + 1);
2823 if (pwent != 0)
2825 if (userend == 0)
2826 return xstrdup (pwent->pw_dir);
2827 else
2828 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2830 else if (userend != 0)
2831 *userend = '/';
2833 # endif /* !AMIGA && !WINDOWS32 */
2834 #endif /* !VMS */
2835 return 0;
2838 /* Parse a string into a sequence of filenames represented as a chain of
2839 struct nameseq's and return that chain. Optionally expand the strings via
2840 glob().
2842 The string is passed as STRINGP, the address of a string pointer.
2843 The string pointer is updated to point at the first character
2844 not parsed, which either is a null char or equals STOPCHAR.
2846 SIZE is how big to construct chain elements.
2847 This is useful if we want them actually to be other structures
2848 that have room for additional info.
2850 PREFIX, if non-null, is added to the beginning of each filename.
2852 FLAGS allows one or more of the following bitflags to be set:
2853 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2854 PARSEFS_NOGLOB - Do not expand globbing characters
2855 PARSEFS_EXISTS - Only return globbed files that actually exist
2856 (cannot also set NOGLOB)
2857 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2860 void *
2861 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2862 const char *prefix, int flags)
2864 extern void dir_setup_glob (glob_t *glob);
2866 /* tmp points to tmpbuf after the prefix, if any.
2867 tp is the end of the buffer. */
2868 static char *tmpbuf = NULL;
2869 static int tmpbuf_len = 0;
2871 int cachep = (! (flags & PARSEFS_NOCACHE));
2873 struct nameseq *new = 0;
2874 struct nameseq **newp = &new;
2875 #define NEWELT(_n) do { \
2876 const char *__n = (_n); \
2877 *newp = xcalloc (size); \
2878 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2879 newp = &(*newp)->next; \
2880 } while(0)
2882 char *p;
2883 glob_t gl;
2884 char *tp;
2886 #ifdef VMS
2887 # define VMS_COMMA ','
2888 #else
2889 # define VMS_COMMA 0
2890 #endif
2892 if (size < sizeof (struct nameseq))
2893 size = sizeof (struct nameseq);
2895 if (! (flags & PARSEFS_NOGLOB))
2896 dir_setup_glob (&gl);
2898 /* Get enough temporary space to construct the largest possible target. */
2900 int l = strlen (*stringp) + 1;
2901 if (l > tmpbuf_len)
2903 tmpbuf = xrealloc (tmpbuf, l);
2904 tmpbuf_len = l;
2907 tp = tmpbuf;
2909 /* Parse STRING. P will always point to the end of the parsed content. */
2910 p = *stringp;
2911 while (1)
2913 const char *name;
2914 const char **nlist = 0;
2915 char *tildep = 0;
2916 #ifndef NO_ARCHIVES
2917 char *arname = 0;
2918 char *memname = 0;
2919 #endif
2920 char *s;
2921 int nlen;
2922 int i;
2924 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2925 p = next_token (p);
2926 if (*p == '\0' || *p == stopchar)
2927 break;
2929 /* There are names left, so find the end of the next name.
2930 Throughout this iteration S points to the start. */
2931 s = p;
2932 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2933 #ifdef VMS
2934 /* convert comma separated list to space separated */
2935 if (p && *p == ',')
2936 *p =' ';
2937 #endif
2938 #ifdef _AMIGA
2939 if (stopchar == ':' && p && *p == ':'
2940 && !(isspace ((unsigned char)p[1]) || !p[1]
2941 || isspace ((unsigned char)p[-1])))
2942 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2943 #endif
2944 #ifdef HAVE_DOS_PATHS
2945 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2946 first colon which isn't followed by a slash or a backslash.
2947 Note that tokens separated by spaces should be treated as separate
2948 tokens since make doesn't allow path names with spaces */
2949 if (stopchar == ':')
2950 while (p != 0 && !isspace ((unsigned char)*p) &&
2951 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2952 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2953 #endif
2954 if (p == 0)
2955 p = s + strlen (s);
2957 /* Strip leading "this directory" references. */
2958 if (! (flags & PARSEFS_NOSTRIP))
2959 #ifdef VMS
2960 /* Skip leading `[]'s. */
2961 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2962 #else
2963 /* Skip leading `./'s. */
2964 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2965 #endif
2967 /* Skip "./" and all following slashes. */
2968 s += 2;
2969 while (*s == '/')
2970 ++s;
2973 /* Extract the filename just found, and skip it.
2974 Set NAME to the string, and NLEN to its length. */
2976 if (s == p)
2978 /* The name was stripped to empty ("./"). */
2979 #if defined(VMS)
2980 continue;
2981 #elif defined(_AMIGA)
2982 /* PDS-- This cannot be right!! */
2983 tp[0] = '\0';
2984 nlen = 0;
2985 #else
2986 tp[0] = '.';
2987 tp[1] = '/';
2988 tp[2] = '\0';
2989 nlen = 2;
2990 #endif
2992 else
2994 #ifdef VMS
2995 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2996 * to remove this '\' before we can use the filename.
2997 * xstrdup called because S may be read-only string constant.
2999 char *n = tp;
3000 while (s < p)
3002 if (s[0] == '\\' && s[1] == ':')
3003 ++s;
3004 *(n++) = *(s++);
3006 n[0] = '\0';
3007 nlen = strlen (tp);
3008 #else
3009 nlen = p - s;
3010 memcpy (tp, s, nlen);
3011 tp[nlen] = '\0';
3012 #endif
3015 /* At this point, TP points to the element and NLEN is its length. */
3017 #ifndef NO_ARCHIVES
3018 /* If this is the start of an archive group that isn't complete, set up
3019 to add the archive prefix for future files.
3021 TP == TMP means we're not already in an archive group. Ignore
3022 something starting with `(', as that cannot actually be an
3023 archive-member reference (and treating it as such results in an empty
3024 file name, which causes much lossage). Also if it ends in ")" then
3025 it's a complete reference so we don't need to treat it specially. */
3027 if (tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3029 char *n = strchr (tp, '(');
3030 if (n)
3032 /* This is the first element in an open archive group. It looks
3033 like "lib(mem". Remember the close paren. */
3034 nlen -= (n + 1) - tp;
3035 tp = n + 1;
3037 /* If we have just "lib(", part of something like "lib( a b)",
3038 go to the next item. */
3039 if (! nlen)
3040 continue;
3044 /* If we are inside an archive group, make sure it has an end. */
3045 if (tp > tmpbuf)
3047 if (tp[nlen-1] == ')')
3049 /* This is the natural end; reset TP. */
3050 tp = tmpbuf;
3052 /* This is just ")", something like "lib(a b )": skip it. */
3053 if (nlen == 1)
3054 continue;
3056 else
3058 /* Not the end, so add a "fake" end. */
3059 tp[nlen++] = ')';
3060 tp[nlen] = '\0';
3063 #endif
3065 /* If we're not globbing we're done: add it to the end of the chain.
3066 Go to the next item in the string. */
3067 if (flags & PARSEFS_NOGLOB)
3069 NEWELT (concat (2, prefix, tp));
3070 continue;
3073 /* If we get here we know we're doing glob expansion.
3074 TP is a string in tmpbuf. NLEN is no longer used.
3075 We may need to do more work: after this NAME will be set. */
3076 name = tp;
3078 /* Expand tilde if applicable. */
3079 if (tp[0] == '~')
3081 tildep = tilde_expand (tp);
3082 if (tildep != 0)
3083 name = tildep;
3086 #ifndef NO_ARCHIVES
3087 /* If NAME is an archive member reference replace it with the archive
3088 file name, and save the member name in MEMNAME. We will glob on the
3089 archive name and then reattach MEMNAME later. */
3090 if (ar_name (name))
3092 ar_parse_name (name, &arname, &memname);
3093 name = arname;
3095 #endif /* !NO_ARCHIVES */
3097 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3099 case GLOB_NOSPACE:
3100 fatal (NILF, _("virtual memory exhausted"));
3102 case 0:
3103 /* Success. */
3104 i = gl.gl_pathc;
3105 nlist = (const char **)gl.gl_pathv;
3106 break;
3108 case GLOB_NOMATCH:
3109 /* If we want only existing items, skip this one. */
3110 if (flags & PARSEFS_EXISTS)
3112 i = 0;
3113 break;
3115 /* FALLTHROUGH */
3117 default:
3118 /* By default keep this name. */
3119 i = 1;
3120 nlist = &name;
3121 break;
3124 /* For each matched element, add it to the list. */
3125 while (i-- > 0)
3126 #ifndef NO_ARCHIVES
3127 if (memname != 0)
3129 /* Try to glob on MEMNAME within the archive. */
3130 struct nameseq *found = ar_glob (nlist[i], memname, size);
3131 if (! found)
3132 /* No matches. Use MEMNAME as-is. */
3133 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3134 else
3136 /* We got a chain of items. Attach them. */
3137 (*newp)->next = found;
3139 /* Find and set the new end. Massage names if necessary. */
3140 while (1)
3142 if (! cachep)
3143 found->name = xstrdup (concat (2, prefix, name));
3144 else if (prefix)
3145 found->name = strcache_add (concat (2, prefix, name));
3147 if (found->next == 0)
3148 break;
3150 found = found->next;
3152 newp = &found->next;
3155 else
3156 #endif /* !NO_ARCHIVES */
3157 NEWELT (concat (2, prefix, nlist[i]));
3159 globfree (&gl);
3161 #ifndef NO_ARCHIVES
3162 if (arname)
3163 free (arname);
3164 #endif
3166 if (tildep)
3167 free (tildep);
3170 *stringp = p;
3171 return new;