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