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