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