a3ad88e4730fea0a6090398ac7bdbe6e2a9f44e5
[platform/upstream/make.git] / read.c
1 /* Reading and parsing of makefiles for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
6
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.
11
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.
15
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/>.  */
18
19 #include "make.h"
20
21 #include <assert.h>
22
23 #include <glob.h>
24
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"
33
34
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 */
44
45 /* A 'struct ebuffer' controls the origin of the makefile we are currently
46    eval'ing.
47 */
48
49 struct ebuffer
50   {
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).  */
57   };
58
59 /* Track the modifiers we can have on variable assignments */
60
61 struct vmodifiers
62   {
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;
69   };
70
71 /* Types of "words" that can be read in a makefile.  */
72 enum make_word_type
73   {
74      w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
75      w_varassign
76   };
77
78
79 /* A `struct conditionals' contains the information describing
80    all the active conditionals in a makefile.
81
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.  */
86
87 struct conditionals
88   {
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'?  */
95   };
96
97 static struct conditionals toplevel_conditionals;
98 static struct conditionals *conditionals = &toplevel_conditionals;
99
100
101 /* Default directories to search for include files in  */
102
103 static const char *default_include_directories[] =
104   {
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
116     0
117   };
118
119 /* List of directories to search for include files in  */
120
121 static const char **include_directories;
122
123 /* Maximum length of an element of the above.  */
124
125 static unsigned int max_incl_len;
126
127 /* The filename and pointer to line number of the
128    makefile currently being read in.  */
129
130 const struct floc *reading_file = 0;
131
132 /* The chain of makefiles read by read_makefile.  */
133
134 static struct dep *read_makefiles = 0;
135
136 static int eval_makefile (const char *filename, int flags);
137 static void eval (struct ebuffer *buffer, int flags);
138
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);
159
160
161 /* Compare a word, both length and contents.
162    P must point to the word to be tested, and WLEN must be the length.
163 */
164 #define word1eq(s)      (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
165
166 \f
167 /* Read in all the makefiles and return the chain of their names.  */
168
169 struct dep *
170 read_all_makefiles (const char **makefiles)
171 {
172   unsigned int num_makefiles = 0;
173
174   /* Create *_LIST variables, to hold the makefiles, targets, and variables
175      we will be reading. */
176
177   define_variable_cname ("MAKEFILE_LIST", "", o_file, 0);
178
179   DB (DB_BASIC, (_("Reading makefiles...\n")));
180
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.  */
184
185   {
186     char *value;
187     char *name, *p;
188     unsigned int length;
189
190     {
191       /* Turn off --warn-undefined-variables while we expand MAKEFILES.  */
192       int save = warn_undefined_variables_flag;
193       warn_undefined_variables_flag = 0;
194
195       value = allocated_variable_expand ("$(MAKEFILES)");
196
197       warn_undefined_variables_flag = save;
198     }
199
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;
203
204     while ((name = find_next_token ((const char **)&p, &length)) != 0)
205       {
206         if (*p != '\0')
207           *p++ = '\0';
208         eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
209       }
210
211     free (value);
212   }
213
214   /* Read makefiles specified with -f switches.  */
215
216   if (makefiles != 0)
217     while (*makefiles != 0)
218       {
219         struct dep *tail = read_makefiles;
220         register struct dep *d;
221
222         if (! eval_makefile (*makefiles, 0))
223           perror_with_name ("", *makefiles);
224
225         /* Find the right element of read_makefiles.  */
226         d = read_makefiles;
227         while (d->next != tail)
228           d = d->next;
229
230         /* Use the storage read_makefile allocates.  */
231         *makefiles = dep_name (d);
232         ++num_makefiles;
233         ++makefiles;
234       }
235
236   /* If there were no -f switches, try the default names.  */
237
238   if (num_makefiles == 0)
239     {
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;
254
255       if (*p != 0)
256         {
257           if (! eval_makefile (*p, 0))
258             perror_with_name ("", *p);
259         }
260       else
261         {
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)
269             {
270               struct dep *d = alloc_dep ();
271               d->file = enter_file (strcache_add (*p));
272               d->dontcare = 1;
273               /* Tell update_goal_chain to bail out as soon as this file is
274                  made, and main not to die if we can't make this file.  */
275               d->changed = RM_DONTCARE;
276               if (tail == 0)
277                 read_makefiles = d;
278               else
279                 tail->next = d;
280               tail = d;
281             }
282           if (tail != 0)
283             tail->next = 0;
284         }
285     }
286
287   return read_makefiles;
288 }
289 \f
290 /* Install a new conditional and return the previous one.  */
291
292 static struct conditionals *
293 install_conditionals (struct conditionals *new)
294 {
295   struct conditionals *save = conditionals;
296
297   memset (new, '\0', sizeof (*new));
298   conditionals = new;
299
300   return save;
301 }
302
303 /* Free the current conditionals and reinstate a saved one.  */
304
305 static void
306 restore_conditionals (struct conditionals *saved)
307 {
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);
313
314   /* Restore state.  */
315   conditionals = saved;
316 }
317 \f
318 static int
319 eval_makefile (const char *filename, int flags)
320 {
321   struct dep *deps;
322   struct ebuffer ebuf;
323   const struct floc *curfile;
324   char *expanded = 0;
325   int makefile_errno;
326
327   filename = strcache_add (filename);
328   ebuf.floc.filenm = filename;
329   ebuf.floc.lineno = 1;
330
331   if (ISDB (DB_VERBOSE))
332     {
333       printf (_("Reading makefile `%s'"), filename);
334       if (flags & RM_NO_DEFAULT_GOAL)
335         printf (_(" (no default goal)"));
336       if (flags & RM_INCLUDED)
337         printf (_(" (search path)"));
338       if (flags & RM_DONTCARE)
339         printf (_(" (don't care)"));
340       if (flags & RM_NO_TILDE)
341         printf (_(" (no ~ expansion)"));
342       puts ("...");
343     }
344
345   /* First, get a stream to read.  */
346
347   /* Expand ~ in FILENAME unless it came from `include',
348      in which case it was already done.  */
349   if (!(flags & RM_NO_TILDE) && filename[0] == '~')
350     {
351       expanded = tilde_expand (filename);
352       if (expanded != 0)
353         filename = expanded;
354     }
355
356   ebuf.fp = fopen (filename, "r");
357   /* Save the error code so we print the right message later.  */
358   makefile_errno = errno;
359
360   /* If the makefile wasn't found and it's either a makefile from
361      the `MAKEFILES' variable or an included makefile,
362      search the included makefile search path for this makefile.  */
363   if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
364     {
365       unsigned int i;
366       for (i = 0; include_directories[i] != 0; ++i)
367         {
368           const char *included = concat (3, include_directories[i],
369                                          "/", filename);
370           ebuf.fp = fopen (included, "r");
371           if (ebuf.fp)
372             {
373               filename = strcache_add (included);
374               break;
375             }
376         }
377     }
378
379   /* Add FILENAME to the chain of read makefiles.  */
380   deps = alloc_dep ();
381   deps->next = read_makefiles;
382   read_makefiles = deps;
383   deps->file = lookup_file (filename);
384   if (deps->file == 0)
385     deps->file = enter_file (filename);
386   filename = deps->file->name;
387   deps->changed = flags;
388   if (flags & RM_DONTCARE)
389     deps->dontcare = 1;
390
391   if (expanded)
392     free (expanded);
393
394   /* If the makefile can't be found at all, give up entirely.  */
395
396   if (ebuf.fp == 0)
397     {
398       /* If we did some searching, errno has the error from the last
399          attempt, rather from FILENAME itself.  Restore it in case the
400          caller wants to use it in a message.  */
401       errno = makefile_errno;
402       return 0;
403     }
404
405   /* Set close-on-exec to avoid leaking the makefile to children, such as
406      $(shell ...).  */
407 #ifdef HAVE_FILENO
408   CLOSE_ON_EXEC (fileno (ebuf.fp));
409 #endif
410
411   /* Add this makefile to the list. */
412   do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
413                           f_append, 0);
414
415   /* Evaluate the makefile */
416
417   ebuf.size = 200;
418   ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);
419
420   curfile = reading_file;
421   reading_file = &ebuf.floc;
422
423   eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));
424
425   reading_file = curfile;
426
427   fclose (ebuf.fp);
428
429   free (ebuf.bufstart);
430   alloca (0);
431
432   return 1;
433 }
434
435 void
436 eval_buffer (char *buffer)
437 {
438   struct ebuffer ebuf;
439   struct conditionals *saved;
440   struct conditionals new;
441   const struct floc *curfile;
442
443   /* Evaluate the buffer */
444
445   ebuf.size = strlen (buffer);
446   ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
447   ebuf.fp = NULL;
448
449   if (reading_file)
450     ebuf.floc = *reading_file;
451   else
452     ebuf.floc.filenm = NULL;
453
454   curfile = reading_file;
455   reading_file = &ebuf.floc;
456
457   saved = install_conditionals (&new);
458
459   eval (&ebuf, 1);
460
461   restore_conditionals (saved);
462
463   reading_file = curfile;
464
465   alloca (0);
466 }
467 \f
468 /* Check LINE to see if it's a variable assignment or undefine.
469
470    It might use one of the modifiers "export", "override", "private", or it
471    might be one of the conditional tokens like "ifdef", "include", etc.
472
473    If it's not a variable assignment or undefine, VMOD.V_ASSIGN is 0.
474    Returns LINE.
475
476    Returns a pointer to the first non-modifier character, and sets VMOD
477    based on the modifiers found if any, plus V_ASSIGN is 1.
478  */
479 static char *
480 parse_var_assignment (const char *line, struct vmodifiers *vmod)
481 {
482   const char *p;
483   memset (vmod, '\0', sizeof (*vmod));
484
485   /* Find the start of the next token.  If there isn't one we're done.  */
486   line = next_token (line);
487   if (*line == '\0')
488     return (char *)line;
489
490   p = line;
491   while (1)
492     {
493       int wlen;
494       const char *p2;
495       enum variable_flavor flavor;
496
497       p2 = parse_variable_definition (p, &flavor);
498
499       /* If this is a variable assignment, we're done.  */
500       if (p2)
501         break;
502
503       /* It's not a variable; see if it's a modifier.  */
504       p2 = end_of_token (p);
505       wlen = p2 - p;
506
507       if (word1eq ("export"))
508         vmod->export_v = 1;
509       else if (word1eq ("override"))
510         vmod->override_v = 1;
511       else if (word1eq ("private"))
512         vmod->private_v = 1;
513       else if (word1eq ("define"))
514         {
515           /* We can't have modifiers after 'define' */
516           vmod->define_v = 1;
517           p = next_token (p2);
518           break;
519         }
520       else if (word1eq ("undefine"))
521         {
522           /* We can't have modifiers after 'undefine' */
523           vmod->undefine_v = 1;
524           p = next_token (p2);
525           break;
526         }
527       else
528         /* Not a variable or modifier: this is not a variable assignment.  */
529         return (char *)line;
530
531       /* It was a modifier.  Try the next word.  */
532       p = next_token (p2);
533       if (*p == '\0')
534         return (char *)line;
535     }
536
537   /* Found a variable assignment or undefine.  */
538   vmod->assign_v = 1;
539   return (char *)p;
540 }
541 \f
542
543 /* Read file FILENAME as a makefile and add its contents to the data base.
544
545    SET_DEFAULT is true if we are allowed to set the default goal.  */
546
547 static void
548 eval (struct ebuffer *ebuf, int set_default)
549 {
550   char *collapsed = 0;
551   unsigned int collapsed_length = 0;
552   unsigned int commands_len = 200;
553   char *commands;
554   unsigned int commands_idx = 0;
555   unsigned int cmds_started, tgts_started;
556   int ignoring = 0, in_ignored_define = 0;
557   int no_targets = 0;           /* Set when reading a rule without targets.  */
558   struct nameseq *filenames = 0;
559   char *depstr = 0;
560   long nlines = 0;
561   int two_colon = 0;
562   const char *pattern = 0;
563   const char *pattern_percent;
564   struct floc *fstart;
565   struct floc fi;
566
567 #define record_waiting_files()                                                \
568   do                                                                          \
569     {                                                                         \
570       if (filenames != 0)                                                     \
571         {                                                                     \
572           fi.lineno = tgts_started;                                           \
573           record_files (filenames, pattern, pattern_percent, depstr,          \
574                         cmds_started, commands, commands_idx, two_colon,      \
575                         &fi);                                                 \
576           filenames = 0;                                                      \
577         }                                                                     \
578       commands_idx = 0;                                                       \
579       no_targets = 0;                                                         \
580       pattern = 0;                                                            \
581     } while (0)
582
583   pattern_percent = 0;
584   cmds_started = tgts_started = 1;
585
586   fstart = &ebuf->floc;
587   fi.filenm = ebuf->floc.filenm;
588
589   /* Loop over lines in the file.
590      The strategy is to accumulate target names in FILENAMES, dependencies
591      in DEPS and commands in COMMANDS.  These are used to define a rule
592      when the start of the next rule (or eof) is encountered.
593
594      When you see a "continue" in the loop below, that means we are moving on
595      to the next line _without_ ending any rule that we happen to be working
596      with at the moment.  If you see a "goto rule_complete", then the
597      statement we just parsed also finishes the previous rule.  */
598
599   commands = xmalloc (200);
600
601   while (1)
602     {
603       unsigned int linelen;
604       char *line;
605       unsigned int wlen;
606       char *p;
607       char *p2;
608       struct vmodifiers vmod;
609
610       /* At the top of this loop, we are starting a brand new line.  */
611       /* Grab the next line to be evaluated */
612       ebuf->floc.lineno += nlines;
613       nlines = readline (ebuf);
614
615       /* If there is nothing left to eval, we're done.  */
616       if (nlines < 0)
617         break;
618
619       /* If this line is empty, skip it.  */
620       line = ebuf->buffer;
621       if (line[0] == '\0')
622         continue;
623
624       linelen = strlen (line);
625
626       /* Check for a shell command line first.
627          If it is not one, we can stop treating tab specially.  */
628       if (line[0] == cmd_prefix)
629         {
630           if (no_targets)
631             /* Ignore the commands in a rule with no targets.  */
632             continue;
633
634           /* If there is no preceding rule line, don't treat this line
635              as a command, even though it begins with a recipe prefix.
636              SunOS 4 make appears to behave this way.  */
637
638           if (filenames != 0)
639             {
640               if (ignoring)
641                 /* Yep, this is a shell command, and we don't care.  */
642                 continue;
643
644               /* Append this command line to the line being accumulated.
645                  Strip command prefix chars that appear after newlines.  */
646               if (commands_idx == 0)
647                 cmds_started = ebuf->floc.lineno;
648
649               if (linelen + commands_idx > commands_len)
650                 {
651                   commands_len = (linelen + commands_idx) * 2;
652                   commands = xrealloc (commands, commands_len);
653                 }
654               p = &commands[commands_idx];
655               p2 = line + 1;
656               while (--linelen)
657                 {
658                   ++commands_idx;
659                   *(p++) = *p2;
660                   if (p2[0] == '\n' && p2[1] == cmd_prefix)
661                     {
662                       ++p2;
663                       --linelen;
664                     }
665                   ++p2;
666                 }
667               *p = '\n';
668               ++commands_idx;
669
670               continue;
671             }
672         }
673
674       /* This line is not a shell command line.  Don't worry about whitespace.
675          Get more space if we need it; we don't need to preserve the current
676          contents of the buffer.  */
677
678       if (collapsed_length < linelen+1)
679         {
680           collapsed_length = linelen+1;
681           if (collapsed)
682             free (collapsed);
683           /* Don't need xrealloc: we don't need to preserve the content.  */
684           collapsed = xmalloc (collapsed_length);
685         }
686       strcpy (collapsed, line);
687       /* Collapse continuation lines.  */
688       collapse_continuations (collapsed);
689       remove_comments (collapsed);
690
691       /* Get rid if starting space (including formfeed, vtab, etc.)  */
692       p = collapsed;
693       while (isspace ((unsigned char)*p))
694         ++p;
695
696       /* See if this is a variable assignment.  We need to do this early, to
697          allow variables with names like 'ifdef', 'export', 'private', etc.  */
698       p = parse_var_assignment(p, &vmod);
699       if (vmod.assign_v)
700         {
701           struct variable *v;
702           enum variable_origin origin = vmod.override_v ? o_override : o_file;
703
704           /* If we're ignoring then we're done now.  */
705           if (ignoring)
706             {
707               if (vmod.define_v)
708                 in_ignored_define = 1;
709               continue;
710             }
711
712           if (vmod.undefine_v)
713           {
714             do_undefine (p, origin, ebuf);
715
716             /* This line has been dealt with.  */
717             goto rule_complete;
718           }
719           else if (vmod.define_v)
720             v = do_define (p, origin, ebuf);
721           else
722             v = try_variable_definition (fstart, p, origin, 0);
723
724           assert (v != NULL);
725
726           if (vmod.export_v)
727             v->export = v_export;
728           if (vmod.private_v)
729             v->private_var = 1;
730
731           /* This line has been dealt with.  */
732           goto rule_complete;
733         }
734
735       /* If this line is completely empty, ignore it.  */
736       if (*p == '\0')
737         continue;
738
739       p2 = end_of_token (p);
740       wlen = p2 - p;
741       p2 = next_token (p2);
742
743       /* If we're in an ignored define, skip this line (but maybe get out).  */
744       if (in_ignored_define)
745         {
746           /* See if this is an endef line (plus optional comment).  */
747           if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
748             in_ignored_define = 0;
749
750           continue;
751         }
752
753       /* Check for conditional state changes.  */
754       {
755         int i = conditional_line (p, wlen, fstart);
756         if (i != -2)
757           {
758             if (i == -1)
759               fatal (fstart, _("invalid syntax in conditional"));
760
761             ignoring = i;
762             continue;
763           }
764       }
765
766       /* Nothing to see here... move along.  */
767       if (ignoring)
768         continue;
769
770       /* Manage the "export" keyword used outside of variable assignment
771          as well as "unexport".  */
772       if (word1eq ("export") || word1eq ("unexport"))
773         {
774           int exporting = *p == 'u' ? 0 : 1;
775
776           /* (un)export by itself causes everything to be (un)exported. */
777           if (*p2 == '\0')
778             export_all_variables = exporting;
779           else
780             {
781               unsigned int l;
782               const char *cp;
783               char *ap;
784
785               /* Expand the line so we can use indirect and constructed
786                  variable names in an (un)export command.  */
787               cp = ap = allocated_variable_expand (p2);
788
789               for (p = find_next_token (&cp, &l); p != 0;
790                    p = find_next_token (&cp, &l))
791                 {
792                   struct variable *v = lookup_variable (p, l);
793                   if (v == 0)
794                     v = define_variable_loc (p, l, "", o_file, 0, fstart);
795                   v->export = exporting ? v_export : v_noexport;
796                 }
797
798               free (ap);
799             }
800           goto rule_complete;
801         }
802
803       /* Handle the special syntax for vpath.  */
804       if (word1eq ("vpath"))
805         {
806           const char *cp;
807           char *vpat;
808           unsigned int l;
809           cp = variable_expand (p2);
810           p = find_next_token (&cp, &l);
811           if (p != 0)
812             {
813               vpat = xstrndup (p, l);
814               p = find_next_token (&cp, &l);
815               /* No searchpath means remove all previous
816                  selective VPATH's with the same pattern.  */
817             }
818           else
819             /* No pattern means remove all previous selective VPATH's.  */
820             vpat = 0;
821           construct_vpath_list (vpat, p);
822           if (vpat != 0)
823             free (vpat);
824
825           goto rule_complete;
826         }
827
828       /* Handle include and variants.  */
829       if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
830         {
831           /* We have found an `include' line specifying a nested
832              makefile to be read at this point.  */
833           struct conditionals *save;
834           struct conditionals new_conditionals;
835           struct nameseq *files;
836           /* "-include" (vs "include") says no error if the file does not
837              exist.  "sinclude" is an alias for this from SGI.  */
838           int noerror = (p[0] != 'i');
839
840           p = allocated_variable_expand (p2);
841
842           /* If no filenames, it's a no-op.  */
843           if (*p == '\0')
844             {
845               free (p);
846               continue;
847             }
848
849           /* Parse the list of file names.  Don't expand archive references!  */
850           p2 = p;
851           files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
852                                   PARSEFS_NOAR);
853           free (p);
854
855           /* Save the state of conditionals and start
856              the included makefile with a clean slate.  */
857           save = install_conditionals (&new_conditionals);
858
859           /* Record the rules that are waiting so they will determine
860              the default goal before those in the included makefile.  */
861           record_waiting_files ();
862
863           /* Read each included makefile.  */
864           while (files != 0)
865             {
866               struct nameseq *next = files->next;
867               const char *name = files->name;
868               int r;
869
870               free_ns (files);
871               files = next;
872
873               r = eval_makefile (name,
874                                  (RM_INCLUDED | RM_NO_TILDE
875                                   | (noerror ? RM_DONTCARE : 0)
876                                   | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
877               if (!r && !noerror)
878                 error (fstart, "%s: %s", name, strerror (errno));
879             }
880
881           /* Restore conditional state.  */
882           restore_conditionals (save);
883
884           goto rule_complete;
885         }
886
887       /* This line starts with a tab but was not caught above because there
888          was no preceding target, and the line might have been usable as a
889          variable definition.  But now we know it is definitely lossage.  */
890       if (line[0] == cmd_prefix)
891         fatal(fstart, _("recipe commences before first target"));
892
893       /* This line describes some target files.  This is complicated by
894          the existence of target-specific variables, because we can't
895          expand the entire line until we know if we have one or not.  So
896          we expand the line word by word until we find the first `:',
897          then check to see if it's a target-specific variable.
898
899          In this algorithm, `lb_next' will point to the beginning of the
900          unexpanded parts of the input buffer, while `p2' points to the
901          parts of the expanded buffer we haven't searched yet. */
902
903       {
904         enum make_word_type wtype;
905         char *cmdleft, *semip, *lb_next;
906         unsigned int plen = 0;
907         char *colonp;
908         const char *end, *beg; /* Helpers for whitespace stripping. */
909
910         /* Record the previous rule.  */
911
912         record_waiting_files ();
913         tgts_started = fstart->lineno;
914
915         /* Search the line for an unquoted ; that is not after an
916            unquoted #.  */
917         cmdleft = find_char_unquote (line, ';', '#', 0, 1);
918         if (cmdleft != 0 && *cmdleft == '#')
919           {
920             /* We found a comment before a semicolon.  */
921             *cmdleft = '\0';
922             cmdleft = 0;
923           }
924         else if (cmdleft != 0)
925           /* Found one.  Cut the line short there before expanding it.  */
926           *(cmdleft++) = '\0';
927         semip = cmdleft;
928
929         collapse_continuations (line);
930
931         /* We can't expand the entire line, since if it's a per-target
932            variable we don't want to expand it.  So, walk from the
933            beginning, expanding as we go, and looking for "interesting"
934            chars.  The first word is always expandable.  */
935         wtype = get_next_mword(line, NULL, &lb_next, &wlen);
936         switch (wtype)
937           {
938           case w_eol:
939             if (cmdleft != 0)
940               fatal(fstart, _("missing rule before recipe"));
941             /* This line contained something but turned out to be nothing
942                but whitespace (a comment?).  */
943             continue;
944
945           case w_colon:
946           case w_dcolon:
947             /* We accept and ignore rules without targets for
948                compatibility with SunOS 4 make.  */
949             no_targets = 1;
950             continue;
951
952           default:
953             break;
954           }
955
956         p2 = variable_expand_string(NULL, lb_next, wlen);
957
958         while (1)
959           {
960             lb_next += wlen;
961             if (cmdleft == 0)
962               {
963                 /* Look for a semicolon in the expanded line.  */
964                 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
965
966                 if (cmdleft != 0)
967                   {
968                     unsigned long p2_off = p2 - variable_buffer;
969                     unsigned long cmd_off = cmdleft - variable_buffer;
970                     char *pend = p2 + strlen(p2);
971
972                     /* Append any remnants of lb, then cut the line short
973                        at the semicolon.  */
974                     *cmdleft = '\0';
975
976                     /* One school of thought says that you shouldn't expand
977                        here, but merely copy, since now you're beyond a ";"
978                        and into a command script.  However, the old parser
979                        expanded the whole line, so we continue that for
980                        backwards-compatiblity.  Also, it wouldn't be
981                        entirely consistent, since we do an unconditional
982                        expand below once we know we don't have a
983                        target-specific variable. */
984                     (void)variable_expand_string(pend, lb_next, (long)-1);
985                     lb_next += strlen(lb_next);
986                     p2 = variable_buffer + p2_off;
987                     cmdleft = variable_buffer + cmd_off + 1;
988                   }
989               }
990
991             colonp = find_char_unquote(p2, ':', 0, 0, 0);
992 #ifdef HAVE_DOS_PATHS
993             /* The drive spec brain-damage strikes again...  */
994             /* Note that the only separators of targets in this context
995                are whitespace and a left paren.  If others are possible,
996                they should be added to the string in the call to index.  */
997             while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
998                    colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
999                    (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
1000               colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
1001 #endif
1002             if (colonp != 0)
1003               break;
1004
1005             wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
1006             if (wtype == w_eol)
1007               break;
1008
1009             p2 += strlen(p2);
1010             *(p2++) = ' ';
1011             p2 = variable_expand_string(p2, lb_next, wlen);
1012             /* We don't need to worry about cmdleft here, because if it was
1013                found in the variable_buffer the entire buffer has already
1014                been expanded... we'll never get here.  */
1015           }
1016
1017         p2 = next_token (variable_buffer);
1018
1019         /* If the word we're looking at is EOL, see if there's _anything_
1020            on the line.  If not, a variable expanded to nothing, so ignore
1021            it.  If so, we can't parse this line so punt.  */
1022         if (wtype == w_eol)
1023           {
1024             if (*p2 != '\0')
1025               /* There's no need to be ivory-tower about this: check for
1026                  one of the most common bugs found in makefiles...  */
1027               fatal (fstart, _("missing separator%s"),
1028                      (cmd_prefix == '\t' && !strneq(line, "        ", 8))
1029                      ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
1030             continue;
1031           }
1032
1033         /* Make the colon the end-of-string so we know where to stop
1034            looking for targets.  */
1035         *colonp = '\0';
1036         filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
1037         *p2 = ':';
1038
1039         if (!filenames)
1040           {
1041             /* We accept and ignore rules without targets for
1042                compatibility with SunOS 4 make.  */
1043             no_targets = 1;
1044             continue;
1045           }
1046         /* This should never be possible; we handled it above.  */
1047         assert (*p2 != '\0');
1048         ++p2;
1049
1050         /* Is this a one-colon or two-colon entry?  */
1051         two_colon = *p2 == ':';
1052         if (two_colon)
1053           p2++;
1054
1055         /* Test to see if it's a target-specific variable.  Copy the rest
1056            of the buffer over, possibly temporarily (we'll expand it later
1057            if it's not a target-specific variable).  PLEN saves the length
1058            of the unparsed section of p2, for later.  */
1059         if (*lb_next != '\0')
1060           {
1061             unsigned int l = p2 - variable_buffer;
1062             plen = strlen (p2);
1063             variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
1064             p2 = variable_buffer + l;
1065           }
1066
1067         p2 = parse_var_assignment (p2, &vmod);
1068         if (vmod.assign_v)
1069           {
1070             /* If there was a semicolon found, add it back, plus anything
1071                after it.  */
1072             if (semip)
1073               {
1074                 unsigned int l = p - variable_buffer;
1075                 *(--semip) = ';';
1076                 collapse_continuations (semip);
1077                 variable_buffer_output (p2 + strlen (p2),
1078                                         semip, strlen (semip)+1);
1079                 p = variable_buffer + l;
1080               }
1081             record_target_var (filenames, p2,
1082                                vmod.override_v ? o_override : o_file,
1083                                &vmod, fstart);
1084             filenames = 0;
1085             continue;
1086           }
1087
1088         /* This is a normal target, _not_ a target-specific variable.
1089            Unquote any = in the dependency list.  */
1090         find_char_unquote (lb_next, '=', 0, 0, 0);
1091
1092         /* We have some targets, so don't ignore the following commands.  */
1093         no_targets = 0;
1094
1095         /* Expand the dependencies, etc.  */
1096         if (*lb_next != '\0')
1097           {
1098             unsigned int l = p2 - variable_buffer;
1099             (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
1100             p2 = variable_buffer + l;
1101
1102             /* Look for a semicolon in the expanded line.  */
1103             if (cmdleft == 0)
1104               {
1105                 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
1106                 if (cmdleft != 0)
1107                   *(cmdleft++) = '\0';
1108               }
1109           }
1110
1111         /* Is this a static pattern rule: `target: %targ: %dep; ...'?  */
1112         p = strchr (p2, ':');
1113         while (p != 0 && p[-1] == '\\')
1114           {
1115             char *q = &p[-1];
1116             int backslash = 0;
1117             while (*q-- == '\\')
1118               backslash = !backslash;
1119             if (backslash)
1120               p = strchr (p + 1, ':');
1121             else
1122               break;
1123           }
1124 #ifdef _AMIGA
1125         /* Here, the situation is quite complicated. Let's have a look
1126            at a couple of targets:
1127
1128            install: dev:make
1129
1130            dev:make: make
1131
1132            dev:make:: xyz
1133
1134            The rule is that it's only a target, if there are TWO :'s
1135            OR a space around the :.
1136         */
1137         if (p && !(isspace ((unsigned char)p[1]) || !p[1]
1138                    || isspace ((unsigned char)p[-1])))
1139           p = 0;
1140 #endif
1141 #ifdef HAVE_DOS_PATHS
1142         {
1143           int check_again;
1144           do {
1145             check_again = 0;
1146             /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
1147             if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
1148                 isalpha ((unsigned char)p[-1]) &&
1149                 (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
1150               p = strchr (p + 1, ':');
1151               check_again = 1;
1152             }
1153           } while (check_again);
1154         }
1155 #endif
1156         if (p != 0)
1157           {
1158             struct nameseq *target;
1159             target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
1160                                      PARSEFS_NOGLOB);
1161             ++p2;
1162             if (target == 0)
1163               fatal (fstart, _("missing target pattern"));
1164             else if (target->next != 0)
1165               fatal (fstart, _("multiple target patterns"));
1166             pattern_percent = find_percent_cached (&target->name);
1167             pattern = target->name;
1168             if (pattern_percent == 0)
1169               fatal (fstart, _("target pattern contains no `%%'"));
1170             free_ns (target);
1171           }
1172         else
1173           pattern = 0;
1174
1175         /* Strip leading and trailing whitespaces. */
1176         beg = p2;
1177         end = beg + strlen (beg) - 1;
1178         strip_whitespace (&beg, &end);
1179
1180         /* Put all the prerequisites here; they'll be parsed later.  */
1181         if (beg <= end && *beg != '\0')
1182           depstr = xstrndup (beg, end - beg + 1);
1183         else
1184           depstr = 0;
1185
1186         commands_idx = 0;
1187         if (cmdleft != 0)
1188           {
1189             /* Semicolon means rest of line is a command.  */
1190             unsigned int l = strlen (cmdleft);
1191
1192             cmds_started = fstart->lineno;
1193
1194             /* Add this command line to the buffer.  */
1195             if (l + 2 > commands_len)
1196               {
1197                 commands_len = (l + 2) * 2;
1198                 commands = xrealloc (commands, commands_len);
1199               }
1200             memcpy (commands, cmdleft, l);
1201             commands_idx += l;
1202             commands[commands_idx++] = '\n';
1203           }
1204
1205         /* Determine if this target should be made default. We used to do
1206            this in record_files() but because of the delayed target recording
1207            and because preprocessor directives are legal in target's commands
1208            it is too late. Consider this fragment for example:
1209
1210            foo:
1211
1212            ifeq ($(.DEFAULT_GOAL),foo)
1213               ...
1214            endif
1215
1216            Because the target is not recorded until after ifeq directive is
1217            evaluated the .DEFAULT_GOAL does not contain foo yet as one
1218            would expect. Because of this we have to move the logic here.  */
1219
1220         if (set_default && default_goal_var->value[0] == '\0')
1221           {
1222             const char *name;
1223             struct dep *d;
1224             struct nameseq *t = filenames;
1225
1226             for (; t != 0; t = t->next)
1227               {
1228                 int reject = 0;
1229                 name = t->name;
1230
1231                 /* We have nothing to do if this is an implicit rule. */
1232                 if (strchr (name, '%') != 0)
1233                   break;
1234
1235                 /* See if this target's name does not start with a `.',
1236                    unless it contains a slash.  */
1237                 if (*name == '.' && strchr (name, '/') == 0
1238 #ifdef HAVE_DOS_PATHS
1239                     && strchr (name, '\\') == 0
1240 #endif
1241                     )
1242                   continue;
1243
1244
1245                 /* If this file is a suffix, don't let it be
1246                    the default goal file.  */
1247                 for (d = suffix_file->deps; d != 0; d = d->next)
1248                   {
1249                     register struct dep *d2;
1250                     if (*dep_name (d) != '.' && streq (name, dep_name (d)))
1251                       {
1252                         reject = 1;
1253                         break;
1254                       }
1255                     for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
1256                       {
1257                         unsigned int l = strlen (dep_name (d2));
1258                         if (!strneq (name, dep_name (d2), l))
1259                           continue;
1260                         if (streq (name + l, dep_name (d)))
1261                           {
1262                             reject = 1;
1263                             break;
1264                           }
1265                       }
1266
1267                     if (reject)
1268                       break;
1269                   }
1270
1271                 if (!reject)
1272                   {
1273                     define_variable_global (".DEFAULT_GOAL", 13, t->name,
1274                                             o_file, 0, NILF);
1275                     break;
1276                   }
1277               }
1278           }
1279
1280         continue;
1281       }
1282
1283       /* We get here except in the case that we just read a rule line.
1284          Record now the last rule we read, so following spurious
1285          commands are properly diagnosed.  */
1286  rule_complete:
1287       record_waiting_files ();
1288     }
1289
1290 #undef  word1eq
1291
1292   if (conditionals->if_cmds)
1293     fatal (fstart, _("missing `endif'"));
1294
1295   /* At eof, record the last rule.  */
1296   record_waiting_files ();
1297
1298   if (collapsed)
1299     free (collapsed);
1300   free (commands);
1301 }
1302 \f
1303
1304 /* Remove comments from LINE.
1305    This is done by copying the text at LINE onto itself.  */
1306
1307 static void
1308 remove_comments (char *line)
1309 {
1310   char *comment;
1311
1312   comment = find_char_unquote (line, '#', 0, 0, 0);
1313
1314   if (comment != 0)
1315     /* Cut off the line at the #.  */
1316     *comment = '\0';
1317 }
1318
1319 /* Execute a `undefine' directive.
1320    The undefine line has already been read, and NAME is the name of
1321    the variable to be undefined. */
1322
1323 static void
1324 do_undefine (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1325 {
1326   char *p, *var;
1327
1328   /* Expand the variable name and find the beginning (NAME) and end.  */
1329   var = allocated_variable_expand (name);
1330   name = next_token (var);
1331   if (*name == '\0')
1332     fatal (&ebuf->floc, _("empty variable name"));
1333   p = name + strlen (name) - 1;
1334   while (p > name && isblank ((unsigned char)*p))
1335     --p;
1336   p[1] = '\0';
1337
1338   undefine_variable_global (name, p - name + 1, origin);
1339   free (var);
1340 }
1341
1342 /* Execute a `define' directive.
1343    The first line has already been read, and NAME is the name of
1344    the variable to be defined.  The following lines remain to be read.  */
1345
1346 static struct variable *
1347 do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
1348 {
1349   struct variable *v;
1350   enum variable_flavor flavor;
1351   struct floc defstart;
1352   int nlevels = 1;
1353   unsigned int length = 100;
1354   char *definition = xmalloc (length);
1355   unsigned int idx = 0;
1356   char *p, *var;
1357
1358   defstart = ebuf->floc;
1359
1360   p = parse_variable_definition (name, &flavor);
1361   if (p == NULL)
1362     /* No assignment token, so assume recursive.  */
1363     flavor = f_recursive;
1364   else
1365     {
1366       if (*(next_token (p)) != '\0')
1367         error (&defstart, _("extraneous text after `define' directive"));
1368
1369       /* Chop the string before the assignment token to get the name.  */
1370       p[flavor == f_recursive ? -1 : -2] = '\0';
1371     }
1372
1373   /* Expand the variable name and find the beginning (NAME) and end.  */
1374   var = allocated_variable_expand (name);
1375   name = next_token (var);
1376   if (*name == '\0')
1377     fatal (&defstart, _("empty variable name"));
1378   p = name + strlen (name) - 1;
1379   while (p > name && isblank ((unsigned char)*p))
1380     --p;
1381   p[1] = '\0';
1382
1383   /* Now read the value of the variable.  */
1384   while (1)
1385     {
1386       unsigned int len;
1387       char *line;
1388       long nlines = readline (ebuf);
1389
1390       /* If there is nothing left to be eval'd, there's no 'endef'!!  */
1391       if (nlines < 0)
1392         fatal (&defstart, _("missing `endef', unterminated `define'"));
1393
1394       ebuf->floc.lineno += nlines;
1395       line = ebuf->buffer;
1396
1397       collapse_continuations (line);
1398
1399       /* If the line doesn't begin with a tab, test to see if it introduces
1400          another define, or ends one.  Stop if we find an 'endef' */
1401       if (line[0] != cmd_prefix)
1402         {
1403           p = next_token (line);
1404           len = strlen (p);
1405
1406           /* If this is another 'define', increment the level count.  */
1407           if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
1408               && strneq (p, "define", 6))
1409             ++nlevels;
1410
1411           /* If this is an 'endef', decrement the count.  If it's now 0,
1412              we've found the last one.  */
1413           else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
1414                    && strneq (p, "endef", 5))
1415             {
1416               p += 5;
1417               remove_comments (p);
1418               if (*(next_token (p)) != '\0')
1419                 error (&ebuf->floc,
1420                        _("extraneous text after `endef' directive"));
1421
1422               if (--nlevels == 0)
1423                 break;
1424             }
1425         }
1426
1427       /* Add this line to the variable definition.  */
1428       len = strlen (line);
1429       if (idx + len + 1 > length)
1430         {
1431           length = (idx + len) * 2;
1432           definition = xrealloc (definition, length + 1);
1433         }
1434
1435       memcpy (&definition[idx], line, len);
1436       idx += len;
1437       /* Separate lines with a newline.  */
1438       definition[idx++] = '\n';
1439     }
1440
1441   /* We've got what we need; define the variable.  */
1442   if (idx == 0)
1443     definition[0] = '\0';
1444   else
1445     definition[idx - 1] = '\0';
1446
1447   v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
1448   free (definition);
1449   free (var);
1450   return (v);
1451 }
1452 \f
1453 /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
1454    "ifneq", "else" and "endif".
1455    LINE is the input line, with the command as its first word.
1456
1457    FILENAME and LINENO are the filename and line number in the
1458    current makefile.  They are used for error messages.
1459
1460    Value is -2 if the line is not a conditional at all,
1461    -1 if the line is an invalid conditional,
1462    0 if following text should be interpreted,
1463    1 if following text should be ignored.  */
1464
1465 static int
1466 conditional_line (char *line, int len, const struct floc *flocp)
1467 {
1468   char *cmdname;
1469   enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
1470   unsigned int i;
1471   unsigned int o;
1472
1473   /* Compare a word, both length and contents. */
1474 #define word1eq(s)      (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
1475 #define chkword(s, t)   if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
1476
1477   /* Make sure this line is a conditional.  */
1478   chkword ("ifdef", c_ifdef)
1479   else chkword ("ifndef", c_ifndef)
1480   else chkword ("ifeq", c_ifeq)
1481   else chkword ("ifneq", c_ifneq)
1482   else chkword ("else", c_else)
1483   else chkword ("endif", c_endif)
1484   else
1485     return -2;
1486
1487   /* Found one: skip past it and any whitespace after it.  */
1488   line = next_token (line + len);
1489
1490 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
1491
1492   /* An 'endif' cannot contain extra text, and reduces the if-depth by 1  */
1493   if (cmdtype == c_endif)
1494     {
1495       if (*line != '\0')
1496         EXTRANEOUS ();
1497
1498       if (!conditionals->if_cmds)
1499         fatal (flocp, _("extraneous `%s'"), cmdname);
1500
1501       --conditionals->if_cmds;
1502
1503       goto DONE;
1504     }
1505
1506   /* An 'else' statement can either be simple, or it can have another
1507      conditional after it.  */
1508   if (cmdtype == c_else)
1509     {
1510       const char *p;
1511
1512       if (!conditionals->if_cmds)
1513         fatal (flocp, _("extraneous `%s'"), cmdname);
1514
1515       o = conditionals->if_cmds - 1;
1516
1517       if (conditionals->seen_else[o])
1518         fatal (flocp, _("only one `else' per conditional"));
1519
1520       /* Change the state of ignorance.  */
1521       switch (conditionals->ignoring[o])
1522         {
1523           case 0:
1524             /* We've just been interpreting.  Never do it again.  */
1525             conditionals->ignoring[o] = 2;
1526             break;
1527           case 1:
1528             /* We've never interpreted yet.  Maybe this time!  */
1529             conditionals->ignoring[o] = 0;
1530             break;
1531         }
1532
1533       /* It's a simple 'else'.  */
1534       if (*line == '\0')
1535         {
1536           conditionals->seen_else[o] = 1;
1537           goto DONE;
1538         }
1539
1540       /* The 'else' has extra text.  That text must be another conditional
1541          and cannot be an 'else' or 'endif'.  */
1542
1543       /* Find the length of the next word.  */
1544       for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
1545         ;
1546       len = p - line;
1547
1548       /* If it's 'else' or 'endif' or an illegal conditional, fail.  */
1549       if (word1eq("else") || word1eq("endif")
1550           || conditional_line (line, len, flocp) < 0)
1551         EXTRANEOUS ();
1552       else
1553         {
1554           /* conditional_line() created a new level of conditional.
1555              Raise it back to this level.  */
1556           if (conditionals->ignoring[o] < 2)
1557             conditionals->ignoring[o] = conditionals->ignoring[o+1];
1558           --conditionals->if_cmds;
1559         }
1560
1561       goto DONE;
1562     }
1563
1564   if (conditionals->allocated == 0)
1565     {
1566       conditionals->allocated = 5;
1567       conditionals->ignoring = xmalloc (conditionals->allocated);
1568       conditionals->seen_else = xmalloc (conditionals->allocated);
1569     }
1570
1571   o = conditionals->if_cmds++;
1572   if (conditionals->if_cmds > conditionals->allocated)
1573     {
1574       conditionals->allocated += 5;
1575       conditionals->ignoring = xrealloc (conditionals->ignoring,
1576                                          conditionals->allocated);
1577       conditionals->seen_else = xrealloc (conditionals->seen_else,
1578                                           conditionals->allocated);
1579     }
1580
1581   /* Record that we have seen an `if...' but no `else' so far.  */
1582   conditionals->seen_else[o] = 0;
1583
1584   /* Search through the stack to see if we're already ignoring.  */
1585   for (i = 0; i < o; ++i)
1586     if (conditionals->ignoring[i])
1587       {
1588         /* We are already ignoring, so just push a level to match the next
1589            "else" or "endif", and keep ignoring.  We don't want to expand
1590            variables in the condition.  */
1591         conditionals->ignoring[o] = 1;
1592         return 1;
1593       }
1594
1595   if (cmdtype == c_ifdef || cmdtype == c_ifndef)
1596     {
1597       char *var;
1598       struct variable *v;
1599       char *p;
1600
1601       /* Expand the thing we're looking up, so we can use indirect and
1602          constructed variable names.  */
1603       var = allocated_variable_expand (line);
1604
1605       /* Make sure there's only one variable name to test.  */
1606       p = end_of_token (var);
1607       i = p - var;
1608       p = next_token (p);
1609       if (*p != '\0')
1610         return -1;
1611
1612       var[i] = '\0';
1613       v = lookup_variable (var, i);
1614
1615       conditionals->ignoring[o] =
1616         ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));
1617
1618       free (var);
1619     }
1620   else
1621     {
1622       /* "ifeq" or "ifneq".  */
1623       char *s1, *s2;
1624       unsigned int l;
1625       char termin = *line == '(' ? ',' : *line;
1626
1627       if (termin != ',' && termin != '"' && termin != '\'')
1628         return -1;
1629
1630       s1 = ++line;
1631       /* Find the end of the first string.  */
1632       if (termin == ',')
1633         {
1634           int count = 0;
1635           for (; *line != '\0'; ++line)
1636             if (*line == '(')
1637               ++count;
1638             else if (*line == ')')
1639               --count;
1640             else if (*line == ',' && count <= 0)
1641               break;
1642         }
1643       else
1644         while (*line != '\0' && *line != termin)
1645           ++line;
1646
1647       if (*line == '\0')
1648         return -1;
1649
1650       if (termin == ',')
1651         {
1652           /* Strip blanks after the first string.  */
1653           char *p = line++;
1654           while (isblank ((unsigned char)p[-1]))
1655             --p;
1656           *p = '\0';
1657         }
1658       else
1659         *line++ = '\0';
1660
1661       s2 = variable_expand (s1);
1662       /* We must allocate a new copy of the expanded string because
1663          variable_expand re-uses the same buffer.  */
1664       l = strlen (s2);
1665       s1 = alloca (l + 1);
1666       memcpy (s1, s2, l + 1);
1667
1668       if (termin != ',')
1669         /* Find the start of the second string.  */
1670         line = next_token (line);
1671
1672       termin = termin == ',' ? ')' : *line;
1673       if (termin != ')' && termin != '"' && termin != '\'')
1674         return -1;
1675
1676       /* Find the end of the second string.  */
1677       if (termin == ')')
1678         {
1679           int count = 0;
1680           s2 = next_token (line);
1681           for (line = s2; *line != '\0'; ++line)
1682             {
1683               if (*line == '(')
1684                 ++count;
1685               else if (*line == ')')
1686                 {
1687                   if (count <= 0)
1688                     break;
1689                   else
1690                     --count;
1691                 }
1692             }
1693         }
1694       else
1695         {
1696           ++line;
1697           s2 = line;
1698           while (*line != '\0' && *line != termin)
1699             ++line;
1700         }
1701
1702       if (*line == '\0')
1703         return -1;
1704
1705       *line = '\0';
1706       line = next_token (++line);
1707       if (*line != '\0')
1708         EXTRANEOUS ();
1709
1710       s2 = variable_expand (s2);
1711       conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
1712     }
1713
1714  DONE:
1715   /* Search through the stack to see if we're ignoring.  */
1716   for (i = 0; i < conditionals->if_cmds; ++i)
1717     if (conditionals->ignoring[i])
1718       return 1;
1719   return 0;
1720 }
1721 \f
1722
1723 /* Record target-specific variable values for files FILENAMES.
1724    TWO_COLON is nonzero if a double colon was used.
1725
1726    The links of FILENAMES are freed, and so are any names in it
1727    that are not incorporated into other data structures.
1728
1729    If the target is a pattern, add the variable to the pattern-specific
1730    variable value list.  */
1731
1732 static void
1733 record_target_var (struct nameseq *filenames, char *defn,
1734                    enum variable_origin origin, struct vmodifiers *vmod,
1735                    const struct floc *flocp)
1736 {
1737   struct nameseq *nextf;
1738   struct variable_set_list *global;
1739
1740   global = current_variable_set_list;
1741
1742   /* If the variable is an append version, store that but treat it as a
1743      normal recursive variable.  */
1744
1745   for (; filenames != 0; filenames = nextf)
1746     {
1747       struct variable *v;
1748       const char *name = filenames->name;
1749       const char *fname;
1750       const char *percent;
1751       struct pattern_var *p;
1752
1753       nextf = filenames->next;
1754       free_ns (filenames);
1755
1756       /* If it's a pattern target, then add it to the pattern-specific
1757          variable list.  */
1758       percent = find_percent_cached (&name);
1759       if (percent)
1760         {
1761           /* Get a reference for this pattern-specific variable struct.  */
1762           p = create_pattern_var (name, percent);
1763           p->variable.fileinfo = *flocp;
1764           /* I don't think this can fail since we already determined it was a
1765              variable definition.  */
1766           v = assign_variable_definition (&p->variable, defn);
1767           assert (v != 0);
1768
1769           v->origin = origin;
1770           if (v->flavor == f_simple)
1771             v->value = allocated_variable_expand (v->value);
1772           else
1773             v->value = xstrdup (v->value);
1774
1775           fname = p->target;
1776         }
1777       else
1778         {
1779           struct file *f;
1780
1781           /* Get a file reference for this file, and initialize it.
1782              We don't want to just call enter_file() because that allocates a
1783              new entry if the file is a double-colon, which we don't want in
1784              this situation.  */
1785           f = lookup_file (name);
1786           if (!f)
1787             f = enter_file (strcache_add (name));
1788           else if (f->double_colon)
1789             f = f->double_colon;
1790
1791           initialize_file_variables (f, 1);
1792           fname = f->name;
1793
1794           current_variable_set_list = f->variables;
1795           v = try_variable_definition (flocp, defn, origin, 1);
1796           if (!v)
1797             fatal (flocp, _("Malformed target-specific variable definition"));
1798           current_variable_set_list = global;
1799         }
1800
1801       /* Set up the variable to be *-specific.  */
1802       v->per_target = 1;
1803       v->private_var = vmod->private_v;
1804       v->export = vmod->export_v ? v_export : v_default;
1805
1806       /* If it's not an override, check to see if there was a command-line
1807          setting.  If so, reset the value.  */
1808       if (v->origin != o_override)
1809         {
1810           struct variable *gv;
1811           int len = strlen(v->name);
1812
1813           gv = lookup_variable (v->name, len);
1814           if (gv && (gv->origin == o_env_override || gv->origin == o_command))
1815             {
1816               if (v->value != 0)
1817                 free (v->value);
1818               v->value = xstrdup (gv->value);
1819               v->origin = gv->origin;
1820               v->recursive = gv->recursive;
1821               v->append = 0;
1822             }
1823         }
1824     }
1825 }
1826 \f
1827 /* Record a description line for files FILENAMES,
1828    with dependencies DEPS, commands to execute described
1829    by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
1830    TWO_COLON is nonzero if a double colon was used.
1831    If not nil, PATTERN is the `%' pattern to make this
1832    a static pattern rule, and PATTERN_PERCENT is a pointer
1833    to the `%' within it.
1834
1835    The links of FILENAMES are freed, and so are any names in it
1836    that are not incorporated into other data structures.  */
1837
1838 static void
1839 record_files (struct nameseq *filenames, const char *pattern,
1840               const char *pattern_percent, char *depstr,
1841               unsigned int cmds_started, char *commands,
1842               unsigned int commands_idx, int two_colon,
1843               const struct floc *flocp)
1844 {
1845   struct commands *cmds;
1846   struct dep *deps;
1847   const char *implicit_percent;
1848   const char *name;
1849
1850   /* If we've already snapped deps, that means we're in an eval being
1851      resolved after the makefiles have been read in.  We can't add more rules
1852      at this time, since they won't get snapped and we'll get core dumps.
1853      See Savannah bug # 12124.  */
1854   if (snapped_deps)
1855     fatal (flocp, _("prerequisites cannot be defined in recipes"));
1856
1857   /* Determine if this is a pattern rule or not.  */
1858   name = filenames->name;
1859   implicit_percent = find_percent_cached (&name);
1860
1861   /* If there's a recipe, set up a struct for it.  */
1862   if (commands_idx > 0)
1863     {
1864       cmds = xmalloc (sizeof (struct commands));
1865       cmds->fileinfo.filenm = flocp->filenm;
1866       cmds->fileinfo.lineno = cmds_started;
1867       cmds->commands = xstrndup (commands, commands_idx);
1868       cmds->command_lines = 0;
1869     }
1870   else
1871      cmds = 0;
1872
1873   /* If there's a prereq string then parse it--unless it's eligible for 2nd
1874      expansion: if so, snap_deps() will do it.  */
1875   if (depstr == 0)
1876     deps = 0;
1877   else if (second_expansion && strchr (depstr, '$'))
1878     {
1879       deps = alloc_dep ();
1880       deps->name = depstr;
1881       deps->need_2nd_expansion = 1;
1882       deps->staticpattern = pattern != 0;
1883     }
1884   else
1885     {
1886       deps = split_prereqs (depstr);
1887       free (depstr);
1888
1889       /* We'll enter static pattern prereqs later when we have the stem.  We
1890          don't want to enter pattern rules at all so that we don't think that
1891          they ought to exist (make manual "Implicit Rule Search Algorithm",
1892          item 5c).  */
1893       if (! pattern && ! implicit_percent)
1894         deps = enter_prereqs (deps, NULL);
1895     }
1896
1897   /* For implicit rules, _all_ the targets must have a pattern.  That means we
1898      can test the first one to see if we're working with an implicit rule; if
1899      so we handle it specially. */
1900
1901   if (implicit_percent)
1902     {
1903       struct nameseq *nextf;
1904       const char **targets, **target_pats;
1905       unsigned int c;
1906
1907       if (pattern != 0)
1908         fatal (flocp, _("mixed implicit and static pattern rules"));
1909
1910       /* Count the targets to create an array of target names.
1911          We already have the first one.  */
1912       nextf = filenames->next;
1913       free_ns (filenames);
1914       filenames = nextf;
1915
1916       for (c = 1; nextf; ++c, nextf = nextf->next)
1917         ;
1918       targets = xmalloc (c * sizeof (const char *));
1919       target_pats = xmalloc (c * sizeof (const char *));
1920
1921       targets[0] = name;
1922       target_pats[0] = implicit_percent;
1923
1924       c = 1;
1925       while (filenames)
1926         {
1927           name = filenames->name;
1928           implicit_percent = find_percent_cached (&name);
1929
1930           if (implicit_percent == 0)
1931             fatal (flocp, _("mixed implicit and normal rules"));
1932
1933           targets[c] = name;
1934           target_pats[c] = implicit_percent;
1935           ++c;
1936
1937           nextf = filenames->next;
1938           free_ns (filenames);
1939           filenames = nextf;
1940         }
1941
1942       create_pattern_rule (targets, target_pats, c, two_colon, deps, cmds, 1);
1943
1944       return;
1945     }
1946
1947
1948   /* Walk through each target and create it in the database.
1949      We already set up the first target, above.  */
1950   while (1)
1951     {
1952       struct nameseq *nextf = filenames->next;
1953       struct file *f;
1954       struct dep *this = 0;
1955
1956       free_ns (filenames);
1957
1958       /* Check for special targets.  Do it here instead of, say, snap_deps()
1959          so that we can immediately use the value.  */
1960       if (streq (name, ".POSIX"))
1961         {
1962           posix_pedantic = 1;
1963           define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
1964         }
1965       else if (streq (name, ".SECONDEXPANSION"))
1966         second_expansion = 1;
1967 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
1968       else if (streq (name, ".ONESHELL"))
1969         one_shell = 1;
1970 #endif
1971
1972       /* If this is a static pattern rule:
1973          `targets: target%pattern: prereq%pattern; recipe',
1974          make sure the pattern matches this target name.  */
1975       if (pattern && !pattern_matches (pattern, pattern_percent, name))
1976         error (flocp, _("target `%s' doesn't match the target pattern"), name);
1977       else if (deps)
1978         /* If there are multiple targets, copy the chain DEPS for all but the
1979            last one.  It is not safe for the same deps to go in more than one
1980            place in the database.  */
1981         this = nextf != 0 ? copy_dep_chain (deps) : deps;
1982
1983       /* Find or create an entry in the file database for this target.  */
1984       if (!two_colon)
1985         {
1986           /* Single-colon.  Combine this rule with the file's existing record,
1987              if any.  */
1988           f = enter_file (strcache_add (name));
1989           if (f->double_colon)
1990             fatal (flocp,
1991                    _("target file `%s' has both : and :: entries"), f->name);
1992
1993           /* If CMDS == F->CMDS, this target was listed in this rule
1994              more than once.  Just give a warning since this is harmless.  */
1995           if (cmds != 0 && cmds == f->cmds)
1996             error (flocp,
1997                    _("target `%s' given more than once in the same rule."),
1998                    f->name);
1999
2000           /* Check for two single-colon entries both with commands.
2001              Check is_target so that we don't lose on files such as .c.o
2002              whose commands were preinitialized.  */
2003           else if (cmds != 0 && f->cmds != 0 && f->is_target)
2004             {
2005               error (&cmds->fileinfo,
2006                      _("warning: overriding recipe for target `%s'"),
2007                      f->name);
2008               error (&f->cmds->fileinfo,
2009                      _("warning: ignoring old recipe for target `%s'"),
2010                      f->name);
2011             }
2012
2013           /* Defining .DEFAULT with no deps or cmds clears it.  */
2014           if (f == default_file && this == 0 && cmds == 0)
2015             f->cmds = 0;
2016           if (cmds != 0)
2017             f->cmds = cmds;
2018
2019           /* Defining .SUFFIXES with no dependencies clears out the list of
2020              suffixes.  */
2021           if (f == suffix_file && this == 0)
2022             {
2023               free_dep_chain (f->deps);
2024               f->deps = 0;
2025             }
2026         }
2027       else
2028         {
2029           /* Double-colon.  Make a new record even if there already is one.  */
2030           f = lookup_file (name);
2031
2032           /* Check for both : and :: rules.  Check is_target so we don't lose
2033              on default suffix rules or makefiles.  */
2034           if (f != 0 && f->is_target && !f->double_colon)
2035             fatal (flocp,
2036                    _("target file `%s' has both : and :: entries"), f->name);
2037
2038           f = enter_file (strcache_add (name));
2039           /* If there was an existing entry and it was a double-colon entry,
2040              enter_file will have returned a new one, making it the prev
2041              pointer of the old one, and setting its double_colon pointer to
2042              the first one.  */
2043           if (f->double_colon == 0)
2044             /* This is the first entry for this name, so we must set its
2045                double_colon pointer to itself.  */
2046             f->double_colon = f;
2047
2048           f->cmds = cmds;
2049         }
2050
2051       f->is_target = 1;
2052
2053       /* If this is a static pattern rule, set the stem to the part of its
2054          name that matched the `%' in the pattern, so you can use $* in the
2055          commands.  If we didn't do it before, enter the prereqs now.  */
2056       if (pattern)
2057         {
2058           static const char *percent = "%";
2059           char *buffer = variable_expand ("");
2060           char *o = patsubst_expand_pat (buffer, name, pattern, percent,
2061                                          pattern_percent+1, percent+1);
2062           f->stem = strcache_add_len (buffer, o - buffer);
2063           if (this)
2064             {
2065               if (! this->need_2nd_expansion)
2066                 this = enter_prereqs (this, f->stem);
2067               else
2068                 this->stem = f->stem;
2069             }
2070         }
2071
2072       /* Add the dependencies to this file entry.  */
2073       if (this != 0)
2074         {
2075           /* Add the file's old deps and the new ones in THIS together.  */
2076           if (f->deps == 0)
2077             f->deps = this;
2078           else if (cmds != 0)
2079             {
2080               struct dep *d = this;
2081
2082               /* If this rule has commands, put these deps first.  */
2083               while (d->next != 0)
2084                 d = d->next;
2085
2086               d->next = f->deps;
2087               f->deps = this;
2088             }
2089           else
2090             {
2091               struct dep *d = f->deps;
2092
2093               /* A rule without commands: put its prereqs at the end.  */
2094               while (d->next != 0)
2095                 d = d->next;
2096
2097               d->next = this;
2098             }
2099         }
2100
2101       name = f->name;
2102
2103       /* All done!  Set up for the next one.  */
2104       if (nextf == 0)
2105         break;
2106
2107       filenames = nextf;
2108
2109       /* Reduce escaped percents.  If there are any unescaped it's an error  */
2110       name = filenames->name;
2111       if (find_percent_cached (&name))
2112         fatal (flocp, _("mixed implicit and normal rules"));
2113     }
2114 }
2115 \f
2116 /* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
2117    Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
2118    Quoting backslashes are removed from STRING by compacting it into
2119    itself.  Returns a pointer to the first unquoted STOPCHAR if there is
2120    one, or nil if there are none.  STOPCHARs inside variable references are
2121    ignored if IGNOREVARS is true.
2122
2123    STOPCHAR _cannot_ be '$' if IGNOREVARS is true.  */
2124
2125 static char *
2126 find_char_unquote (char *string, int stop1, int stop2, int blank,
2127                    int ignorevars)
2128 {
2129   unsigned int string_len = 0;
2130   char *p = string;
2131
2132   if (ignorevars)
2133     ignorevars = '$';
2134
2135   while (1)
2136     {
2137       if (stop2 && blank)
2138         while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
2139                && ! isblank ((unsigned char) *p))
2140           ++p;
2141       else if (stop2)
2142         while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
2143           ++p;
2144       else if (blank)
2145         while (*p != '\0' && *p != ignorevars && *p != stop1
2146                && ! isblank ((unsigned char) *p))
2147           ++p;
2148       else
2149         while (*p != '\0' && *p != ignorevars && *p != stop1)
2150           ++p;
2151
2152       if (*p == '\0')
2153         break;
2154
2155       /* If we stopped due to a variable reference, skip over its contents.  */
2156       if (*p == ignorevars)
2157         {
2158           char openparen = p[1];
2159
2160           p += 2;
2161
2162           /* Skip the contents of a non-quoted, multi-char variable ref.  */
2163           if (openparen == '(' || openparen == '{')
2164             {
2165               unsigned int pcount = 1;
2166               char closeparen = (openparen == '(' ? ')' : '}');
2167
2168               while (*p)
2169                 {
2170                   if (*p == openparen)
2171                     ++pcount;
2172                   else if (*p == closeparen)
2173                     if (--pcount == 0)
2174                       {
2175                         ++p;
2176                         break;
2177                       }
2178                   ++p;
2179                 }
2180             }
2181
2182           /* Skipped the variable reference: look for STOPCHARS again.  */
2183           continue;
2184         }
2185
2186       if (p > string && p[-1] == '\\')
2187         {
2188           /* Search for more backslashes.  */
2189           int i = -2;
2190           while (&p[i] >= string && p[i] == '\\')
2191             --i;
2192           ++i;
2193           /* Only compute the length if really needed.  */
2194           if (string_len == 0)
2195             string_len = strlen (string);
2196           /* The number of backslashes is now -I.
2197              Copy P over itself to swallow half of them.  */
2198           memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
2199           p += i/2;
2200           if (i % 2 == 0)
2201             /* All the backslashes quoted each other; the STOPCHAR was
2202                unquoted.  */
2203             return p;
2204
2205           /* The STOPCHAR was quoted by a backslash.  Look for another.  */
2206         }
2207       else
2208         /* No backslash in sight.  */
2209         return p;
2210     }
2211
2212   /* Never hit a STOPCHAR or blank (with BLANK nonzero).  */
2213   return 0;
2214 }
2215
2216 /* Search PATTERN for an unquoted % and handle quoting.  */
2217
2218 char *
2219 find_percent (char *pattern)
2220 {
2221   return find_char_unquote (pattern, '%', 0, 0, 0);
2222 }
2223
2224 /* Search STRING for an unquoted % and handle quoting.  Returns a pointer to
2225    the % or NULL if no % was found.
2226    This version is used with strings in the string cache: if there's a need to
2227    modify the string a new version will be added to the string cache and
2228    *STRING will be set to that.  */
2229
2230 const char *
2231 find_percent_cached (const char **string)
2232 {
2233   const char *p = *string;
2234   char *new = 0;
2235   int slen = 0;
2236
2237   /* If the first char is a % return now.  This lets us avoid extra tests
2238      inside the loop.  */
2239   if (*p == '%')
2240     return p;
2241
2242   while (1)
2243     {
2244       while (*p != '\0' && *p != '%')
2245         ++p;
2246
2247       if (*p == '\0')
2248         break;
2249
2250       /* See if this % is escaped with a backslash; if not we're done.  */
2251       if (p[-1] != '\\')
2252         break;
2253
2254       {
2255         /* Search for more backslashes.  */
2256         char *pv;
2257         int i = -2;
2258
2259         while (&p[i] >= *string && p[i] == '\\')
2260           --i;
2261         ++i;
2262
2263         /* At this point we know we'll need to allocate a new string.
2264            Make a copy if we haven't yet done so.  */
2265         if (! new)
2266           {
2267             slen = strlen (*string);
2268             new = alloca (slen + 1);
2269             memcpy (new, *string, slen + 1);
2270             p = new + (p - *string);
2271             *string = new;
2272           }
2273
2274         /* At this point *string, p, and new all point into the same string.
2275            Get a non-const version of p so we can modify new.  */
2276         pv = new + (p - *string);
2277
2278         /* The number of backslashes is now -I.
2279            Copy P over itself to swallow half of them.  */
2280         memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
2281         p += i/2;
2282
2283         /* If the backslashes quoted each other; the % was unquoted.  */
2284         if (i % 2 == 0)
2285           break;
2286       }
2287     }
2288
2289   /* If we had to change STRING, add it to the strcache.  */
2290   if (new)
2291     {
2292       *string = strcache_add (*string);
2293       p = *string + (p - new);
2294     }
2295
2296   /* If we didn't find a %, return NULL.  Otherwise return a ptr to it.  */
2297   return (*p == '\0') ? NULL : p;
2298 }
2299 \f
2300 /* Find the next line of text in an eval buffer, combining continuation lines
2301    into one line.
2302    Return the number of actual lines read (> 1 if continuation lines).
2303    Returns -1 if there's nothing left in the buffer.
2304
2305    After this function, ebuf->buffer points to the first character of the
2306    line we just found.
2307  */
2308
2309 /* Read a line of text from a STRING.
2310    Since we aren't really reading from a file, don't bother with linenumbers.
2311  */
2312
2313 static unsigned long
2314 readstring (struct ebuffer *ebuf)
2315 {
2316   char *eol;
2317
2318   /* If there is nothing left in this buffer, return 0.  */
2319   if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
2320     return -1;
2321
2322   /* Set up a new starting point for the buffer, and find the end of the
2323      next logical line (taking into account backslash/newline pairs).  */
2324
2325   eol = ebuf->buffer = ebuf->bufnext;
2326
2327   while (1)
2328     {
2329       int backslash = 0;
2330       const char *bol = eol;
2331       const char *p;
2332
2333       /* Find the next newline.  At EOS, stop.  */
2334       p = eol = strchr (eol , '\n');
2335       if (!eol)
2336         {
2337           ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
2338           return 0;
2339         }
2340
2341       /* Found a newline; if it's escaped continue; else we're done.  */
2342       while (p > bol && *(--p) == '\\')
2343         backslash = !backslash;
2344       if (!backslash)
2345         break;
2346       ++eol;
2347     }
2348
2349   /* Overwrite the newline char.  */
2350   *eol = '\0';
2351   ebuf->bufnext = eol+1;
2352
2353   return 0;
2354 }
2355
2356 static long
2357 readline (struct ebuffer *ebuf)
2358 {
2359   char *p;
2360   char *end;
2361   char *start;
2362   long nlines = 0;
2363
2364   /* The behaviors between string and stream buffers are different enough to
2365      warrant different functions.  Do the Right Thing.  */
2366
2367   if (!ebuf->fp)
2368     return readstring (ebuf);
2369
2370   /* When reading from a file, we always start over at the beginning of the
2371      buffer for each new line.  */
2372
2373   p = start = ebuf->bufstart;
2374   end = p + ebuf->size;
2375   *p = '\0';
2376
2377   while (fgets (p, end - p, ebuf->fp) != 0)
2378     {
2379       char *p2;
2380       unsigned long len;
2381       int backslash;
2382
2383       len = strlen (p);
2384       if (len == 0)
2385         {
2386           /* This only happens when the first thing on the line is a '\0'.
2387              It is a pretty hopeless case, but (wonder of wonders) Athena
2388              lossage strikes again!  (xmkmf puts NULs in its makefiles.)
2389              There is nothing really to be done; we synthesize a newline so
2390              the following line doesn't appear to be part of this line.  */
2391           error (&ebuf->floc,
2392                  _("warning: NUL character seen; rest of line ignored"));
2393           p[0] = '\n';
2394           len = 1;
2395         }
2396
2397       /* Jump past the text we just read.  */
2398       p += len;
2399
2400       /* If the last char isn't a newline, the whole line didn't fit into the
2401          buffer.  Get some more buffer and try again.  */
2402       if (p[-1] != '\n')
2403         goto more_buffer;
2404
2405       /* We got a newline, so add one to the count of lines.  */
2406       ++nlines;
2407
2408 #if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
2409       /* Check to see if the line was really ended with CRLF; if so ignore
2410          the CR.  */
2411       if ((p - start) > 1 && p[-2] == '\r')
2412         {
2413           --p;
2414           p[-1] = '\n';
2415         }
2416 #endif
2417
2418       backslash = 0;
2419       for (p2 = p - 2; p2 >= start; --p2)
2420         {
2421           if (*p2 != '\\')
2422             break;
2423           backslash = !backslash;
2424         }
2425
2426       if (!backslash)
2427         {
2428           p[-1] = '\0';
2429           break;
2430         }
2431
2432       /* It was a backslash/newline combo.  If we have more space, read
2433          another line.  */
2434       if (end - p >= 80)
2435         continue;
2436
2437       /* We need more space at the end of our buffer, so realloc it.
2438          Make sure to preserve the current offset of p.  */
2439     more_buffer:
2440       {
2441         unsigned long off = p - start;
2442         ebuf->size *= 2;
2443         start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
2444         p = start + off;
2445         end = start + ebuf->size;
2446         *p = '\0';
2447       }
2448     }
2449
2450   if (ferror (ebuf->fp))
2451     pfatal_with_name (ebuf->floc.filenm);
2452
2453   /* If we found some lines, return how many.
2454      If we didn't, but we did find _something_, that indicates we read the last
2455      line of a file with no final newline; return 1.
2456      If we read nothing, we're at EOF; return -1.  */
2457
2458   return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
2459 }
2460 \f
2461 /* Parse the next "makefile word" from the input buffer, and return info
2462    about it.
2463
2464    A "makefile word" is one of:
2465
2466      w_bogus        Should never happen
2467      w_eol          End of input
2468      w_static       A static word; cannot be expanded
2469      w_variable     A word containing one or more variables/functions
2470      w_colon        A colon
2471      w_dcolon       A double-colon
2472      w_semicolon    A semicolon
2473      w_varassign    A variable assignment operator (=, :=, +=, or ?=)
2474
2475    Note that this function is only used when reading certain parts of the
2476    makefile.  Don't use it where special rules hold sway (RHS of a variable,
2477    in a command list, etc.)  */
2478
2479 static enum make_word_type
2480 get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
2481 {
2482   enum make_word_type wtype = w_bogus;
2483   char *p = buffer, *beg;
2484   char c;
2485
2486   /* Skip any leading whitespace.  */
2487   while (isblank ((unsigned char)*p))
2488     ++p;
2489
2490   beg = p;
2491   c = *(p++);
2492   switch (c)
2493     {
2494     case '\0':
2495       wtype = w_eol;
2496       break;
2497
2498     case ';':
2499       wtype = w_semicolon;
2500       break;
2501
2502     case '=':
2503       wtype = w_varassign;
2504       break;
2505
2506     case ':':
2507       wtype = w_colon;
2508       switch (*p)
2509         {
2510         case ':':
2511           ++p;
2512           wtype = w_dcolon;
2513           break;
2514
2515         case '=':
2516           ++p;
2517           wtype = w_varassign;
2518           break;
2519         }
2520       break;
2521
2522     case '+':
2523     case '?':
2524       if (*p == '=')
2525         {
2526           ++p;
2527           wtype = w_varassign;
2528           break;
2529         }
2530
2531     default:
2532       if (delim && strchr (delim, c))
2533         wtype = w_static;
2534       break;
2535     }
2536
2537   /* Did we find something?  If so, return now.  */
2538   if (wtype != w_bogus)
2539     goto done;
2540
2541   /* This is some non-operator word.  A word consists of the longest
2542      string of characters that doesn't contain whitespace, one of [:=#],
2543      or [?+]=, or one of the chars in the DELIM string.  */
2544
2545   /* We start out assuming a static word; if we see a variable we'll
2546      adjust our assumptions then.  */
2547   wtype = w_static;
2548
2549   /* We already found the first value of "c", above.  */
2550   while (1)
2551     {
2552       char closeparen;
2553       int count;
2554
2555       switch (c)
2556         {
2557         case '\0':
2558         case ' ':
2559         case '\t':
2560         case '=':
2561           goto done_word;
2562
2563         case ':':
2564 #ifdef HAVE_DOS_PATHS
2565           /* A word CAN include a colon in its drive spec.  The drive
2566              spec is allowed either at the beginning of a word, or as part
2567              of the archive member name, like in "libfoo.a(d:/foo/bar.o)".  */
2568           if (!(p - beg >= 2
2569                 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
2570                 && (p - beg == 2 || p[-3] == '(')))
2571 #endif
2572           goto done_word;
2573
2574         case '$':
2575           c = *(p++);
2576           if (c == '$')
2577             break;
2578
2579           /* This is a variable reference, so note that it's expandable.
2580              Then read it to the matching close paren.  */
2581           wtype = w_variable;
2582
2583           if (c == '(')
2584             closeparen = ')';
2585           else if (c == '{')
2586             closeparen = '}';
2587           else
2588             /* This is a single-letter variable reference.  */
2589             break;
2590
2591           for (count=0; *p != '\0'; ++p)
2592             {
2593               if (*p == c)
2594                 ++count;
2595               else if (*p == closeparen && --count < 0)
2596                 {
2597                   ++p;
2598                   break;
2599                 }
2600             }
2601           break;
2602
2603         case '?':
2604         case '+':
2605           if (*p == '=')
2606             goto done_word;
2607           break;
2608
2609         case '\\':
2610           switch (*p)
2611             {
2612             case ':':
2613             case ';':
2614             case '=':
2615             case '\\':
2616               ++p;
2617               break;
2618             }
2619           break;
2620
2621         default:
2622           if (delim && strchr (delim, c))
2623             goto done_word;
2624           break;
2625         }
2626
2627       c = *(p++);
2628     }
2629  done_word:
2630   --p;
2631
2632  done:
2633   if (startp)
2634     *startp = beg;
2635   if (length)
2636     *length = p - beg;
2637   return wtype;
2638 }
2639 \f
2640 /* Construct the list of include directories
2641    from the arguments and the default list.  */
2642
2643 void
2644 construct_include_path (const char **arg_dirs)
2645 {
2646 #ifdef VAXC             /* just don't ask ... */
2647   stat_t stbuf;
2648 #else
2649   struct stat stbuf;
2650 #endif
2651   const char **dirs;
2652   const char **cpp;
2653   unsigned int idx;
2654
2655   /* Compute the number of pointers we need in the table.  */
2656   idx = sizeof (default_include_directories) / sizeof (const char *);
2657   if (arg_dirs)
2658     for (cpp = arg_dirs; *cpp != 0; ++cpp)
2659       ++idx;
2660
2661 #ifdef  __MSDOS__
2662   /* Add one for $DJDIR.  */
2663   ++idx;
2664 #endif
2665
2666   dirs = xmalloc (idx * sizeof (const char *));
2667
2668   idx = 0;
2669   max_incl_len = 0;
2670
2671   /* First consider any dirs specified with -I switches.
2672      Ignore any that don't exist.  Remember the maximum string length.  */
2673
2674   if (arg_dirs)
2675     while (*arg_dirs != 0)
2676       {
2677         const char *dir = *(arg_dirs++);
2678         char *expanded = 0;
2679         int e;
2680
2681         if (dir[0] == '~')
2682           {
2683             expanded = tilde_expand (dir);
2684             if (expanded != 0)
2685               dir = expanded;
2686           }
2687
2688         EINTRLOOP (e, stat (dir, &stbuf));
2689         if (e == 0 && S_ISDIR (stbuf.st_mode))
2690           {
2691             unsigned int len = strlen (dir);
2692             /* If dir name is written with trailing slashes, discard them.  */
2693             while (len > 1 && dir[len - 1] == '/')
2694               --len;
2695             if (len > max_incl_len)
2696               max_incl_len = len;
2697             dirs[idx++] = strcache_add_len (dir, len);
2698           }
2699
2700         if (expanded)
2701           free (expanded);
2702       }
2703
2704   /* Now add the standard default dirs at the end.  */
2705
2706 #ifdef  __MSDOS__
2707   {
2708     /* The environment variable $DJDIR holds the root of the DJGPP directory
2709        tree; add ${DJDIR}/include.  */
2710     struct variable *djdir = lookup_variable ("DJDIR", 5);
2711
2712     if (djdir)
2713       {
2714         unsigned int len = strlen (djdir->value) + 8;
2715         char *defdir = alloca (len + 1);
2716
2717         strcat (strcpy (defdir, djdir->value), "/include");
2718         dirs[idx++] = strcache_add (defdir);
2719
2720         if (len > max_incl_len)
2721           max_incl_len = len;
2722       }
2723   }
2724 #endif
2725
2726   for (cpp = default_include_directories; *cpp != 0; ++cpp)
2727     {
2728       int e;
2729
2730       EINTRLOOP (e, stat (*cpp, &stbuf));
2731       if (e == 0 && S_ISDIR (stbuf.st_mode))
2732         {
2733           unsigned int len = strlen (*cpp);
2734           /* If dir name is written with trailing slashes, discard them.  */
2735           while (len > 1 && (*cpp)[len - 1] == '/')
2736             --len;
2737           if (len > max_incl_len)
2738             max_incl_len = len;
2739           dirs[idx++] = strcache_add_len (*cpp, len);
2740         }
2741     }
2742
2743   dirs[idx] = 0;
2744
2745   /* Now add each dir to the .INCLUDE_DIRS variable.  */
2746
2747   for (cpp = dirs; *cpp != 0; ++cpp)
2748     do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
2749                             o_default, f_append, 0);
2750
2751   include_directories = dirs;
2752 }
2753 \f
2754 /* Expand ~ or ~USER at the beginning of NAME.
2755    Return a newly malloc'd string or 0.  */
2756
2757 char *
2758 tilde_expand (const char *name)
2759 {
2760 #ifndef VMS
2761   if (name[1] == '/' || name[1] == '\0')
2762     {
2763       extern char *getenv ();
2764       char *home_dir;
2765       int is_variable;
2766
2767       {
2768         /* Turn off --warn-undefined-variables while we expand HOME.  */
2769         int save = warn_undefined_variables_flag;
2770         warn_undefined_variables_flag = 0;
2771
2772         home_dir = allocated_variable_expand ("$(HOME)");
2773
2774         warn_undefined_variables_flag = save;
2775       }
2776
2777       is_variable = home_dir[0] != '\0';
2778       if (!is_variable)
2779         {
2780           free (home_dir);
2781           home_dir = getenv ("HOME");
2782         }
2783 # if !defined(_AMIGA) && !defined(WINDOWS32)
2784       if (home_dir == 0 || home_dir[0] == '\0')
2785         {
2786           extern char *getlogin ();
2787           char *logname = getlogin ();
2788           home_dir = 0;
2789           if (logname != 0)
2790             {
2791               struct passwd *p = getpwnam (logname);
2792               if (p != 0)
2793                 home_dir = p->pw_dir;
2794             }
2795         }
2796 # endif /* !AMIGA && !WINDOWS32 */
2797       if (home_dir != 0)
2798         {
2799           char *new = xstrdup (concat (2, home_dir, name + 1));
2800           if (is_variable)
2801             free (home_dir);
2802           return new;
2803         }
2804     }
2805 # if !defined(_AMIGA) && !defined(WINDOWS32)
2806   else
2807     {
2808       struct passwd *pwent;
2809       char *userend = strchr (name + 1, '/');
2810       if (userend != 0)
2811         *userend = '\0';
2812       pwent = getpwnam (name + 1);
2813       if (pwent != 0)
2814         {
2815           if (userend == 0)
2816             return xstrdup (pwent->pw_dir);
2817           else
2818             return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
2819         }
2820       else if (userend != 0)
2821         *userend = '/';
2822     }
2823 # endif /* !AMIGA && !WINDOWS32 */
2824 #endif /* !VMS */
2825   return 0;
2826 }
2827 \f
2828 /* Parse a string into a sequence of filenames represented as a chain of
2829    struct nameseq's and return that chain.  Optionally expand the strings via
2830    glob().
2831
2832    The string is passed as STRINGP, the address of a string pointer.
2833    The string pointer is updated to point at the first character
2834    not parsed, which either is a null char or equals STOPCHAR.
2835
2836    SIZE is how big to construct chain elements.
2837    This is useful if we want them actually to be other structures
2838    that have room for additional info.
2839
2840    PREFIX, if non-null, is added to the beginning of each filename.
2841
2842    FLAGS allows one or more of the following bitflags to be set:
2843         PARSEFS_NOSTRIP - Do no strip './'s off the beginning
2844         PARSEFS_NOAR    - Do not check filenames for archive references
2845         PARSEFS_NOGLOB  - Do not expand globbing characters
2846         PARSEFS_EXISTS  - Only return globbed files that actually exist
2847                           (cannot also set NOGLOB)
2848         PARSEFS_NOCACHE - Do not add filenames to the strcache (caller frees)
2849   */
2850
2851 void *
2852 parse_file_seq (char **stringp, unsigned int size, int stopchar,
2853                 const char *prefix, int flags)
2854 {
2855   extern void dir_setup_glob (glob_t *glob);
2856
2857   /* tmp points to tmpbuf after the prefix, if any.
2858      tp is the end of the buffer. */
2859   static char *tmpbuf = NULL;
2860   static int tmpbuf_len = 0;
2861
2862   int cachep = (! (flags & PARSEFS_NOCACHE));
2863
2864   struct nameseq *new = 0;
2865   struct nameseq **newp = &new;
2866 #define NEWELT(_n)  do { \
2867                         const char *__n = (_n); \
2868                         *newp = xcalloc (size); \
2869                         (*newp)->name = (cachep ? strcache_add (__n) : xstrdup (__n)); \
2870                         newp = &(*newp)->next; \
2871                     } while(0)
2872
2873   char *p;
2874   glob_t gl;
2875   char *tp;
2876
2877 #ifdef VMS
2878 # define VMS_COMMA ','
2879 #else
2880 # define VMS_COMMA 0
2881 #endif
2882
2883   if (size < sizeof (struct nameseq))
2884     size = sizeof (struct nameseq);
2885
2886   if (! (flags & PARSEFS_NOGLOB))
2887     dir_setup_glob (&gl);
2888
2889   /* Get enough temporary space to construct the largest possible target.  */
2890   {
2891     int l = strlen (*stringp) + 1;
2892     if (l > tmpbuf_len)
2893       {
2894         tmpbuf = xrealloc (tmpbuf, l);
2895         tmpbuf_len = l;
2896       }
2897   }
2898   tp = tmpbuf;
2899
2900   /* Parse STRING.  P will always point to the end of the parsed content.  */
2901   p = *stringp;
2902   while (1)
2903     {
2904       const char *name;
2905       const char **nlist = 0;
2906       char *tildep = 0;
2907 #ifndef NO_ARCHIVES
2908       char *arname = 0;
2909       char *memname = 0;
2910 #endif
2911       char *s;
2912       int nlen;
2913       int i;
2914
2915       /* Skip whitespace; at the end of the string or STOPCHAR we're done.  */
2916       p = next_token (p);
2917       if (*p == '\0' || *p == stopchar)
2918         break;
2919
2920       /* There are names left, so find the end of the next name.
2921          Throughout this iteration S points to the start.  */
2922       s = p;
2923       p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
2924 #ifdef VMS
2925         /* convert comma separated list to space separated */
2926       if (p && *p == ',')
2927         *p =' ';
2928 #endif
2929 #ifdef _AMIGA
2930       if (stopchar == ':' && p && *p == ':'
2931           && !(isspace ((unsigned char)p[1]) || !p[1]
2932                || isspace ((unsigned char)p[-1])))
2933         p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
2934 #endif
2935 #ifdef HAVE_DOS_PATHS
2936     /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
2937        first colon which isn't followed by a slash or a backslash.
2938        Note that tokens separated by spaces should be treated as separate
2939        tokens since make doesn't allow path names with spaces */
2940     if (stopchar == ':')
2941       while (p != 0 && !isspace ((unsigned char)*p) &&
2942              (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
2943         p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
2944 #endif
2945       if (p == 0)
2946         p = s + strlen (s);
2947
2948       /* Strip leading "this directory" references.  */
2949       if (! (flags & PARSEFS_NOSTRIP))
2950 #ifdef VMS
2951         /* Skip leading `[]'s.  */
2952         while (p - s > 2 && s[0] == '[' && s[1] == ']')
2953 #else
2954         /* Skip leading `./'s.  */
2955         while (p - s > 2 && s[0] == '.' && s[1] == '/')
2956 #endif
2957           {
2958             /* Skip "./" and all following slashes.  */
2959             s += 2;
2960             while (*s == '/')
2961               ++s;
2962           }
2963
2964       /* Extract the filename just found, and skip it.
2965          Set NAME to the string, and NLEN to its length.  */
2966
2967       if (s == p)
2968         {
2969         /* The name was stripped to empty ("./"). */
2970 #if defined(VMS)
2971           continue;
2972 #elif defined(_AMIGA)
2973           /* PDS-- This cannot be right!! */
2974           tp[0] = '\0';
2975           nlen = 0;
2976 #else
2977           tp[0] = '.';
2978           tp[1] = '/';
2979           tp[2] = '\0';
2980           nlen = 2;
2981 #endif
2982         }
2983       else
2984         {
2985 #ifdef VMS
2986 /* VMS filenames can have a ':' in them but they have to be '\'ed but we need
2987  *  to remove this '\' before we can use the filename.
2988  * xstrdup called because S may be read-only string constant.
2989  */
2990           char *n = tp;
2991           while (s < p)
2992             {
2993               if (s[0] == '\\' && s[1] == ':')
2994                 ++s;
2995               *(n++) = *(s++);
2996             }
2997           n[0] = '\0';
2998           nlen = strlen (tp);
2999 #else
3000           nlen = p - s;
3001           memcpy (tp, s, nlen);
3002           tp[nlen] = '\0';
3003 #endif
3004         }
3005
3006       /* At this point, TP points to the element and NLEN is its length.  */
3007
3008 #ifndef NO_ARCHIVES
3009       /* If this is the start of an archive group that isn't complete, set up
3010          to add the archive prefix for future files.  A file list like:
3011          "libf.a(x.o y.o z.o)" needs to be expanded as:
3012          "libf.a(x.o) libf.a(y.o) libf.a(z.o)"
3013
3014          TP == TMP means we're not already in an archive group.  Ignore
3015          something starting with `(', as that cannot actually be an
3016          archive-member reference (and treating it as such results in an empty
3017          file name, which causes much lossage).  Also if it ends in ")" then
3018          it's a complete reference so we don't need to treat it specially.
3019
3020          Finally, note that archive groups must end with ')' as the last
3021          character, so ensure there's some word ending like that before
3022          considering this an archive group.  */
3023       if (! (flags & PARSEFS_NOAR)
3024           && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
3025         {
3026           char *n = strchr (tp, '(');
3027           if (n)
3028             {
3029               /* This looks like the first element in an open archive group.
3030                  A valid group MUST have ')' as the last character.  */
3031               const char *e = p + nlen;
3032               do
3033                 {
3034                   e = next_token (e);
3035                   /* Find the end of this word.  We don't want to unquote and
3036                      we don't care about quoting since we're looking for the
3037                      last char in the word. */
3038                   while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
3039                          && ! isblank ((unsigned char) *e))
3040                     ++e;
3041                   if (e[-1] == ')')
3042                     {
3043                       /* Found the end, so this is the first element in an
3044                          open archive group.  It looks like "lib(mem".
3045                          Reset TP past the open paren.  */
3046                       nlen -= (n + 1) - tp;
3047                       tp = n + 1;
3048
3049                       /* If we have just "lib(", part of something like
3050                          "lib( a b)", go to the next item.  */
3051                       if (! nlen)
3052                         continue;
3053
3054                       /* We can stop looking now.  */
3055                       break;
3056                     }
3057                 }
3058               while (*e != '\0');
3059             }
3060         }
3061
3062       /* If we are inside an archive group, make sure it has an end.  */
3063       if (tp > tmpbuf)
3064         {
3065           if (tp[nlen-1] == ')')
3066             {
3067               /* This is the natural end; reset TP.  */
3068               tp = tmpbuf;
3069
3070               /* This is just ")", something like "lib(a b )": skip it.  */
3071               if (nlen == 1)
3072                 continue;
3073             }
3074           else
3075             {
3076               /* Not the end, so add a "fake" end.  */
3077               tp[nlen++] = ')';
3078               tp[nlen] = '\0';
3079             }
3080         }
3081 #endif
3082
3083       /* If we're not globbing we're done: add it to the end of the chain.
3084          Go to the next item in the string.  */
3085       if (flags & PARSEFS_NOGLOB)
3086         {
3087           NEWELT (concat (2, prefix, tp));
3088           continue;
3089         }
3090
3091       /* If we get here we know we're doing glob expansion.
3092          TP is a string in tmpbuf.  NLEN is no longer used.
3093          We may need to do more work: after this NAME will be set.  */
3094       name = tp;
3095
3096       /* Expand tilde if applicable.  */
3097       if (tp[0] == '~')
3098         {
3099           tildep = tilde_expand (tp);
3100           if (tildep != 0)
3101             name = tildep;
3102         }
3103
3104 #ifndef NO_ARCHIVES
3105       /* If NAME is an archive member reference replace it with the archive
3106          file name, and save the member name in MEMNAME.  We will glob on the
3107          archive name and then reattach MEMNAME later.  */
3108       if (! (flags & PARSEFS_NOAR) && ar_name (name))
3109         {
3110           ar_parse_name (name, &arname, &memname);
3111           name = arname;
3112         }
3113 #endif /* !NO_ARCHIVES */
3114
3115       switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
3116         {
3117         case GLOB_NOSPACE:
3118           fatal (NILF, _("virtual memory exhausted"));
3119
3120         case 0:
3121           /* Success.  */
3122           i = gl.gl_pathc;
3123           nlist = (const char **)gl.gl_pathv;
3124           break;
3125
3126         case GLOB_NOMATCH:
3127           /* If we want only existing items, skip this one.  */
3128           if (flags & PARSEFS_EXISTS)
3129             {
3130               i = 0;
3131               break;
3132             }
3133           /* FALLTHROUGH */
3134
3135         default:
3136           /* By default keep this name.  */
3137           i = 1;
3138           nlist = &name;
3139           break;
3140         }
3141
3142       /* For each matched element, add it to the list.  */
3143       while (i-- > 0)
3144 #ifndef NO_ARCHIVES
3145         if (memname != 0)
3146           {
3147             /* Try to glob on MEMNAME within the archive.  */
3148             struct nameseq *found = ar_glob (nlist[i], memname, size);
3149             if (! found)
3150               /* No matches.  Use MEMNAME as-is.  */
3151               NEWELT (concat (5, prefix, nlist[i], "(", memname, ")"));
3152             else
3153               {
3154                 /* We got a chain of items.  Attach them.  */
3155                 (*newp)->next = found;
3156
3157                 /* Find and set the new end.  Massage names if necessary.  */
3158                 while (1)
3159                   {
3160                     if (! cachep)
3161                       found->name = xstrdup (concat (2, prefix, name));
3162                     else if (prefix)
3163                       found->name = strcache_add (concat (2, prefix, name));
3164
3165                     if (found->next == 0)
3166                       break;
3167
3168                     found = found->next;
3169                   }
3170                 newp = &found->next;
3171               }
3172           }
3173         else
3174 #endif /* !NO_ARCHIVES */
3175           NEWELT (concat (2, prefix, nlist[i]));
3176
3177       globfree (&gl);
3178
3179 #ifndef NO_ARCHIVES
3180       if (arname)
3181         free (arname);
3182 #endif
3183
3184       if (tildep)
3185         free (tildep);
3186     }
3187
3188   *stringp = p;
3189   return new;
3190 }