Massage the NEWS file
[make.git] / read.c
blobaa27701dd4bf27acde15a6703dbe7bf35e9a79da
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2009 Free Software
4 Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
21 #include <assert.h>
23 #include <glob.h>
25 #include "dep.h"
26 #include "filedef.h"
27 #include "job.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #include "debug.h"
32 #include "hash.h"
35 #ifndef WINDOWS32
36 #ifndef _AMIGA
37 #ifndef VMS
38 #include <pwd.h>
39 #else
40 struct passwd *getpwnam (char *name);
41 #endif
42 #endif
43 #endif /* !WINDOWS32 */
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
46 eval'ing.
49 struct ebuffer
51 char *buffer; /* Start of the current line in the buffer. */
52 char *bufnext; /* Start of the next line in the buffer. */
53 char *bufstart; /* Start of the entire buffer. */
54 unsigned int size; /* Malloc'd size of buffer. */
55 FILE *fp; /* File, or NULL if this is an internal buffer. */
56 struct floc floc; /* Info on the file in fp (if any). */
59 /* Track the modifiers we can have on variable assignments */
61 struct vmodifiers
63 unsigned int assign_v:1;
64 unsigned int define_v:1;
65 unsigned int undefine_v:1;
66 unsigned int export_v:1;
67 unsigned int override_v:1;
68 unsigned int private_v:1;
71 /* Types of "words" that can be read in a makefile. */
72 enum make_word_type
74 w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
75 w_varassign
79 /* A `struct conditionals' contains the information describing
80 all the active conditionals in a makefile.
82 The global variable `conditionals' contains the conditionals
83 information for the current makefile. It is initialized from
84 the static structure `toplevel_conditionals' and is later changed
85 to new structures for included makefiles. */
87 struct conditionals
89 unsigned int if_cmds; /* Depth of conditional nesting. */
90 unsigned int allocated; /* Elts allocated in following arrays. */
91 char *ignoring; /* Are we ignoring or interpreting?
92 0=interpreting, 1=not yet interpreted,
93 2=already interpreted */
94 char *seen_else; /* Have we already seen an `else'? */
97 static struct conditionals toplevel_conditionals;
98 static struct conditionals *conditionals = &toplevel_conditionals;
101 /* Default directories to search for include files in */
103 static const char *default_include_directories[] =
105 #if defined(WINDOWS32) && !defined(INCLUDEDIR)
106 /* This completely up to the user when they install MSVC or other packages.
107 This is defined as a placeholder. */
108 # define INCLUDEDIR "."
109 #endif
110 INCLUDEDIR,
111 #ifndef _AMIGA
112 "/usr/gnu/include",
113 "/usr/local/include",
114 "/usr/include",
115 #endif
119 /* List of directories to search for include files in */
121 static const char **include_directories;
123 /* Maximum length of an element of the above. */
125 static unsigned int max_incl_len;
127 /* The filename and pointer to line number of the
128 makefile currently being read in. */
130 const struct floc *reading_file = 0;
132 /* The chain of makefiles read by read_makefile. */
134 static struct dep *read_makefiles = 0;
136 static int eval_makefile (const char *filename, int flags);
137 static int eval (struct ebuffer *buffer, int flags);
139 static long readline (struct ebuffer *ebuf);
140 static void do_undefine (char *name, enum variable_origin origin,
141 struct ebuffer *ebuf);
142 static struct variable *do_define (char *name, enum variable_origin origin,
143 struct ebuffer *ebuf);
144 static int conditional_line (char *line, int len, const struct floc *flocp);
145 static void record_files (struct nameseq *filenames, const char *pattern,
146 const char *pattern_percent, char *depstr,
147 unsigned int cmds_started, char *commands,
148 unsigned int commands_idx, int two_colon,
149 const struct floc *flocp);
150 static void record_target_var (struct nameseq *filenames, char *defn,
151 enum variable_origin origin,
152 struct vmodifiers *vmod,
153 const struct floc *flocp);
154 static enum make_word_type get_next_mword (char *buffer, char *delim,
155 char **startp, unsigned int *length);
156 static void remove_comments (char *line);
157 static char *find_char_unquote (char *string, int stop1, int stop2,
158 int blank, int ignorevars);
161 /* Compare a word, both length and contents.
162 P must point to the word to be tested, and WLEN must be the length.
164 #define word1eq(s) (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
167 /* Read in all the makefiles and return the chain of their names. */
169 struct dep *
170 read_all_makefiles (const char **makefiles)
172 unsigned int num_makefiles = 0;
174 /* Create *_LIST variables, to hold the makefiles, targets, and variables
175 we will be reading. */
177 define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);
179 DB (DB_BASIC, (_("Reading makefiles...\n")));
181 /* If there's a non-null variable MAKEFILES, its value is a list of
182 files to read first thing. But don't let it prevent reading the
183 default makefiles and don't let the default goal come from there. */
186 char *value;
187 char *name, *p;
188 unsigned int length;
191 /* Turn off --warn-undefined-variables while we expand MAKEFILES. */
192 int save = warn_undefined_variables_flag;
193 warn_undefined_variables_flag = 0;
195 value = allocated_variable_expand ("$(MAKEFILES)");
197 warn_undefined_variables_flag = save;
200 /* Set NAME to the start of next token and LENGTH to its length.
201 MAKEFILES is updated for finding remaining tokens. */
202 p = value;
204 while ((name = find_next_token ((const char **)&p, &length)) != 0)
206 if (*p != '\0')
207 *p++ = '\0';
208 eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
211 free (value);
214 /* Read makefiles specified with -f switches. */
216 if (makefiles != 0)
217 while (*makefiles != 0)
219 struct dep *tail = read_makefiles;
220 register struct dep *d;
222 if (! eval_makefile (*makefiles, 0))
223 perror_with_name ("", *makefiles);
225 /* Find the right element of read_makefiles. */
226 d = read_makefiles;
227 while (d->next != tail)
228 d = d->next;
230 /* Use the storage read_makefile allocates. */
231 *makefiles = dep_name (d);
232 ++num_makefiles;
233 ++makefiles;
236 /* If there were no -f switches, try the default names. */
238 if (num_makefiles == 0)
240 static char *default_makefiles[] =
241 #ifdef VMS
242 /* all lower case since readdir() (the vms version) 'lowercasifies' */
243 { "makefile.vms", "gnumakefile.", "makefile.", 0 };
244 #else
245 #ifdef _AMIGA
246 { "GNUmakefile", "Makefile", "SMakefile", 0 };
247 #else /* !Amiga && !VMS */
248 { "GNUmakefile", "makefile", "Makefile", 0 };
249 #endif /* AMIGA */
250 #endif /* VMS */
251 register char **p = default_makefiles;
252 while (*p != 0 && !file_exists_p (*p))
253 ++p;
255 if (*p != 0)
257 if (! eval_makefile (*p, 0))
258 perror_with_name ("", *p);
260 else
262 /* No default makefile was found. Add the default makefiles to the
263 `read_makefiles' chain so they will be updated if possible. */
264 struct dep *tail = read_makefiles;
265 /* Add them to the tail, after any MAKEFILES variable makefiles. */
266 while (tail != 0 && tail->next != 0)
267 tail = tail->next;
268 for (p = default_makefiles; *p != 0; ++p)
270 struct dep *d = alloc_dep ();
271 d->file = enter_file (strcache_add (*p));
272 d->file->dontcare = 1;
273 /* Tell update_goal_chain to bail out as soon as this file is
274 made, and main not to die if we can't make this file. */
275 d->changed = RM_DONTCARE;
276 if (tail == 0)
277 read_makefiles = d;
278 else
279 tail->next = d;
280 tail = d;
282 if (tail != 0)
283 tail->next = 0;
287 return read_makefiles;
290 /* Install a new conditional and return the previous one. */
292 static struct conditionals *
293 install_conditionals (struct conditionals *new)
295 struct conditionals *save = conditionals;
297 memset (new, '\0', sizeof (*new));
298 conditionals = new;
300 return save;
303 /* Free the current conditionals and reinstate a saved one. */
305 static void
306 restore_conditionals (struct conditionals *saved)
308 /* Free any space allocated by conditional_line. */
309 if (conditionals->ignoring)
310 free (conditionals->ignoring);
311 if (conditionals->seen_else)
312 free (conditionals->seen_else);
314 /* Restore state. */
315 conditionals = saved;
318 static int
319 eval_makefile (const char *filename, int flags)
321 struct dep *deps;
322 struct ebuffer ebuf;
323 const struct floc *curfile;
324 char *expanded = 0;
325 int makefile_errno;
326 int r;
328 filename = strcache_add (filename);
329 ebuf.floc.filenm = filename;
330 ebuf.floc.lineno = 1;
332 if (ISDB (DB_VERBOSE))
334 printf (_("Reading makefile `%s'"), filename);
335 if (flags & RM_NO_DEFAULT_GOAL)
336 printf (_(" (no default goal)"));
337 if (flags & RM_INCLUDED)
338 printf (_(" (search path)"));
339 if (flags & RM_DONTCARE)
340 printf (_(" (don't care)"));
341 if (flags & RM_NO_TILDE)
342 printf (_(" (no ~ expansion)"));
343 puts ("...");
346 /* First, get a stream to read. */
348 /* Expand ~ in FILENAME unless it came from `include',
349 in which case it was already done. */
350 if (!(flags & RM_NO_TILDE) && filename[0] == '~')
352 expanded = tilde_expand (filename);
353 if (expanded != 0)
354 filename = expanded;
357 ebuf.fp = fopen (filename, "r");
358 /* Save the error code so we print the right message later. */
359 makefile_errno = errno;
361 /* If the makefile wasn't found and it's either a makefile from
362 the `MAKEFILES' variable or an included makefile,
363 search the included makefile search path for this makefile. */
364 if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
366 unsigned int i;
367 for (i = 0; include_directories[i] != 0; ++i)
369 const char *included = concat (3, include_directories[i],
370 "/", filename);
371 ebuf.fp = fopen (included, "r");
372 if (ebuf.fp)
374 filename = strcache_add (included);
375 break;
380 /* Add FILENAME to the chain of read makefiles. */
381 deps = alloc_dep ();
382 deps->next = read_makefiles;
383 read_makefiles = deps;
384 deps->file = lookup_file (filename);
385 if (deps->file == 0)
386 deps->file = enter_file (filename);
387 filename = deps->file->name;
388 deps->changed = flags;
389 if (flags & RM_DONTCARE)
390 deps->dontcare = 1;
392 if (expanded)
393 free (expanded);
395 /* If the makefile can't be found at all, give up entirely. */
397 if (ebuf.fp == 0)
399 /* If we did some searching, errno has the error from the last
400 attempt, rather from FILENAME itself. Restore it in case the
401 caller wants to use it in a message. */
402 errno = makefile_errno;
403 return 0;
406 /* Set close-on-exec to avoid leaking the makefile to children, such as
407 $(shell ...). */
408 #ifdef HAVE_FILENO
409 CLOSE_ON_EXEC (fileno (ebuf.fp));
410 #endif
412 /* Add this makefile to the list. */
413 do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
414 f_append, 0);
416 /* Evaluate the makefile */
418 ebuf.size = 200;
419 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
421 curfile = reading_file;
422 reading_file = &ebuf.floc;
424 r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
426 reading_file = curfile;
428 fclose (ebuf.fp);
430 free (ebuf.bufstart);
431 alloca (0);
432 return r;
436 eval_buffer (char *buffer)
438 struct ebuffer ebuf;
439 struct conditionals *saved;
440 struct conditionals new;
441 const struct floc *curfile;
442 int r;
444 /* Evaluate the buffer */
446 ebuf.size = strlen (buffer);
447 ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
448 ebuf.fp = NULL;
450 if (reading_file)
451 ebuf.floc = *reading_file;
452 else
453 ebuf.floc.filenm = NULL;
455 curfile = reading_file;
456 reading_file = &ebuf.floc;
458 saved = install_conditionals (&new);
460 r = eval (&ebuf, 1);
462 restore_conditionals (saved);
464 reading_file = curfile;
466 alloca (0);
467 return r;
470 /* Check LINE to see if it's a variable assignment or undefine.
472 It might use one of the modifiers "export", "override", "private", or it
473 might be one of the conditional tokens like "ifdef", "include", etc.
475 If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
476 Returns LINE.
478 Returns a pointer to the first non-modifier character, and sets VMOD
479 based on the modifiers found if any, plus V_ASSIGN is 1.
481 static char *
482 parse_var_assignment (const char *line, struct vmodifiers *vmod)
484 const char *p;
485 memset (vmod, '\0', sizeof (*vmod));
487 /* Find the start of the next token. If there isn't one we're done. */
488 line = next_token (line);
489 if (*line == '\0')
490 return (char *)line;
492 p = line;
493 while (1)
495 int wlen;
496 const char *p2;
497 enum variable_flavor flavor;
499 p2 = parse_variable_definition (p, &flavor);
501 /* If this is a variable assignment, we're done. */
502 if (p2)
503 break;
505 /* It's not a variable; see if it's a modifier. */
506 p2 = end_of_token (p);
507 wlen = p2 - p;
509 if (word1eq ("export"))
510 vmod->export_v = 1;
511 else if (word1eq ("override"))
512 vmod->override_v = 1;
513 else if (word1eq ("private"))
514 vmod->private_v = 1;
515 else if (word1eq ("define"))
517 /* We can't have modifiers after 'define' */
518 vmod->define_v = 1;
519 p = next_token (p2);
520 break;
522 else if (word1eq ("undefine"))
524 /* We can't have modifiers after 'undefine' */
525 vmod->undefine_v = 1;
526 p = next_token (p2);
527 break;
529 else
530 /* Not a variable or modifier: this is not a variable assignment. */
531 return (char *)line;
533 /* It was a modifier. Try the next word. */
534 p = next_token (p2);
535 if (*p == '\0')
536 return (char *)line;
539 /* Found a variable assignment or undefine. */
540 vmod->assign_v = 1;
541 return (char *)p;
546 /* Read file FILENAME as a makefile and add its contents to the data base.
548 SET_DEFAULT is true if we are allowed to set the default goal. */
551 static int
552 eval (struct ebuffer *ebuf, int set_default)
554 char *collapsed = 0;
555 unsigned int collapsed_length = 0;
556 unsigned int commands_len = 200;
557 char *commands;
558 unsigned int commands_idx = 0;
559 unsigned int cmds_started, tgts_started;
560 int ignoring = 0, in_ignored_define = 0;
561 int no_targets = 0; /* Set when reading a rule without targets. */
562 struct nameseq *filenames = 0;
563 char *depstr = 0;
564 long nlines = 0;
565 int two_colon = 0;
566 const char *pattern = 0;
567 const char *pattern_percent;
568 struct floc *fstart;
569 struct floc fi;
571 #define record_waiting_files() \
572 do \
574 if (filenames != 0) \
576 fi.lineno = tgts_started; \
577 record_files (filenames, pattern, pattern_percent, depstr, \
578 cmds_started, commands, commands_idx, two_colon, \
579 &fi); \
580 filenames = 0; \
582 commands_idx = 0; \
583 no_targets = 0; \
584 pattern = 0; \
585 } while (0)
587 pattern_percent = 0;
588 cmds_started = tgts_started = 1;
590 fstart = &ebuf->floc;
591 fi.filenm = ebuf->floc.filenm;
593 /* Loop over lines in the file.
594 The strategy is to accumulate target names in FILENAMES, dependencies
595 in DEPS and commands in COMMANDS. These are used to define a rule
596 when the start of the next rule (or eof) is encountered.
598 When you see a "continue" in the loop below, that means we are moving on
599 to the next line _without_ ending any rule that we happen to be working
600 with at the moment. If you see a "goto rule_complete", then the
601 statement we just parsed also finishes the previous rule. */
603 commands = xmalloc (200);
605 while (1)
607 unsigned int linelen;
608 char *line;
609 unsigned int wlen;
610 char *p;
611 char *p2;
612 struct vmodifiers vmod;
614 /* At the top of this loop, we are starting a brand new line. */
615 /* Grab the next line to be evaluated */
616 ebuf->floc.lineno += nlines;
617 nlines = readline (ebuf);
619 /* If there is nothing left to eval, we're done. */
620 if (nlines < 0)
621 break;
623 /* If this line is empty, skip it. */
624 line = ebuf->buffer;
625 if (line[0] == '\0')
626 continue;
628 linelen = strlen (line);
630 /* Check for a shell command line first.
631 If it is not one, we can stop treating tab specially. */
632 if (line[0] == cmd_prefix)
634 if (no_targets)
635 /* Ignore the commands in a rule with no targets. */
636 continue;
638 /* If there is no preceding rule line, don't treat this line
639 as a command, even though it begins with a recipe prefix.
640 SunOS 4 make appears to behave this way. */
642 if (filenames != 0)
644 if (ignoring)
645 /* Yep, this is a shell command, and we don't care. */
646 continue;
648 /* Append this command line to the line being accumulated.
649 Strip command prefix chars that appear after newlines. */
650 if (commands_idx == 0)
651 cmds_started = ebuf->floc.lineno;
653 if (linelen + commands_idx > commands_len)
655 commands_len = (linelen + commands_idx) * 2;
656 commands = xrealloc (commands, commands_len);
658 p = &commands[commands_idx];
659 p2 = line + 1;
660 while (--linelen)
662 ++commands_idx;
663 *(p++) = *p2;
664 if (p2[0] == '\n' && p2[1] == cmd_prefix)
666 ++p2;
667 --linelen;
669 ++p2;
671 *p = '\n';
672 ++commands_idx;
674 continue;
678 /* This line is not a shell command line. Don't worry about whitespace.
679 Get more space if we need it; we don't need to preserve the current
680 contents of the buffer. */
682 if (collapsed_length < linelen+1)
684 collapsed_length = linelen+1;
685 if (collapsed)
686 free (collapsed);
687 /* Don't need xrealloc: we don't need to preserve the content. */
688 collapsed = xmalloc (collapsed_length);
690 strcpy (collapsed, line);
691 /* Collapse continuation lines. */
692 collapse_continuations (collapsed);
693 remove_comments (collapsed);
695 /* Get rid if starting space (including formfeed, vtab, etc.) */
696 p = collapsed;
697 while (isspace ((unsigned char)*p))
698 ++p;
700 /* See if this is a variable assignment. We need to do this early, to
701 allow variables with names like 'ifdef', 'export', 'private', etc. */
702 p = parse_var_assignment(p, &vmod);
703 if (vmod.assign_v)
705 struct variable *v;
706 enum variable_origin origin = vmod.override_v ? o_override : o_file;
708 /* If we're ignoring then we're done now. */
709 if (ignoring)
711 if (vmod.define_v)
712 in_ignored_define = 1;
713 continue;
716 if (vmod.undefine_v)
718 do_undefine (p, origin, ebuf);
720 /* This line has been dealt with. */
721 goto rule_complete;
723 else if (vmod.define_v)
724 v = do_define (p, origin, ebuf);
725 else
726 v = try_variable_definition (fstart, p, origin, 0);
728 assert (v != NULL);
730 if (vmod.export_v)
731 v->export = v_export;
732 if (vmod.private_v)
733 v->private_var = 1;
735 /* This line has been dealt with. */
736 goto rule_complete;
739 /* If this line is completely empty, ignore it. */
740 if (*p == '\0')
741 continue;
743 p2 = end_of_token (p);
744 wlen = p2 - p;
745 p2 = next_token (p2);
747 /* If we're in an ignored define, skip this line (but maybe get out). */
748 if (in_ignored_define)
750 /* See if this is an endef line (plus optional comment). */
751 if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
752 in_ignored_define = 0;
754 continue;
757 /* Check for conditional state changes. */
759 int i = conditional_line (p, wlen, fstart);
760 if (i != -2)
762 if (i == -1)
763 fatal (fstart, _("invalid syntax in conditional"));
765 ignoring = i;
766 continue;
770 /* Nothing to see here... move along. */
771 if (ignoring)
772 continue;
774 /* Manage the "export" keyword used outside of variable assignment
775 as well as "unexport". */
776 if (word1eq ("export") || word1eq ("unexport"))
778 int exporting = *p == 'u' ? 0 : 1;
780 /* (un)export by itself causes everything to be (un)exported. */
781 if (*p2 == '\0')
782 export_all_variables = exporting;
783 else
785 unsigned int l;
786 const char *cp;
787 char *ap;
789 /* Expand the line so we can use indirect and constructed
790 variable names in an (un)export command. */
791 cp = ap = allocated_variable_expand (p2);
793 for (p = find_next_token (&cp, &l); p != 0;
794 p = find_next_token (&cp, &l))
796 struct variable *v = lookup_variable (p, l);
797 if (v == 0)
798 v = define_variable_loc (p, l, "", o_file, 0, fstart);
799 v->export = exporting ? v_export : v_noexport;
802 free (ap);
804 goto rule_complete;
807 /* Handle the special syntax for vpath. */
808 if (word1eq ("vpath"))
810 const char *cp;
811 char *vpat;
812 unsigned int l;
813 cp = variable_expand (p2);
814 p = find_next_token (&cp, &l);
815 if (p != 0)
817 vpat = xstrndup (p, l);
818 p = find_next_token (&cp, &l);
819 /* No searchpath means remove all previous
820 selective VPATH's with the same pattern. */
822 else
823 /* No pattern means remove all previous selective VPATH's. */
824 vpat = 0;
825 construct_vpath_list (vpat, p);
826 if (vpat != 0)
827 free (vpat);
829 goto rule_complete;
832 /* Handle include and variants. */
833 if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
835 /* We have found an `include' line specifying a nested
836 makefile to be read at this point. */
837 struct conditionals *save;
838 struct conditionals new_conditionals;
839 struct nameseq *files;
840 /* "-include" (vs "include") says no error if the file does not
841 exist. "sinclude" is an alias for this from SGI. */
842 int noerror = (p[0] != 'i');
844 p = allocated_variable_expand (p2);
846 /* If no filenames, it's a no-op. */
847 if (*p == '\0')
849 free (p);
850 continue;
853 /* Parse the list of file names. */
854 p2 = p;
855 files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
856 free (p);
858 /* Save the state of conditionals and start
859 the included makefile with a clean slate. */
860 save = install_conditionals (&new_conditionals);
862 /* Record the rules that are waiting so they will determine
863 the default goal before those in the included makefile. */
864 record_waiting_files ();
866 /* Read each included makefile. */
867 while (files != 0)
869 struct nameseq *next = files->next;
870 const char *name = files->name;
871 int r;
873 free_ns (files);
874 files = next;
876 r = eval_makefile (name,
877 (RM_INCLUDED | RM_NO_TILDE
878 | (noerror ? RM_DONTCARE : 0)
879 | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
880 if (!r && !noerror)
881 error (fstart, "%s: %s", name, strerror (errno));
884 /* Restore conditional state. */
885 restore_conditionals (save);
887 goto rule_complete;
890 /* This line starts with a tab but was not caught above because there
891 was no preceding target, and the line might have been usable as a
892 variable definition. But now we know it is definitely lossage. */
893 if (line[0] == cmd_prefix)
894 fatal(fstart, _("recipe commences before first target"));
896 /* This line describes some target files. This is complicated by
897 the existence of target-specific variables, because we can't
898 expand the entire line until we know if we have one or not. So
899 we expand the line word by word until we find the first `:',
900 then check to see if it's a target-specific variable.
902 In this algorithm, `lb_next' will point to the beginning of the
903 unexpanded parts of the input buffer, while `p2' points to the
904 parts of the expanded buffer we haven't searched yet. */
907 enum make_word_type wtype;
908 char *cmdleft, *semip, *lb_next;
909 unsigned int plen = 0;
910 char *colonp;
911 const char *end, *beg; /* Helpers for whitespace stripping. */
913 /* Record the previous rule. */
915 record_waiting_files ();
916 tgts_started = fstart->lineno;
918 /* Search the line for an unquoted ; that is not after an
919 unquoted #. */
920 cmdleft = find_char_unquote (line, ';', '#', 0, 1);
921 if (cmdleft != 0 && *cmdleft == '#')
923 /* We found a comment before a semicolon. */
924 *cmdleft = '\0';
925 cmdleft = 0;
927 else if (cmdleft != 0)
928 /* Found one. Cut the line short there before expanding it. */
929 *(cmdleft++) = '\0';
930 semip = cmdleft;
932 collapse_continuations (line);
934 /* We can't expand the entire line, since if it's a per-target
935 variable we don't want to expand it. So, walk from the
936 beginning, expanding as we go, and looking for "interesting"
937 chars. The first word is always expandable. */
938 wtype = get_next_mword(line, NULL, &lb_next, &wlen);
939 switch (wtype)
941 case w_eol:
942 if (cmdleft != 0)
943 fatal(fstart, _("missing rule before recipe"));
944 /* This line contained something but turned out to be nothing
945 but whitespace (a comment?). */
946 continue;
948 case w_colon:
949 case w_dcolon:
950 /* We accept and ignore rules without targets for
951 compatibility with SunOS 4 make. */
952 no_targets = 1;
953 continue;
955 default:
956 break;
959 p2 = variable_expand_string(NULL, lb_next, wlen);
961 while (1)
963 lb_next += wlen;
964 if (cmdleft == 0)
966 /* Look for a semicolon in the expanded line. */
967 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
969 if (cmdleft != 0)
971 unsigned long p2_off = p2 - variable_buffer;
972 unsigned long cmd_off = cmdleft - variable_buffer;
973 char *pend = p2 + strlen(p2);
975 /* Append any remnants of lb, then cut the line short
976 at the semicolon. */
977 *cmdleft = '\0';
979 /* One school of thought says that you shouldn't expand
980 here, but merely copy, since now you're beyond a ";"
981 and into a command script. However, the old parser
982 expanded the whole line, so we continue that for
983 backwards-compatiblity. Also, it wouldn't be
984 entirely consistent, since we do an unconditional
985 expand below once we know we don't have a
986 target-specific variable. */
987 (void)variable_expand_string(pend, lb_next, (long)-1);
988 lb_next += strlen(lb_next);
989 p2 = variable_buffer + p2_off;
990 cmdleft = variable_buffer + cmd_off + 1;
994 colonp = find_char_unquote(p2, ':', 0, 0, 0);
995 #ifdef HAVE_DOS_PATHS
996 /* The drive spec brain-damage strikes again... */
997 /* Note that the only separators of targets in this context
998 are whitespace and a left paren. If others are possible,
999 they should be added to the string in the call to index. */
1000 while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
1001 colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
1002 (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
1003 colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
1004 #endif
1005 if (colonp != 0)
1006 break;
1008 wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
1009 if (wtype == w_eol)
1010 break;
1012 p2 += strlen(p2);
1013 *(p2++) = ' ';
1014 p2 = variable_expand_string(p2, lb_next, wlen);
1015 /* We don't need to worry about cmdleft here, because if it was
1016 found in the variable_buffer the entire buffer has already
1017 been expanded... we'll never get here. */
1020 p2 = next_token (variable_buffer);
1022 /* If the word we're looking at is EOL, see if there's _anything_
1023 on the line. If not, a variable expanded to nothing, so ignore
1024 it. If so, we can't parse this line so punt. */
1025 if (wtype == w_eol)
1027 if (*p2 != '\0')
1028 /* There's no need to be ivory-tower about this: check for
1029 one of the most common bugs found in makefiles... */
1030 fatal (fstart, _("missing separator%s"),
1031 (cmd_prefix == '\t' && !strneq(line, " ", 8))
1032 ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1033 continue;
1036 /* Make the colon the end-of-string so we know where to stop
1037 looking for targets. */
1038 *colonp = '\0';
1039 filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1040 *p2 = ':';
1042 if (!filenames)
1044 /* We accept and ignore rules without targets for
1045 compatibility with SunOS 4 make. */
1046 no_targets = 1;
1047 continue;
1049 /* This should never be possible; we handled it above. */
1050 assert (*p2 != '\0');
1051 ++p2;
1053 /* Is this a one-colon or two-colon entry? */
1054 two_colon = *p2 == ':';
1055 if (two_colon)
1056 p2++;
1058 /* Test to see if it's a target-specific variable. Copy the rest
1059 of the buffer over, possibly temporarily (we'll expand it later
1060 if it's not a target-specific variable). PLEN saves the length
1061 of the unparsed section of p2, for later. */
1062 if (*lb_next != '\0')
1064 unsigned int l = p2 - variable_buffer;
1065 plen = strlen (p2);
1066 variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1067 p2 = variable_buffer + l;
1070 p2 = parse_var_assignment (p2, &vmod);
1071 if (vmod.assign_v)
1073 /* If there was a semicolon found, add it back, plus anything
1074 after it. */
1075 if (semip)
1077 unsigned int l = p - variable_buffer;
1078 *(--semip) = ';';
1079 collapse_continuations (semip);
1080 variable_buffer_output (p2 + strlen (p2),
1081 semip, strlen (semip)+1);
1082 p = variable_buffer + l;
1084 record_target_var (filenames, p2,
1085 vmod.override_v ? o_override : o_file,
1086 &vmod, fstart);
1087 filenames = 0;
1088 continue;
1091 /* This is a normal target, _not_ a target-specific variable.
1092 Unquote any = in the dependency list. */
1093 find_char_unquote (lb_next, '=', 0, 0, 0);
1095 /* We have some targets, so don't ignore the following commands. */
1096 no_targets = 0;
1098 /* Expand the dependencies, etc. */
1099 if (*lb_next != '\0')
1101 unsigned int l = p2 - variable_buffer;
1102 (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1103 p2 = variable_buffer + l;
1105 /* Look for a semicolon in the expanded line. */
1106 if (cmdleft == 0)
1108 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1109 if (cmdleft != 0)
1110 *(cmdleft++) = '\0';
1114 /* Is this a static pattern rule: `target: %targ: %dep; ...'? */
1115 p = strchr (p2, ':');
1116 while (p != 0 && p[-1] == '\\')
1118 char *q = &p[-1];
1119 int backslash = 0;
1120 while (*q-- == '\\')
1121 backslash = !backslash;
1122 if (backslash)
1123 p = strchr (p + 1, ':');
1124 else
1125 break;
1127 #ifdef _AMIGA
1128 /* Here, the situation is quite complicated. Let's have a look
1129 at a couple of targets:
1131 install: dev:make
1133 dev:make: make
1135 dev:make:: xyz
1137 The rule is that it's only a target, if there are TWO :'s
1138 OR a space around the :.
1140 if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1141 || isspace ((unsigned char)p[-1])))
1142 p = 0;
1143 #endif
1144 #ifdef HAVE_DOS_PATHS
1146 int check_again;
1147 do {
1148 check_again = 0;
1149 /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1150 if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1151 isalpha ((unsigned char)p[-1]) &&
1152 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1153 p = strchr (p + 1, ':');
1154 check_again = 1;
1156 } while (check_again);
1158 #endif
1159 if (p != 0)
1161 struct nameseq *target;
1162 target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1163 PARSEFS_NOGLOB);
1164 ++p2;
1165 if (target == 0)
1166 fatal (fstart, _("missing target pattern"));
1167 else if (target->next != 0)
1168 fatal (fstart, _("multiple target patterns"));
1169 pattern_percent = find_percent_cached (&target->name);
1170 pattern = target->name;
1171 if (pattern_percent == 0)
1172 fatal (fstart, _("target pattern contains no `%%'"));
1173 free_ns (target);
1175 else
1176 pattern = 0;
1178 /* Strip leading and trailing whitespaces. */
1179 beg = p2;
1180 end = beg + strlen (beg) - 1;
1181 strip_whitespace (&beg, &end);
1183 /* Put all the prerequisites here; they'll be parsed later. */
1184 if (beg <= end && *beg != '\0')
1185 depstr = xstrndup (beg, end - beg + 1);
1186 else
1187 depstr = 0;
1189 commands_idx = 0;
1190 if (cmdleft != 0)
1192 /* Semicolon means rest of line is a command. */
1193 unsigned int l = strlen (cmdleft);
1195 cmds_started = fstart->lineno;
1197 /* Add this command line to the buffer. */
1198 if (l + 2 > commands_len)
1200 commands_len = (l + 2) * 2;
1201 commands = xrealloc (commands, commands_len);
1203 memcpy (commands, cmdleft, l);
1204 commands_idx += l;
1205 commands[commands_idx++] = '\n';
1208 /* Determine if this target should be made default. We used to do
1209 this in record_files() but because of the delayed target recording
1210 and because preprocessor directives are legal in target's commands
1211 it is too late. Consider this fragment for example:
1213 foo:
1215 ifeq ($(.DEFAULT_GOAL),foo)
1217 endif
1219 Because the target is not recorded until after ifeq directive is
1220 evaluated the .DEFAULT_GOAL does not contain foo yet as one
1221 would expect. Because of this we have to move the logic here. */
1223 if (set_default && default_goal_var->value[0] == '\0')
1225 const char *name;
1226 struct dep *d;
1227 struct nameseq *t = filenames;
1229 for (; t != 0; t = t->next)
1231 int reject = 0;
1232 name = t->name;
1234 /* We have nothing to do if this is an implicit rule. */
1235 if (strchr (name, '%') != 0)
1236 break;
1238 /* See if this target's name does not start with a `.',
1239 unless it contains a slash. */
1240 if (*name == '.' && strchr (name, '/') == 0
1241 #ifdef HAVE_DOS_PATHS
1242 && strchr (name, '\\') == 0
1243 #endif
1245 continue;
1248 /* If this file is a suffix, don't let it be
1249 the default goal file. */
1250 for (d = suffix_file->deps; d != 0; d = d->next)
1252 register struct dep *d2;
1253 if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1255 reject = 1;
1256 break;
1258 for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1260 unsigned int l = strlen (dep_name (d2));
1261 if (!strneq (name, dep_name (d2), l))
1262 continue;
1263 if (streq (name + l, dep_name (d)))
1265 reject = 1;
1266 break;
1270 if (reject)
1271 break;
1274 if (!reject)
1276 define_variable_global (".DEFAULT_GOAL", 13, t->name,
1277 o_file, 0, NILF);
1278 break;
1283 continue;
1286 /* We get here except in the case that we just read a rule line.
1287 Record now the last rule we read, so following spurious
1288 commands are properly diagnosed. */
1289 rule_complete:
1290 record_waiting_files ();
1293 #undef word1eq
1295 if (conditionals->if_cmds)
1296 fatal (fstart, _("missing `endif'"));
1298 /* At eof, record the last rule. */
1299 record_waiting_files ();
1301 if (collapsed)
1302 free (collapsed);
1303 free (commands);
1305 return 1;
1309 /* Remove comments from LINE.
1310 This is done by copying the text at LINE onto itself. */
1312 static void
1313 remove_comments (char *line)
1315 char *comment;
1317 comment = find_char_unquote (line, '#', 0, 0, 0);
1319 if (comment != 0)
1320 /* Cut off the line at the #. */
1321 *comment = '\0';
1324 /* Execute a `undefine' directive.
1325 The undefine line has already been read, and NAME is the name of
1326 the variable to be undefined. */
1328 static void
1329 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1331 char *p, *var;
1333 /* Expand the variable name and find the beginning (NAME) and end. */
1334 var = allocated_variable_expand (name);
1335 name = next_token (var);
1336 if (*name == '\0')
1337 fatal (&ebuf->floc, _("empty variable name"));
1338 p = name + strlen (name) - 1;
1339 while (p > name && isblank ((unsigned char)*p))
1340 --p;
1341 p[1] = '\0';
1343 undefine_variable_global (name, p - name + 1, origin);
1344 free (var);
1347 /* Execute a `define' directive.
1348 The first line has already been read, and NAME is the name of
1349 the variable to be defined. The following lines remain to be read. */
1351 static struct variable *
1352 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1354 struct variable *v;
1355 enum variable_flavor flavor;
1356 struct floc defstart;
1357 int nlevels = 1;
1358 unsigned int length = 100;
1359 char *definition = xmalloc (length);
1360 unsigned int idx = 0;
1361 char *p, *var;
1363 defstart = ebuf->floc;
1365 p = parse_variable_definition (name, &flavor);
1366 if (p == NULL)
1367 /* No assignment token, so assume recursive. */
1368 flavor = f_recursive;
1369 else
1371 if (*(next_token (p)) != '\0')
1372 error (&defstart, _("extraneous text after `define' directive"));
1374 /* Chop the string before the assignment token to get the name. */
1375 p[flavor == f_recursive ? -1 : -2] = '\0';
1378 /* Expand the variable name and find the beginning (NAME) and end. */
1379 var = allocated_variable_expand (name);
1380 name = next_token (var);
1381 if (*name == '\0')
1382 fatal (&defstart, _("empty variable name"));
1383 p = name + strlen (name) - 1;
1384 while (p > name && isblank ((unsigned char)*p))
1385 --p;
1386 p[1] = '\0';
1388 /* Now read the value of the variable. */
1389 while (1)
1391 unsigned int len;
1392 char *line;
1393 long nlines = readline (ebuf);
1395 /* If there is nothing left to be eval'd, there's no 'endef'!! */
1396 if (nlines < 0)
1397 fatal (&defstart, _("missing `endef', unterminated `define'"));
1399 ebuf->floc.lineno += nlines;
1400 line = ebuf->buffer;
1402 collapse_continuations (line);
1404 /* If the line doesn't begin with a tab, test to see if it introduces
1405 another define, or ends one. Stop if we find an 'endef' */
1406 if (line[0] != cmd_prefix)
1408 p = next_token (line);
1409 len = strlen (p);
1411 /* If this is another 'define', increment the level count. */
1412 if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1413 && strneq (p, "define", 6))
1414 ++nlevels;
1416 /* If this is an 'endef', decrement the count. If it's now 0,
1417 we've found the last one. */
1418 else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1419 && strneq (p, "endef", 5))
1421 p += 5;
1422 remove_comments (p);
1423 if (*(next_token (p)) != '\0')
1424 error (&ebuf->floc,
1425 _("extraneous text after `endef' directive"));
1427 if (--nlevels == 0)
1428 break;
1432 /* Add this line to the variable definition. */
1433 len = strlen (line);
1434 if (idx + len + 1 > length)
1436 length = (idx + len) * 2;
1437 definition = xrealloc (definition, length + 1);
1440 memcpy (&definition[idx], line, len);
1441 idx += len;
1442 /* Separate lines with a newline. */
1443 definition[idx++] = '\n';
1446 /* We've got what we need; define the variable. */
1447 if (idx == 0)
1448 definition[0] = '\0';
1449 else
1450 definition[idx - 1] = '\0';
1452 v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1453 free (definition);
1454 free (var);
1455 return (v);
1458 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1459 "ifneq", "else" and "endif".
1460 LINE is the input line, with the command as its first word.
1462 FILENAME and LINENO are the filename and line number in the
1463 current makefile. They are used for error messages.
1465 Value is -2 if the line is not a conditional at all,
1466 -1 if the line is an invalid conditional,
1467 0 if following text should be interpreted,
1468 1 if following text should be ignored. */
1470 static int
1471 conditional_line (char *line, int len, const struct floc *flocp)
1473 char *cmdname;
1474 enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1475 unsigned int i;
1476 unsigned int o;
1478 /* Compare a word, both length and contents. */
1479 #define word1eq(s) (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1480 #define chkword(s, t) if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1482 /* Make sure this line is a conditional. */
1483 chkword ("ifdef", c_ifdef)
1484 else chkword ("ifndef", c_ifndef)
1485 else chkword ("ifeq", c_ifeq)
1486 else chkword ("ifneq", c_ifneq)
1487 else chkword ("else", c_else)
1488 else chkword ("endif", c_endif)
1489 else
1490 return -2;
1492 /* Found one: skip past it and any whitespace after it. */
1493 line = next_token (line + len);
1495 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1497 /* An 'endif' cannot contain extra text, and reduces the if-depth by 1 */
1498 if (cmdtype == c_endif)
1500 if (*line != '\0')
1501 EXTRANEOUS ();
1503 if (!conditionals->if_cmds)
1504 fatal (flocp, _("extraneous `%s'"), cmdname);
1506 --conditionals->if_cmds;
1508 goto DONE;
1511 /* An 'else' statement can either be simple, or it can have another
1512 conditional after it. */
1513 if (cmdtype == c_else)
1515 const char *p;
1517 if (!conditionals->if_cmds)
1518 fatal (flocp, _("extraneous `%s'"), cmdname);
1520 o = conditionals->if_cmds - 1;
1522 if (conditionals->seen_else[o])
1523 fatal (flocp, _("only one `else' per conditional"));
1525 /* Change the state of ignorance. */
1526 switch (conditionals->ignoring[o])
1528 case 0:
1529 /* We've just been interpreting. Never do it again. */
1530 conditionals->ignoring[o] = 2;
1531 break;
1532 case 1:
1533 /* We've never interpreted yet. Maybe this time! */
1534 conditionals->ignoring[o] = 0;
1535 break;
1538 /* It's a simple 'else'. */
1539 if (*line == '\0')
1541 conditionals->seen_else[o] = 1;
1542 goto DONE;
1545 /* The 'else' has extra text. That text must be another conditional
1546 and cannot be an 'else' or 'endif'. */
1548 /* Find the length of the next word. */
1549 for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1551 len = p - line;
1553 /* If it's 'else' or 'endif' or an illegal conditional, fail. */
1554 if (word1eq("else") || word1eq("endif")
1555 || conditional_line (line, len, flocp) < 0)
1556 EXTRANEOUS ();
1557 else
1559 /* conditional_line() created a new level of conditional.
1560 Raise it back to this level. */
1561 if (conditionals->ignoring[o] < 2)
1562 conditionals->ignoring[o] = conditionals->ignoring[o+1];
1563 --conditionals->if_cmds;
1566 goto DONE;
1569 if (conditionals->allocated == 0)
1571 conditionals->allocated = 5;
1572 conditionals->ignoring = xmalloc (conditionals->allocated);
1573 conditionals->seen_else = xmalloc (conditionals->allocated);
1576 o = conditionals->if_cmds++;
1577 if (conditionals->if_cmds > conditionals->allocated)
1579 conditionals->allocated += 5;
1580 conditionals->ignoring = xrealloc (conditionals->ignoring,
1581 conditionals->allocated);
1582 conditionals->seen_else = xrealloc (conditionals->seen_else,
1583 conditionals->allocated);
1586 /* Record that we have seen an `if...' but no `else' so far. */
1587 conditionals->seen_else[o] = 0;
1589 /* Search through the stack to see if we're already ignoring. */
1590 for (i = 0; i < o; ++i)
1591 if (conditionals->ignoring[i])
1593 /* We are already ignoring, so just push a level to match the next
1594 "else" or "endif", and keep ignoring. We don't want to expand
1595 variables in the condition. */
1596 conditionals->ignoring[o] = 1;
1597 return 1;
1600 if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1602 char *var;
1603 struct variable *v;
1604 char *p;
1606 /* Expand the thing we're looking up, so we can use indirect and
1607 constructed variable names. */
1608 var = allocated_variable_expand (line);
1610 /* Make sure there's only one variable name to test. */
1611 p = end_of_token (var);
1612 i = p - var;
1613 p = next_token (p);
1614 if (*p != '\0')
1615 return -1;
1617 var[i] = '\0';
1618 v = lookup_variable (var, i);
1620 conditionals->ignoring[o] =
1621 ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1623 free (var);
1625 else
1627 /* "ifeq" or "ifneq". */
1628 char *s1, *s2;
1629 unsigned int l;
1630 char termin = *line == '(' ? ',' : *line;
1632 if (termin != ',' && termin != '"' && termin != '\'')
1633 return -1;
1635 s1 = ++line;
1636 /* Find the end of the first string. */
1637 if (termin == ',')
1639 int count = 0;
1640 for (; *line != '\0'; ++line)
1641 if (*line == '(')
1642 ++count;
1643 else if (*line == ')')
1644 --count;
1645 else if (*line == ',' && count <= 0)
1646 break;
1648 else
1649 while (*line != '\0' && *line != termin)
1650 ++line;
1652 if (*line == '\0')
1653 return -1;
1655 if (termin == ',')
1657 /* Strip blanks after the first string. */
1658 char *p = line++;
1659 while (isblank ((unsigned char)p[-1]))
1660 --p;
1661 *p = '\0';
1663 else
1664 *line++ = '\0';
1666 s2 = variable_expand (s1);
1667 /* We must allocate a new copy of the expanded string because
1668 variable_expand re-uses the same buffer. */
1669 l = strlen (s2);
1670 s1 = alloca (l + 1);
1671 memcpy (s1, s2, l + 1);
1673 if (termin != ',')
1674 /* Find the start of the second string. */
1675 line = next_token (line);
1677 termin = termin == ',' ? ')' : *line;
1678 if (termin != ')' && termin != '"' && termin != '\'')
1679 return -1;
1681 /* Find the end of the second string. */
1682 if (termin == ')')
1684 int count = 0;
1685 s2 = next_token (line);
1686 for (line = s2; *line != '\0'; ++line)
1688 if (*line == '(')
1689 ++count;
1690 else if (*line == ')')
1692 if (count <= 0)
1693 break;
1694 else
1695 --count;
1699 else
1701 ++line;
1702 s2 = line;
1703 while (*line != '\0' && *line != termin)
1704 ++line;
1707 if (*line == '\0')
1708 return -1;
1710 *line = '\0';
1711 line = next_token (++line);
1712 if (*line != '\0')
1713 EXTRANEOUS ();
1715 s2 = variable_expand (s2);
1716 conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1719 DONE:
1720 /* Search through the stack to see if we're ignoring. */
1721 for (i = 0; i < conditionals->if_cmds; ++i)
1722 if (conditionals->ignoring[i])
1723 return 1;
1724 return 0;
1728 /* Record target-specific variable values for files FILENAMES.
1729 TWO_COLON is nonzero if a double colon was used.
1731 The links of FILENAMES are freed, and so are any names in it
1732 that are not incorporated into other data structures.
1734 If the target is a pattern, add the variable to the pattern-specific
1735 variable value list. */
1737 static void
1738 record_target_var (struct nameseq *filenames, char *defn,
1739 enum variable_origin origin, struct vmodifiers *vmod,
1740 const struct floc *flocp)
1742 struct nameseq *nextf;
1743 struct variable_set_list *global;
1745 global = current_variable_set_list;
1747 /* If the variable is an append version, store that but treat it as a
1748 normal recursive variable. */
1750 for (; filenames != 0; filenames = nextf)
1752 struct variable *v;
1753 const char *name = filenames->name;
1754 const char *fname;
1755 const char *percent;
1756 struct pattern_var *p;
1758 nextf = filenames->next;
1759 free_ns (filenames);
1761 /* If it's a pattern target, then add it to the pattern-specific
1762 variable list. */
1763 percent = find_percent_cached (&name);
1764 if (percent)
1766 /* Get a reference for this pattern-specific variable struct. */
1767 p = create_pattern_var (name, percent);
1768 p->variable.fileinfo = *flocp;
1769 /* I don't think this can fail since we already determined it was a
1770 variable definition. */
1771 v = assign_variable_definition (&p->variable, defn);
1772 assert (v != 0);
1774 v->origin = origin;
1775 if (v->flavor == f_simple)
1776 v->value = allocated_variable_expand (v->value);
1777 else
1778 v->value = xstrdup (v->value);
1780 fname = p->target;
1782 else
1784 struct file *f;
1786 /* Get a file reference for this file, and initialize it.
1787 We don't want to just call enter_file() because that allocates a
1788 new entry if the file is a double-colon, which we don't want in
1789 this situation. */
1790 f = lookup_file (name);
1791 if (!f)
1792 f = enter_file (strcache_add (name));
1793 else if (f->double_colon)
1794 f = f->double_colon;
1796 initialize_file_variables (f, 1);
1797 fname = f->name;
1799 current_variable_set_list = f->variables;
1800 v = try_variable_definition (flocp, defn, origin, 1);
1801 if (!v)
1802 fatal (flocp, _("Malformed target-specific variable definition"));
1803 current_variable_set_list = global;
1806 /* Set up the variable to be *-specific. */
1807 v->per_target = 1;
1808 v->private_var = vmod->private_v;
1809 v->export = vmod->export_v ? v_export : v_default;
1811 /* If it's not an override, check to see if there was a command-line
1812 setting. If so, reset the value. */
1813 if (v->origin != o_override)
1815 struct variable *gv;
1816 int len = strlen(v->name);
1818 gv = lookup_variable (v->name, len);
1819 if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1821 if (v->value != 0)
1822 free (v->value);
1823 v->value = xstrdup (gv->value);
1824 v->origin = gv->origin;
1825 v->recursive = gv->recursive;
1826 v->append = 0;
1832 /* Record a description line for files FILENAMES,
1833 with dependencies DEPS, commands to execute described
1834 by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1835 TWO_COLON is nonzero if a double colon was used.
1836 If not nil, PATTERN is the `%' pattern to make this
1837 a static pattern rule, and PATTERN_PERCENT is a pointer
1838 to the `%' within it.
1840 The links of FILENAMES are freed, and so are any names in it
1841 that are not incorporated into other data structures. */
1843 static void
1844 record_files (struct nameseq *filenames, const char *pattern,
1845 const char *pattern_percent, char *depstr,
1846 unsigned int cmds_started, char *commands,
1847 unsigned int commands_idx, int two_colon,
1848 const struct floc *flocp)
1850 struct commands *cmds;
1851 struct dep *deps;
1852 const char *implicit_percent;
1853 const char *name;
1855 /* If we've already snapped deps, that means we're in an eval being
1856 resolved after the makefiles have been read in. We can't add more rules
1857 at this time, since they won't get snapped and we'll get core dumps.
1858 See Savannah bug # 12124. */
1859 if (snapped_deps)
1860 fatal (flocp, _("prerequisites cannot be defined in recipes"));
1862 /* Determine if this is a pattern rule or not. */
1863 name = filenames->name;
1864 implicit_percent = find_percent_cached (&name);
1866 /* If there's a recipe, set up a struct for it. */
1867 if (commands_idx > 0)
1869 cmds = xmalloc (sizeof (struct commands));
1870 cmds->fileinfo.filenm = flocp->filenm;
1871 cmds->fileinfo.lineno = cmds_started;
1872 cmds->commands = xstrndup (commands, commands_idx);
1873 cmds->command_lines = 0;
1875 else
1876 cmds = 0;
1878 /* If there's a prereq string then parse it--unless it's eligible for 2nd
1879 expansion: if so, snap_deps() will do it. */
1880 if (depstr == 0)
1881 deps = 0;
1882 else if (second_expansion && strchr (depstr, '$'))
1884 deps = alloc_dep ();
1885 deps->name = depstr;
1886 deps->need_2nd_expansion = 1;
1887 deps->staticpattern = pattern != 0;
1889 else
1891 deps = split_prereqs (depstr);
1892 free (depstr);
1894 /* We'll enter static pattern prereqs later when we have the stem. We
1895 don't want to enter pattern rules at all so that we don't think that
1896 they ought to exist (make manual "Implicit Rule Search Algorithm",
1897 item 5c). */
1898 if (! pattern && ! implicit_percent)
1899 deps = enter_prereqs (deps, NULL);
1902 /* For implicit rules, _all_ the targets must have a pattern. That means we
1903 can test the first one to see if we're working with an implicit rule; if
1904 so we handle it specially. */
1906 if (implicit_percent)
1908 struct nameseq *nextf;
1909 const char **targets, **target_pats;
1910 unsigned int c;
1912 if (pattern != 0)
1913 fatal (flocp, _("mixed implicit and static pattern rules"));
1915 /* Count the targets to create an array of target names.
1916 We already have the first one. */
1917 nextf = filenames->next;
1918 free_ns (filenames);
1919 filenames = nextf;
1921 for (c = 1; nextf; ++c, nextf = nextf->next)
1923 targets = xmalloc (c * sizeof (const char *));
1924 target_pats = xmalloc (c * sizeof (const char *));
1926 targets[0] = name;
1927 target_pats[0] = implicit_percent;
1929 c = 1;
1930 while (filenames)
1932 name = filenames->name;
1933 implicit_percent = find_percent_cached (&name);
1935 if (implicit_percent == 0)
1936 fatal (flocp, _("mixed implicit and normal rules"));
1938 targets[c] = name;
1939 target_pats[c] = implicit_percent;
1940 ++c;
1942 nextf = filenames->next;
1943 free_ns (filenames);
1944 filenames = nextf;
1947 create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1949 return;
1953 /* Walk through each target and create it in the database.
1954 We already set up the first target, above. */
1955 while (1)
1957 struct nameseq *nextf = filenames->next;
1958 struct file *f;
1959 struct dep *this = 0;
1961 free_ns (filenames);
1963 /* Check for special targets. Do it here instead of, say, snap_deps()
1964 so that we can immediately use the value. */
1965 if (streq (name, ".POSIX"))
1966 posix_pedantic = 1;
1967 else if (streq (name, ".SECONDEXPANSION"))
1968 second_expansion = 1;
1970 /* If this is a static pattern rule:
1971 `targets: target%pattern: prereq%pattern; recipe',
1972 make sure the pattern matches this target name. */
1973 if (pattern && !pattern_matches (pattern, pattern_percent, name))
1974 error (flocp, _("target `%s' doesn't match the target pattern"), name);
1975 else if (deps)
1976 /* If there are multiple targets, copy the chain DEPS for all but the
1977 last one. It is not safe for the same deps to go in more than one
1978 place in the database. */
1979 this = nextf != 0 ? copy_dep_chain (deps) : deps;
1981 /* Find or create an entry in the file database for this target. */
1982 if (!two_colon)
1984 /* Single-colon. Combine this rule with the file's existing record,
1985 if any. */
1986 f = enter_file (strcache_add (name));
1987 if (f->double_colon)
1988 fatal (flocp,
1989 _("target file `%s' has both : and :: entries"), f->name);
1991 /* If CMDS == F->CMDS, this target was listed in this rule
1992 more than once. Just give a warning since this is harmless. */
1993 if (cmds != 0 && cmds == f->cmds)
1994 error (flocp,
1995 _("target `%s' given more than once in the same rule."),
1996 f->name);
1998 /* Check for two single-colon entries both with commands.
1999 Check is_target so that we don't lose on files such as .c.o
2000 whose commands were preinitialized. */
2001 else if (cmds != 0 && f->cmds != 0 && f->is_target)
2003 error (&cmds->fileinfo,
2004 _("warning: overriding recipe for target `%s'"),
2005 f->name);
2006 error (&f->cmds->fileinfo,
2007 _("warning: ignoring old recipe for target `%s'"),
2008 f->name);
2011 /* Defining .DEFAULT with no deps or cmds clears it. */
2012 if (f == default_file && this == 0 && cmds == 0)
2013 f->cmds = 0;
2014 if (cmds != 0)
2015 f->cmds = cmds;
2017 /* Defining .SUFFIXES with no dependencies clears out the list of
2018 suffixes. */
2019 if (f == suffix_file && this == 0)
2021 free_dep_chain (f->deps);
2022 f->deps = 0;
2025 else
2027 /* Double-colon. Make a new record even if there already is one. */
2028 f = lookup_file (name);
2030 /* Check for both : and :: rules. Check is_target so we don't lose
2031 on default suffix rules or makefiles. */
2032 if (f != 0 && f->is_target && !f->double_colon)
2033 fatal (flocp,
2034 _("target file `%s' has both : and :: entries"), f->name);
2036 f = enter_file (strcache_add (name));
2037 /* If there was an existing entry and it was a double-colon entry,
2038 enter_file will have returned a new one, making it the prev
2039 pointer of the old one, and setting its double_colon pointer to
2040 the first one. */
2041 if (f->double_colon == 0)
2042 /* This is the first entry for this name, so we must set its
2043 double_colon pointer to itself. */
2044 f->double_colon = f;
2046 f->cmds = cmds;
2049 f->is_target = 1;
2051 /* If this is a static pattern rule, set the stem to the part of its
2052 name that matched the `%' in the pattern, so you can use $* in the
2053 commands. If we didn't do it before, enter the prereqs now. */
2054 if (pattern)
2056 static const char *percent = "%";
2057 char *buffer = variable_expand ("");
2058 char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2059 pattern_percent+1, percent+1);
2060 f->stem = strcache_add_len (buffer, o - buffer);
2061 if (this)
2063 if (! this->need_2nd_expansion)
2064 this = enter_prereqs (this, f->stem);
2065 else
2066 this->stem = f->stem;
2070 /* Add the dependencies to this file entry. */
2071 if (this != 0)
2073 /* Add the file's old deps and the new ones in THIS together. */
2074 if (f->deps == 0)
2075 f->deps = this;
2076 else if (cmds != 0)
2078 struct dep *d = this;
2080 /* If this rule has commands, put these deps first. */
2081 while (d->next != 0)
2082 d = d->next;
2084 d->next = f->deps;
2085 f->deps = this;
2087 else
2089 struct dep *d = f->deps;
2091 /* A rule without commands: put its prereqs at the end. */
2092 while (d->next != 0)
2093 d = d->next;
2095 d->next = this;
2099 name = f->name;
2101 /* All done! Set up for the next one. */
2102 if (nextf == 0)
2103 break;
2105 filenames = nextf;
2107 /* Reduce escaped percents. If there are any unescaped it's an error */
2108 name = filenames->name;
2109 if (find_percent_cached (&name))
2110 fatal (flocp, _("mixed implicit and normal rules"));
2114 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2115 Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2116 Quoting backslashes are removed from STRING by compacting it into
2117 itself. Returns a pointer to the first unquoted STOPCHAR if there is
2118 one, or nil if there are none. STOPCHARs inside variable references are
2119 ignored if IGNOREVARS is true.
2121 STOPCHAR _cannot_ be '$' if IGNOREVARS is true. */
2123 static char *
2124 find_char_unquote (char *string, int stop1, int stop2, int blank,
2125 int ignorevars)
2127 unsigned int string_len = 0;
2128 char *p = string;
2130 if (ignorevars)
2131 ignorevars = '$';
2133 while (1)
2135 if (stop2 && blank)
2136 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2137 && ! isblank ((unsigned char) *p))
2138 ++p;
2139 else if (stop2)
2140 while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2141 ++p;
2142 else if (blank)
2143 while (*p != '\0' && *p != ignorevars && *p != stop1
2144 && ! isblank ((unsigned char) *p))
2145 ++p;
2146 else
2147 while (*p != '\0' && *p != ignorevars && *p != stop1)
2148 ++p;
2150 if (*p == '\0')
2151 break;
2153 /* If we stopped due to a variable reference, skip over its contents. */
2154 if (*p == ignorevars)
2156 char openparen = p[1];
2158 p += 2;
2160 /* Skip the contents of a non-quoted, multi-char variable ref. */
2161 if (openparen == '(' || openparen == '{')
2163 unsigned int pcount = 1;
2164 char closeparen = (openparen == '(' ? ')' : '}');
2166 while (*p)
2168 if (*p == openparen)
2169 ++pcount;
2170 else if (*p == closeparen)
2171 if (--pcount == 0)
2173 ++p;
2174 break;
2176 ++p;
2180 /* Skipped the variable reference: look for STOPCHARS again. */
2181 continue;
2184 if (p > string && p[-1] == '\\')
2186 /* Search for more backslashes. */
2187 int i = -2;
2188 while (&p[i] >= string && p[i] == '\\')
2189 --i;
2190 ++i;
2191 /* Only compute the length if really needed. */
2192 if (string_len == 0)
2193 string_len = strlen (string);
2194 /* The number of backslashes is now -I.
2195 Copy P over itself to swallow half of them. */
2196 memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2197 p += i/2;
2198 if (i % 2 == 0)
2199 /* All the backslashes quoted each other; the STOPCHAR was
2200 unquoted. */
2201 return p;
2203 /* The STOPCHAR was quoted by a backslash. Look for another. */
2205 else
2206 /* No backslash in sight. */
2207 return p;
2210 /* Never hit a STOPCHAR or blank (with BLANK nonzero). */
2211 return 0;
2214 /* Search PATTERN for an unquoted % and handle quoting. */
2216 char *
2217 find_percent (char *pattern)
2219 return find_char_unquote (pattern, '%', 0, 0, 0);
2222 /* Search STRING for an unquoted % and handle quoting. Returns a pointer to
2223 the % or NULL if no % was found.
2224 This version is used with strings in the string cache: if there's a need to
2225 modify the string a new version will be added to the string cache and
2226 *STRING will be set to that. */
2228 const char *
2229 find_percent_cached (const char **string)
2231 const char *p = *string;
2232 char *new = 0;
2233 int slen = 0;
2235 /* If the first char is a % return now. This lets us avoid extra tests
2236 inside the loop. */
2237 if (*p == '%')
2238 return p;
2240 while (1)
2242 while (*p != '\0' && *p != '%')
2243 ++p;
2245 if (*p == '\0')
2246 break;
2248 /* See if this % is escaped with a backslash; if not we're done. */
2249 if (p[-1] != '\\')
2250 break;
2253 /* Search for more backslashes. */
2254 char *pv;
2255 int i = -2;
2257 while (&p[i] >= *string && p[i] == '\\')
2258 --i;
2259 ++i;
2261 /* At this point we know we'll need to allocate a new string.
2262 Make a copy if we haven't yet done so. */
2263 if (! new)
2265 slen = strlen (*string);
2266 new = alloca (slen + 1);
2267 memcpy (new, *string, slen + 1);
2268 p = new + (p - *string);
2269 *string = new;
2272 /* At this point *string, p, and new all point into the same string.
2273 Get a non-const version of p so we can modify new. */
2274 pv = new + (p - *string);
2276 /* The number of backslashes is now -I.
2277 Copy P over itself to swallow half of them. */
2278 memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2279 p += i/2;
2281 /* If the backslashes quoted each other; the % was unquoted. */
2282 if (i % 2 == 0)
2283 break;
2287 /* If we had to change STRING, add it to the strcache. */
2288 if (new)
2290 *string = strcache_add (*string);
2291 p = *string + (p - new);
2294 /* If we didn't find a %, return NULL. Otherwise return a ptr to it. */
2295 return (*p == '\0') ? NULL : p;
2298 /* Find the next line of text in an eval buffer, combining continuation lines
2299 into one line.
2300 Return the number of actual lines read (> 1 if continuation lines).
2301 Returns -1 if there's nothing left in the buffer.
2303 After this function, ebuf->buffer points to the first character of the
2304 line we just found.
2307 /* Read a line of text from a STRING.
2308 Since we aren't really reading from a file, don't bother with linenumbers.
2311 static unsigned long
2312 readstring (struct ebuffer *ebuf)
2314 char *eol;
2316 /* If there is nothing left in this buffer, return 0. */
2317 if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2318 return -1;
2320 /* Set up a new starting point for the buffer, and find the end of the
2321 next logical line (taking into account backslash/newline pairs). */
2323 eol = ebuf->buffer = ebuf->bufnext;
2325 while (1)
2327 int backslash = 0;
2328 const char *bol = eol;
2329 const char *p;
2331 /* Find the next newline. At EOS, stop. */
2332 p = eol = strchr (eol , '\n');
2333 if (!eol)
2335 ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2336 return 0;
2339 /* Found a newline; if it's escaped continue; else we're done. */
2340 while (p > bol && *(--p) == '\\')
2341 backslash = !backslash;
2342 if (!backslash)
2343 break;
2344 ++eol;
2347 /* Overwrite the newline char. */
2348 *eol = '\0';
2349 ebuf->bufnext = eol+1;
2351 return 0;
2354 static long
2355 readline (struct ebuffer *ebuf)
2357 char *p;
2358 char *end;
2359 char *start;
2360 long nlines = 0;
2362 /* The behaviors between string and stream buffers are different enough to
2363 warrant different functions. Do the Right Thing. */
2365 if (!ebuf->fp)
2366 return readstring (ebuf);
2368 /* When reading from a file, we always start over at the beginning of the
2369 buffer for each new line. */
2371 p = start = ebuf->bufstart;
2372 end = p + ebuf->size;
2373 *p = '\0';
2375 while (fgets (p, end - p, ebuf->fp) != 0)
2377 char *p2;
2378 unsigned long len;
2379 int backslash;
2381 len = strlen (p);
2382 if (len == 0)
2384 /* This only happens when the first thing on the line is a '\0'.
2385 It is a pretty hopeless case, but (wonder of wonders) Athena
2386 lossage strikes again! (xmkmf puts NULs in its makefiles.)
2387 There is nothing really to be done; we synthesize a newline so
2388 the following line doesn't appear to be part of this line. */
2389 error (&ebuf->floc,
2390 _("warning: NUL character seen; rest of line ignored"));
2391 p[0] = '\n';
2392 len = 1;
2395 /* Jump past the text we just read. */
2396 p += len;
2398 /* If the last char isn't a newline, the whole line didn't fit into the
2399 buffer. Get some more buffer and try again. */
2400 if (p[-1] != '\n')
2401 goto more_buffer;
2403 /* We got a newline, so add one to the count of lines. */
2404 ++nlines;
2406 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2407 /* Check to see if the line was really ended with CRLF; if so ignore
2408 the CR. */
2409 if ((p - start) > 1 && p[-2] == '\r')
2411 --p;
2412 p[-1] = '\n';
2414 #endif
2416 backslash = 0;
2417 for (p2 = p - 2; p2 >= start; --p2)
2419 if (*p2 != '\\')
2420 break;
2421 backslash = !backslash;
2424 if (!backslash)
2426 p[-1] = '\0';
2427 break;
2430 /* It was a backslash/newline combo. If we have more space, read
2431 another line. */
2432 if (end - p >= 80)
2433 continue;
2435 /* We need more space at the end of our buffer, so realloc it.
2436 Make sure to preserve the current offset of p. */
2437 more_buffer:
2439 unsigned long off = p - start;
2440 ebuf->size *= 2;
2441 start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2442 p = start + off;
2443 end = start + ebuf->size;
2444 *p = '\0';
2448 if (ferror (ebuf->fp))
2449 pfatal_with_name (ebuf->floc.filenm);
2451 /* If we found some lines, return how many.
2452 If we didn't, but we did find _something_, that indicates we read the last
2453 line of a file with no final newline; return 1.
2454 If we read nothing, we're at EOF; return -1. */
2456 return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2459 /* Parse the next "makefile word" from the input buffer, and return info
2460 about it.
2462 A "makefile word" is one of:
2464 w_bogus Should never happen
2465 w_eol End of input
2466 w_static A static word; cannot be expanded
2467 w_variable A word containing one or more variables/functions
2468 w_colon A colon
2469 w_dcolon A double-colon
2470 w_semicolon A semicolon
2471 w_varassign A variable assignment operator (=, :=, +=, or ?=)
2473 Note that this function is only used when reading certain parts of the
2474 makefile. Don't use it where special rules hold sway (RHS of a variable,
2475 in a command list, etc.) */
2477 static enum make_word_type
2478 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2480 enum make_word_type wtype = w_bogus;
2481 char *p = buffer, *beg;
2482 char c;
2484 /* Skip any leading whitespace. */
2485 while (isblank ((unsigned char)*p))
2486 ++p;
2488 beg = p;
2489 c = *(p++);
2490 switch (c)
2492 case '\0':
2493 wtype = w_eol;
2494 break;
2496 case ';':
2497 wtype = w_semicolon;
2498 break;
2500 case '=':
2501 wtype = w_varassign;
2502 break;
2504 case ':':
2505 wtype = w_colon;
2506 switch (*p)
2508 case ':':
2509 ++p;
2510 wtype = w_dcolon;
2511 break;
2513 case '=':
2514 ++p;
2515 wtype = w_varassign;
2516 break;
2518 break;
2520 case '+':
2521 case '?':
2522 if (*p == '=')
2524 ++p;
2525 wtype = w_varassign;
2526 break;
2529 default:
2530 if (delim && strchr (delim, c))
2531 wtype = w_static;
2532 break;
2535 /* Did we find something? If so, return now. */
2536 if (wtype != w_bogus)
2537 goto done;
2539 /* This is some non-operator word. A word consists of the longest
2540 string of characters that doesn't contain whitespace, one of [:=#],
2541 or [?+]=, or one of the chars in the DELIM string. */
2543 /* We start out assuming a static word; if we see a variable we'll
2544 adjust our assumptions then. */
2545 wtype = w_static;
2547 /* We already found the first value of "c", above. */
2548 while (1)
2550 char closeparen;
2551 int count;
2553 switch (c)
2555 case '\0':
2556 case ' ':
2557 case '\t':
2558 case '=':
2559 goto done_word;
2561 case ':':
2562 #ifdef HAVE_DOS_PATHS
2563 /* A word CAN include a colon in its drive spec. The drive
2564 spec is allowed either at the beginning of a word, or as part
2565 of the archive member name, like in "libfoo.a(d:/foo/bar.o)". */
2566 if (!(p - beg >= 2
2567 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2568 && (p - beg == 2 || p[-3] == '(')))
2569 #endif
2570 goto done_word;
2572 case '$':
2573 c = *(p++);
2574 if (c == '$')
2575 break;
2577 /* This is a variable reference, so note that it's expandable.
2578 Then read it to the matching close paren. */
2579 wtype = w_variable;
2581 if (c == '(')
2582 closeparen = ')';
2583 else if (c == '{')
2584 closeparen = '}';
2585 else
2586 /* This is a single-letter variable reference. */
2587 break;
2589 for (count=0; *p != '\0'; ++p)
2591 if (*p == c)
2592 ++count;
2593 else if (*p == closeparen && --count < 0)
2595 ++p;
2596 break;
2599 break;
2601 case '?':
2602 case '+':
2603 if (*p == '=')
2604 goto done_word;
2605 break;
2607 case '\\':
2608 switch (*p)
2610 case ':':
2611 case ';':
2612 case '=':
2613 case '\\':
2614 ++p;
2615 break;
2617 break;
2619 default:
2620 if (delim && strchr (delim, c))
2621 goto done_word;
2622 break;
2625 c = *(p++);
2627 done_word:
2628 --p;
2630 done:
2631 if (startp)
2632 *startp = beg;
2633 if (length)
2634 *length = p - beg;
2635 return wtype;
2638 /* Construct the list of include directories
2639 from the arguments and the default list. */
2641 void
2642 construct_include_path (const char **arg_dirs)
2644 #ifdef VAXC /* just don't ask ... */
2645 stat_t stbuf;
2646 #else
2647 struct stat stbuf;
2648 #endif
2649 const char **dirs;
2650 const char **cpp;
2651 unsigned int idx;
2653 /* Compute the number of pointers we need in the table. */
2654 idx = sizeof (default_include_directories) / sizeof (const char *);
2655 if (arg_dirs)
2656 for (cpp = arg_dirs; *cpp != 0; ++cpp)
2657 ++idx;
2659 #ifdef __MSDOS__
2660 /* Add one for $DJDIR. */
2661 ++idx;
2662 #endif
2664 dirs = xmalloc (idx * sizeof (const char *));
2666 idx = 0;
2667 max_incl_len = 0;
2669 /* First consider any dirs specified with -I switches.
2670 Ignore any that don't exist. Remember the maximum string length. */
2672 if (arg_dirs)
2673 while (*arg_dirs != 0)
2675 const char *dir = *(arg_dirs++);
2676 char *expanded = 0;
2677 int e;
2679 if (dir[0] == '~')
2681 expanded = tilde_expand (dir);
2682 if (expanded != 0)
2683 dir = expanded;
2686 EINTRLOOP (e, stat (dir, &stbuf));
2687 if (e == 0 && S_ISDIR (stbuf.st_mode))
2689 unsigned int len = strlen (dir);
2690 /* If dir name is written with trailing slashes, discard them. */
2691 while (len > 1 && dir[len - 1] == '/')
2692 --len;
2693 if (len > max_incl_len)
2694 max_incl_len = len;
2695 dirs[idx++] = strcache_add_len (dir, len);
2698 if (expanded)
2699 free (expanded);
2702 /* Now add the standard default dirs at the end. */
2704 #ifdef __MSDOS__
2706 /* The environment variable $DJDIR holds the root of the DJGPP directory
2707 tree; add ${DJDIR}/include. */
2708 struct variable *djdir = lookup_variable ("DJDIR", 5);
2710 if (djdir)
2712 unsigned int len = strlen (djdir->value) + 8;
2713 char *defdir = alloca (len + 1);
2715 strcat (strcpy (defdir, djdir->value), "/include");
2716 dirs[idx++] = strcache_add (defdir);
2718 if (len > max_incl_len)
2719 max_incl_len = len;
2722 #endif
2724 for (cpp = default_include_directories; *cpp != 0; ++cpp)
2726 int e;
2728 EINTRLOOP (e, stat (*cpp, &stbuf));
2729 if (e == 0 && S_ISDIR (stbuf.st_mode))
2731 unsigned int len = strlen (*cpp);
2732 /* If dir name is written with trailing slashes, discard them. */
2733 while (len > 1 && (*cpp)[len - 1] == '/')
2734 --len;
2735 if (len > max_incl_len)
2736 max_incl_len = len;
2737 dirs[idx++] = strcache_add_len (*cpp, len);
2741 dirs[idx] = 0;
2743 /* Now add each dir to the .INCLUDE_DIRS variable. */
2745 for (cpp = dirs; *cpp != 0; ++cpp)
2746 do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2747 o_default, f_append, 0);
2749 include_directories = dirs;
2752 /* Expand ~ or ~USER at the beginning of NAME.
2753 Return a newly malloc'd string or 0. */
2755 char *
2756 tilde_expand (const char *name)
2758 #ifndef VMS
2759 if (name[1] == '/' || name[1] == '\0')
2761 extern char *getenv ();
2762 char *home_dir;
2763 int is_variable;
2766 /* Turn off --warn-undefined-variables while we expand HOME. */
2767 int save = warn_undefined_variables_flag;
2768 warn_undefined_variables_flag = 0;
2770 home_dir = allocated_variable_expand ("$(HOME)");
2772 warn_undefined_variables_flag = save;
2775 is_variable = home_dir[0] != '\0';
2776 if (!is_variable)
2778 free (home_dir);
2779 home_dir = getenv ("HOME");
2781 # if !defined(_AMIGA) && !defined(WINDOWS32)
2782 if (home_dir == 0 || home_dir[0] == '\0')
2784 extern char *getlogin ();
2785 char *logname = getlogin ();
2786 home_dir = 0;
2787 if (logname != 0)
2789 struct passwd *p = getpwnam (logname);
2790 if (p != 0)
2791 home_dir = p->pw_dir;
2794 # endif /* !AMIGA && !WINDOWS32 */
2795 if (home_dir != 0)
2797 char *new = xstrdup (concat (2, home_dir, name + 1));
2798 if (is_variable)
2799 free (home_dir);
2800 return new;
2803 # if !defined(_AMIGA) && !defined(WINDOWS32)
2804 else
2806 struct passwd *pwent;
2807 char *userend = strchr (name + 1, '/');
2808 if (userend != 0)
2809 *userend = '\0';
2810 pwent = getpwnam (name + 1);
2811 if (pwent != 0)
2813 if (userend == 0)
2814 return xstrdup (pwent->pw_dir);
2815 else
2816 return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2818 else if (userend != 0)
2819 *userend = '/';
2821 # endif /* !AMIGA && !WINDOWS32 */
2822 #endif /* !VMS */
2823 return 0;
2826 /* Parse a string into a sequence of filenames represented as a chain of
2827 struct nameseq's and return that chain. Optionally expand the strings via
2828 glob().
2830 The string is passed as STRINGP, the address of a string pointer.
2831 The string pointer is updated to point at the first character
2832 not parsed, which either is a null char or equals STOPCHAR.
2834 SIZE is how big to construct chain elements.
2835 This is useful if we want them actually to be other structures
2836 that have room for additional info.
2838 PREFIX, if non-null, is added to the beginning of each filename.
2840 FLAGS allows one or more of the following bitflags to be set:
2841 PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2842 PARSEFS_NOGLOB - Do not expand globbing characters
2843 PARSEFS_EXISTS - Only return globbed files that actually exist
2844 (cannot also set NOGLOB)
2845 PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2848 void *
2849 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2850 const char *prefix, int flags)
2852 extern void dir_setup_glob (glob_t *glob);
2854 /* tmp points to tmpbuf after the prefix, if any.
2855 tp is the end of the buffer. */
2856 static char *tmpbuf = NULL;
2857 static int tmpbuf_len = 0;
2859 int cachep = (! (flags & PARSEFS_NOCACHE));
2861 struct nameseq *new = 0;
2862 struct nameseq **newp = &new;
2863 #define NEWELT(_n) do { \
2864 const char *__n = (_n); \
2865 *newp = xcalloc (size); \
2866 (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2867 newp = &(*newp)->next; \
2868 } while(0)
2870 char *p;
2871 glob_t gl;
2872 char *tp;
2874 #ifdef VMS
2875 # define VMS_COMMA ','
2876 #else
2877 # define VMS_COMMA 0
2878 #endif
2880 if (size < sizeof (struct nameseq))
2881 size = sizeof (struct nameseq);
2883 if (! (flags & PARSEFS_NOGLOB))
2884 dir_setup_glob (&gl);
2886 /* Get enough temporary space to construct the largest possible target. */
2888 int l = strlen (*stringp) + 1;
2889 if (l > tmpbuf_len)
2891 tmpbuf = xrealloc (tmpbuf, l);
2892 tmpbuf_len = l;
2895 tp = tmpbuf;
2897 /* Parse STRING. P will always point to the end of the parsed content. */
2898 p = *stringp;
2899 while (1)
2901 const char *name;
2902 const char **nlist = 0;
2903 char *tildep = 0;
2904 #ifndef NO_ARCHIVES
2905 char *arname = 0;
2906 char *memname = 0;
2907 #endif
2908 char *s;
2909 int nlen;
2910 int i;
2912 /* Skip whitespace; at the end of the string or STOPCHAR we're done. */
2913 p = next_token (p);
2914 if (*p == '\0' || *p == stopchar)
2915 break;
2917 /* There are names left, so find the end of the next name.
2918 Throughout this iteration S points to the start. */
2919 s = p;
2920 p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2921 #ifdef VMS
2922 /* convert comma separated list to space separated */
2923 if (p && *p == ',')
2924 *p =' ';
2925 #endif
2926 #ifdef _AMIGA
2927 if (stopchar == ':' && p && *p == ':'
2928 && !(isspace ((unsigned char)p[1]) || !p[1]
2929 || isspace ((unsigned char)p[-1])))
2930 p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2931 #endif
2932 #ifdef HAVE_DOS_PATHS
2933 /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2934 first colon which isn't followed by a slash or a backslash.
2935 Note that tokens separated by spaces should be treated as separate
2936 tokens since make doesn't allow path names with spaces */
2937 if (stopchar == ':')
2938 while (p != 0 && !isspace ((unsigned char)*p) &&
2939 (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2940 p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2941 #endif
2942 if (p == 0)
2943 p = s + strlen (s);
2945 /* Strip leading "this directory" references. */
2946 if (! (flags & PARSEFS_NOSTRIP))
2947 #ifdef VMS
2948 /* Skip leading `[]'s. */
2949 while (p - s > 2 && s[0] == '[' && s[1] == ']')
2950 #else
2951 /* Skip leading `./'s. */
2952 while (p - s > 2 && s[0] == '.' && s[1] == '/')
2953 #endif
2955 /* Skip "./" and all following slashes. */
2956 s += 2;
2957 while (*s == '/')
2958 ++s;
2961 /* Extract the filename just found, and skip it.
2962 Set NAME to the string, and NLEN to its length. */
2964 if (s == p)
2966 /* The name was stripped to empty ("./"). */
2967 #if defined(VMS)
2968 continue;
2969 #elif defined(_AMIGA)
2970 /* PDS-- This cannot be right!! */
2971 tp[0] = '\0';
2972 nlen = 0;
2973 #else
2974 tp[0] = '.';
2975 tp[1] = '/';
2976 tp[2] = '\0';
2977 nlen = 2;
2978 #endif
2980 else
2982 #ifdef VMS
2983 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2984 * to remove this '\' before we can use the filename.
2985 * xstrdup called because S may be read-only string constant.
2987 char *n = tp;
2988 while (s < p)
2990 if (s[0] == '\\' && s[1] == ':')
2991 ++s;
2992 *(n++) = *(s++);
2994 n[0] = '\0';
2995 nlen = strlen (tp);
2996 #else
2997 nlen = p - s;
2998 memcpy (tp, s, nlen);
2999 tp[nlen] = '\0';
3000 #endif
3003 /* At this point, TP points to the element and NLEN is its length. */
3005 #ifndef NO_ARCHIVES
3006 /* If this is the start of an archive group that isn't complete, set up
3007 to add the archive prefix for future files.
3009 TP == TMP means we're not already in an archive group. Ignore
3010 something starting with `(', as that cannot actually be an
3011 archive-member reference (and treating it as such results in an empty
3012 file name, which causes much lossage). Also if it ends in ")" then
3013 it's a complete reference so we don't need to treat it specially. */
3015 if (tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3017 char *n = strchr (tp, '(');
3018 if (n)
3020 /* This is the first element in an open archive group. It looks
3021 like "lib(mem". Remember the close paren. */
3022 nlen -= (n + 1) - tp;
3023 tp = n + 1;
3025 /* If we have just "lib(", part of something like "lib( a b)",
3026 go to the next item. */
3027 if (! nlen)
3028 continue;
3032 /* If we are inside an archive group, make sure it has an end. */
3033 if (tp > tmpbuf)
3035 if (tp[nlen-1] == ')')
3037 /* This is the natural end; reset TP. */
3038 tp = tmpbuf;
3040 /* This is just ")", something like "lib(a b )": skip it. */
3041 if (nlen == 1)
3042 continue;
3044 else
3046 /* Not the end, so add a "fake" end. */
3047 tp[nlen++] = ')';
3048 tp[nlen] = '\0';
3051 #endif
3053 /* If we're not globbing we're done: add it to the end of the chain.
3054 Go to the next item in the string. */
3055 if (flags & PARSEFS_NOGLOB)
3057 NEWELT (concat (2, prefix, tp));
3058 continue;
3061 /* If we get here we know we're doing glob expansion.
3062 TP is a string in tmpbuf. NLEN is no longer used.
3063 We may need to do more work: after this NAME will be set. */
3064 name = tp;
3066 /* Expand tilde if applicable. */
3067 if (tp[0] == '~')
3069 tildep = tilde_expand (tp);
3070 if (tildep != 0)
3071 name = tildep;
3074 #ifndef NO_ARCHIVES
3075 /* If NAME is an archive member reference replace it with the archive
3076 file name, and save the member name in MEMNAME. We will glob on the
3077 archive name and then reattach MEMNAME later. */
3078 if (ar_name (name))
3080 ar_parse_name (name, &arname, &memname);
3081 name = arname;
3083 #endif /* !NO_ARCHIVES */
3085 switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3087 case GLOB_NOSPACE:
3088 fatal (NILF, _("virtual memory exhausted"));
3090 case 0:
3091 /* Success. */
3092 i = gl.gl_pathc;
3093 nlist = (const char **)gl.gl_pathv;
3094 break;
3096 case GLOB_NOMATCH:
3097 /* If we want only existing items, skip this one. */
3098 if (flags & PARSEFS_EXISTS)
3100 i = 0;
3101 break;
3103 /* FALLTHROUGH */
3105 default:
3106 /* By default keep this name. */
3107 i = 1;
3108 nlist = &name;
3109 break;
3112 /* For each matched element, add it to the list. */
3113 while (i-- > 0)
3114 #ifndef NO_ARCHIVES
3115 if (memname != 0)
3117 /* Try to glob on MEMNAME within the archive. */
3118 struct nameseq *found = ar_glob (nlist[i], memname, size);
3119 if (! found)
3120 /* No matches. Use MEMNAME as-is. */
3121 NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3122 else
3124 /* We got a chain of items. Attach them. */
3125 (*newp)->next = found;
3127 /* Find and set the new end. Massage names if necessary. */
3128 while (1)
3130 if (! cachep)
3131 found->name = xstrdup (concat (2, prefix, name));
3132 else if (prefix)
3133 found->name = strcache_add (concat (2, prefix, name));
3135 if (found->next == 0)
3136 break;
3138 found = found->next;
3140 newp = &found->next;
3143 else
3144 #endif /* !NO_ARCHIVES */
3145 NEWELT (concat (2, prefix, nlist[i]));
3147 globfree (&gl);
3149 #ifndef NO_ARCHIVES
3150 if (arname)
3151 free (arname);
3152 #endif
3154 if (tildep)
3155 free (tildep);
3158 *stringp = p;
3159 return new;