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