Home | History | Annotate | Download | only in make-3.81
      1 /* Variable expansion functions 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 "filedef.h"
     24 #include "job.h"
     25 #include "commands.h"
     26 #include "variable.h"
     27 #include "rule.h"
     28 
     29 /* Initially, any errors reported when expanding strings will be reported
     30    against the file where the error appears.  */
     31 const struct floc **expanding_var = &reading_file;
     32 
     33 /* The next two describe the variable output buffer.
     34    This buffer is used to hold the variable-expansion of a line of the
     35    makefile.  It is made bigger with realloc whenever it is too small.
     36    variable_buffer_length is the size currently allocated.
     37    variable_buffer is the address of the buffer.
     38 
     39    For efficiency, it's guaranteed that the buffer will always have
     40    VARIABLE_BUFFER_ZONE extra bytes allocated.  This allows you to add a few
     41    extra chars without having to call a function.  Note you should never use
     42    these bytes unless you're _sure_ you have room (you know when the buffer
     43    length was last checked.  */
     44 
     45 #define VARIABLE_BUFFER_ZONE    5
     46 
     47 static unsigned int variable_buffer_length;
     48 char *variable_buffer;
     49 
     50 /* Subroutine of variable_expand and friends:
     51    The text to add is LENGTH chars starting at STRING to the variable_buffer.
     52    The text is added to the buffer at PTR, and the updated pointer into
     53    the buffer is returned as the value.  Thus, the value returned by
     54    each call to variable_buffer_output should be the first argument to
     55    the following call.  */
     56 
     57 char *
     58 variable_buffer_output (char *ptr, char *string, unsigned int length)
     59 {
     60   register unsigned int newlen = length + (ptr - variable_buffer);
     61 
     62   if ((newlen + VARIABLE_BUFFER_ZONE) > variable_buffer_length)
     63     {
     64       unsigned int offset = ptr - variable_buffer;
     65       variable_buffer_length = (newlen + 100 > 2 * variable_buffer_length
     66 				? newlen + 100
     67 				: 2 * variable_buffer_length);
     68       variable_buffer = (char *) xrealloc (variable_buffer,
     69 					   variable_buffer_length);
     70       ptr = variable_buffer + offset;
     71     }
     72 
     73   bcopy (string, ptr, length);
     74   return ptr + length;
     75 }
     76 
     77 /* Return a pointer to the beginning of the variable buffer.  */
     78 
     79 static char *
     80 initialize_variable_output (void)
     81 {
     82   /* If we don't have a variable output buffer yet, get one.  */
     83 
     84   if (variable_buffer == 0)
     85     {
     86       variable_buffer_length = 200;
     87       variable_buffer = (char *) xmalloc (variable_buffer_length);
     88       variable_buffer[0] = '\0';
     89     }
     90 
     91   return variable_buffer;
     92 }
     93 
     94 /* Recursively expand V.  The returned string is malloc'd.  */
     96 
     97 static char *allocated_variable_append PARAMS ((const struct variable *v));
     98 
     99 char *
    100 recursively_expand_for_file (struct variable *v, struct file *file)
    101 {
    102   char *value;
    103   const struct floc *this_var;
    104   const struct floc **saved_varp;
    105   struct variable_set_list *save = 0;
    106   int set_reading = 0;
    107 
    108   /* Don't install a new location if this location is empty.
    109      This can happen for command-line variables, builtin variables, etc.  */
    110   saved_varp = expanding_var;
    111   if (v->fileinfo.filenm)
    112     {
    113       this_var = &v->fileinfo;
    114       expanding_var = &this_var;
    115     }
    116 
    117   /* If we have no other file-reading context, use the variable's context. */
    118   if (!reading_file)
    119     {
    120       set_reading = 1;
    121       reading_file = &v->fileinfo;
    122     }
    123 
    124   if (v->expanding)
    125     {
    126       if (!v->exp_count)
    127         /* Expanding V causes infinite recursion.  Lose.  */
    128         fatal (*expanding_var,
    129                _("Recursive variable `%s' references itself (eventually)"),
    130                v->name);
    131       --v->exp_count;
    132     }
    133 
    134   if (file)
    135     {
    136       save = current_variable_set_list;
    137       current_variable_set_list = file->variables;
    138     }
    139 
    140   v->expanding = 1;
    141   if (v->append)
    142     value = allocated_variable_append (v);
    143   else
    144     value = allocated_variable_expand (v->value);
    145   v->expanding = 0;
    146 
    147   if (set_reading)
    148     reading_file = 0;
    149 
    150   if (file)
    151     current_variable_set_list = save;
    152 
    153   expanding_var = saved_varp;
    154 
    155   return value;
    156 }
    157 
    158 /* Expand a simple reference to variable NAME, which is LENGTH chars long.  */
    159 
    160 #ifdef __GNUC__
    161 __inline
    162 #endif
    163 static char *
    164 reference_variable (char *o, char *name, unsigned int length)
    165 {
    166   register struct variable *v;
    167   char *value;
    168 
    169   v = lookup_variable (name, length);
    170 
    171   if (v == 0)
    172     warn_undefined (name, length);
    173 
    174   /* If there's no variable by that name or it has no value, stop now.  */
    175   if (v == 0 || (*v->value == '\0' && !v->append))
    176     return o;
    177 
    178   value = (v->recursive ? recursively_expand (v) : v->value);
    179 
    180   o = variable_buffer_output (o, value, strlen (value));
    181 
    182   if (v->recursive)
    183     free (value);
    184 
    185   return o;
    186 }
    187 
    188 /* Scan STRING for variable references and expansion-function calls.  Only
    190    LENGTH bytes of STRING are actually scanned.  If LENGTH is -1, scan until
    191    a null byte is found.
    192 
    193    Write the results to LINE, which must point into `variable_buffer'.  If
    194    LINE is NULL, start at the beginning of the buffer.
    195    Return a pointer to LINE, or to the beginning of the buffer if LINE is
    196    NULL.  */
    197 
    198 char *
    199 variable_expand_string (char *line, char *string, long length)
    200 {
    201   register struct variable *v;
    202   register char *p, *o, *p1;
    203   char save_char = '\0';
    204   unsigned int line_offset;
    205 
    206   if (!line)
    207     line = initialize_variable_output();
    208 
    209   p = string;
    210   o = line;
    211   line_offset = line - variable_buffer;
    212 
    213   if (length >= 0)
    214     {
    215       save_char = string[length];
    216       string[length] = '\0';
    217     }
    218 
    219   while (1)
    220     {
    221       /* Copy all following uninteresting chars all at once to the
    222          variable output buffer, and skip them.  Uninteresting chars end
    223 	 at the next $ or the end of the input.  */
    224 
    225       p1 = strchr (p, '$');
    226 
    227       o = variable_buffer_output (o, p, p1 != 0 ? (unsigned int)(p1 - p) : strlen (p) + 1);
    228 
    229       if (p1 == 0)
    230 	break;
    231       p = p1 + 1;
    232 
    233       /* Dispatch on the char that follows the $.  */
    234 
    235       switch (*p)
    236 	{
    237 	case '$':
    238 	  /* $$ seen means output one $ to the variable output buffer.  */
    239 	  o = variable_buffer_output (o, p, 1);
    240 	  break;
    241 
    242 	case '(':
    243 	case '{':
    244 	  /* $(...) or ${...} is the general case of substitution.  */
    245 	  {
    246 	    char openparen = *p;
    247 	    char closeparen = (openparen == '(') ? ')' : '}';
    248 	    register char *beg = p + 1;
    249 	    int free_beg = 0;
    250 	    char *op, *begp;
    251 	    char *end, *colon;
    252 
    253 	    op = o;
    254 	    begp = p;
    255 	    if (handle_function (&op, &begp))
    256 	      {
    257 		o = op;
    258 		p = begp;
    259 		break;
    260 	      }
    261 
    262 	    /* Is there a variable reference inside the parens or braces?
    263 	       If so, expand it before expanding the entire reference.  */
    264 
    265 	    end = strchr (beg, closeparen);
    266 	    if (end == 0)
    267               /* Unterminated variable reference.  */
    268               fatal (*expanding_var, _("unterminated variable reference"));
    269 	    p1 = lindex (beg, end, '$');
    270 	    if (p1 != 0)
    271 	      {
    272 		/* BEG now points past the opening paren or brace.
    273 		   Count parens or braces until it is matched.  */
    274 		int count = 0;
    275 		for (p = beg; *p != '\0'; ++p)
    276 		  {
    277 		    if (*p == openparen)
    278 		      ++count;
    279 		    else if (*p == closeparen && --count < 0)
    280 		      break;
    281 		  }
    282 		/* If COUNT is >= 0, there were unmatched opening parens
    283 		   or braces, so we go to the simple case of a variable name
    284 		   such as `$($(a)'.  */
    285 		if (count < 0)
    286 		  {
    287 		    beg = expand_argument (beg, p); /* Expand the name.  */
    288 		    free_beg = 1; /* Remember to free BEG when finished.  */
    289 		    end = strchr (beg, '\0');
    290 		  }
    291 	      }
    292 	    else
    293 	      /* Advance P to the end of this reference.  After we are
    294                  finished expanding this one, P will be incremented to
    295                  continue the scan.  */
    296 	      p = end;
    297 
    298 	    /* This is not a reference to a built-in function and
    299 	       any variable references inside are now expanded.
    300 	       Is the resultant text a substitution reference?  */
    301 
    302 	    colon = lindex (beg, end, ':');
    303 	    if (colon)
    304 	      {
    305 		/* This looks like a substitution reference: $(FOO:A=B).  */
    306 		char *subst_beg, *subst_end, *replace_beg, *replace_end;
    307 
    308 		subst_beg = colon + 1;
    309 		subst_end = lindex (subst_beg, end, '=');
    310 		if (subst_end == 0)
    311 		  /* There is no = in sight.  Punt on the substitution
    312 		     reference and treat this as a variable name containing
    313 		     a colon, in the code below.  */
    314 		  colon = 0;
    315 		else
    316 		  {
    317 		    replace_beg = subst_end + 1;
    318 		    replace_end = end;
    319 
    320 		    /* Extract the variable name before the colon
    321 		       and look up that variable.  */
    322 		    v = lookup_variable (beg, colon - beg);
    323 		    if (v == 0)
    324 		      warn_undefined (beg, colon - beg);
    325 
    326                     /* If the variable is not empty, perform the
    327                        substitution.  */
    328 		    if (v != 0 && *v->value != '\0')
    329 		      {
    330 			char *pattern, *replace, *ppercent, *rpercent;
    331 			char *value = (v->recursive
    332                                        ? recursively_expand (v)
    333 				       : v->value);
    334 
    335                         /* Copy the pattern and the replacement.  Add in an
    336                            extra % at the beginning to use in case there
    337                            isn't one in the pattern.  */
    338                         pattern = (char *) alloca (subst_end - subst_beg + 2);
    339                         *(pattern++) = '%';
    340                         bcopy (subst_beg, pattern, subst_end - subst_beg);
    341                         pattern[subst_end - subst_beg] = '\0';
    342 
    343                         replace = (char *) alloca (replace_end
    344                                                    - replace_beg + 2);
    345                         *(replace++) = '%';
    346                         bcopy (replace_beg, replace,
    347                                replace_end - replace_beg);
    348                         replace[replace_end - replace_beg] = '\0';
    349 
    350                         /* Look for %.  Set the percent pointers properly
    351                            based on whether we find one or not.  */
    352 			ppercent = find_percent (pattern);
    353 			if (ppercent)
    354                           {
    355                             ++ppercent;
    356                             rpercent = 0;
    357                           }
    358 			else
    359                           {
    360                             ppercent = pattern;
    361                             rpercent = replace;
    362                             --pattern;
    363                             --replace;
    364                           }
    365 
    366                         o = patsubst_expand (o, value, pattern, replace,
    367                                              ppercent, rpercent);
    368 
    369 			if (v->recursive)
    370 			  free (value);
    371 		      }
    372 		  }
    373 	      }
    374 
    375 	    if (colon == 0)
    376 	      /* This is an ordinary variable reference.
    377 		 Look up the value of the variable.  */
    378 		o = reference_variable (o, beg, end - beg);
    379 
    380 	  if (free_beg)
    381 	    free (beg);
    382 	  }
    383 	  break;
    384 
    385 	case '\0':
    386 	  break;
    387 
    388 	default:
    389 	  if (isblank ((unsigned char)p[-1]))
    390 	    break;
    391 
    392 	  /* A $ followed by a random char is a variable reference:
    393 	     $a is equivalent to $(a).  */
    394           o = reference_variable (o, p, 1);
    395 
    396 	  break;
    397 	}
    398 
    399       if (*p == '\0')
    400 	break;
    401       else
    402 	++p;
    403     }
    404 
    405   if (save_char)
    406     string[length] = save_char;
    407 
    408   (void)variable_buffer_output (o, "", 1);
    409   return (variable_buffer + line_offset);
    410 }
    411 
    412 /* Scan LINE for variable references and expansion-function calls.
    414    Build in `variable_buffer' the result of expanding the references and calls.
    415    Return the address of the resulting string, which is null-terminated
    416    and is valid only until the next time this function is called.  */
    417 
    418 char *
    419 variable_expand (char *line)
    420 {
    421   return variable_expand_string(NULL, line, (long)-1);
    422 }
    423 
    424 /* Expand an argument for an expansion function.
    426    The text starting at STR and ending at END is variable-expanded
    427    into a null-terminated string that is returned as the value.
    428    This is done without clobbering `variable_buffer' or the current
    429    variable-expansion that is in progress.  */
    430 
    431 char *
    432 expand_argument (const char *str, const char *end)
    433 {
    434   char *tmp;
    435 
    436   if (str == end)
    437     return xstrdup("");
    438 
    439   if (!end || *end == '\0')
    440     return allocated_variable_expand ((char *)str);
    441 
    442   tmp = (char *) alloca (end - str + 1);
    443   bcopy (str, tmp, end - str);
    444   tmp[end - str] = '\0';
    445 
    446   return allocated_variable_expand (tmp);
    447 }
    448 
    449 /* Expand LINE for FILE.  Error messages refer to the file and line where
    451    FILE's commands were found.  Expansion uses FILE's variable set list.  */
    452 
    453 char *
    454 variable_expand_for_file (char *line, struct file *file)
    455 {
    456   char *result;
    457   struct variable_set_list *save;
    458 
    459   if (file == 0)
    460     return variable_expand (line);
    461 
    462   save = current_variable_set_list;
    463   current_variable_set_list = file->variables;
    464   if (file->cmds && file->cmds->fileinfo.filenm)
    465     reading_file = &file->cmds->fileinfo;
    466   else
    467     reading_file = 0;
    468   result = variable_expand (line);
    469   current_variable_set_list = save;
    470   reading_file = 0;
    471 
    472   return result;
    473 }
    474 
    475 /* Like allocated_variable_expand, but for += target-specific variables.
    477    First recursively construct the variable value from its appended parts in
    478    any upper variable sets.  Then expand the resulting value.  */
    479 
    480 static char *
    481 variable_append (const char *name, unsigned int length,
    482                  const struct variable_set_list *set)
    483 {
    484   const struct variable *v;
    485   char *buf = 0;
    486 
    487   /* If there's nothing left to check, return the empty buffer.  */
    488   if (!set)
    489     return initialize_variable_output ();
    490 
    491   /* Try to find the variable in this variable set.  */
    492   v = lookup_variable_in_set (name, length, set->set);
    493 
    494   /* If there isn't one, look to see if there's one in a set above us.  */
    495   if (!v)
    496     return variable_append (name, length, set->next);
    497 
    498   /* If this variable type is append, first get any upper values.
    499      If not, initialize the buffer.  */
    500   if (v->append)
    501     buf = variable_append (name, length, set->next);
    502   else
    503     buf = initialize_variable_output ();
    504 
    505   /* Append this value to the buffer, and return it.
    506      If we already have a value, first add a space.  */
    507   if (buf > variable_buffer)
    508     buf = variable_buffer_output (buf, " ", 1);
    509 
    510   /* Either expand it or copy it, depending.  */
    511   if (! v->recursive)
    512     return variable_buffer_output (buf, v->value, strlen (v->value));
    513 
    514   buf = variable_expand_string (buf, v->value, strlen (v->value));
    515   return (buf + strlen (buf));
    516 }
    517 
    518 
    519 static char *
    520 allocated_variable_append (const struct variable *v)
    521 {
    522   char *val;
    523 
    524   /* Construct the appended variable value.  */
    525 
    526   char *obuf = variable_buffer;
    527   unsigned int olen = variable_buffer_length;
    528 
    529   variable_buffer = 0;
    530 
    531   val = variable_append (v->name, strlen (v->name), current_variable_set_list);
    532   variable_buffer_output (val, "", 1);
    533   val = variable_buffer;
    534 
    535   variable_buffer = obuf;
    536   variable_buffer_length = olen;
    537 
    538   return val;
    539 }
    540 
    541 /* Like variable_expand_for_file, but the returned string is malloc'd.
    542    This function is called a lot.  It wants to be efficient.  */
    543 
    544 char *
    545 allocated_variable_expand_for_file (char *line, struct file *file)
    546 {
    547   char *value;
    548 
    549   char *obuf = variable_buffer;
    550   unsigned int olen = variable_buffer_length;
    551 
    552   variable_buffer = 0;
    553 
    554   value = variable_expand_for_file (line, file);
    555 
    556 #if 0
    557   /* Waste a little memory and save time.  */
    558   value = xrealloc (value, strlen (value))
    559 #endif
    560 
    561   variable_buffer = obuf;
    562   variable_buffer_length = olen;
    563 
    564   return value;
    565 }
    566 
    567 /* Install a new variable_buffer context, returning the current one for
    568    safe-keeping.  */
    569 
    570 void
    571 install_variable_buffer (char **bufp, unsigned int *lenp)
    572 {
    573   *bufp = variable_buffer;
    574   *lenp = variable_buffer_length;
    575 
    576   variable_buffer = 0;
    577   initialize_variable_output ();
    578 }
    579 
    580 /* Restore a previously-saved variable_buffer setting (free the current one).
    581  */
    582 
    583 void
    584 restore_variable_buffer (char *buf, unsigned int len)
    585 {
    586   free (variable_buffer);
    587 
    588   variable_buffer = buf;
    589   variable_buffer_length = len;
    590 }
    591