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