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