Blob Blame History Raw
From 2f661dc20617ba6fdeb2d7e243dc898653faafea Mon Sep 17 00:00:00 2001
From: Lubomir Rintel <lkundrak@v3.sk>
Date: Tue, 26 Apr 2011 21:50:26 +0200
Subject: [PATCH] Always copy the string before expanding it

It might get freed during expansion, e.g. with eval function.
A simple reproducer:

TRUE = $(eval TRUE := true)
all:
	$(TRUE)
---
 ChangeLog |    5 +++++
 expand.c  |   18 +++++++++---------
 2 files changed, 14 insertions(+), 9 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 91878fb..7519164 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,8 @@
+2011-04-26  Lubomir Rintel  <lkundrak@v3.sk>
+
+	* expand.c (variable_expand_string): Always copy the string
+	to expand.
+
 2010-08-13  Paul Smith  <psmith@gnu.org>
 
 	* NEWS: Accidentally forgot to back out the sorted wildcard
diff --git a/expand.c b/expand.c
index 2315b06..3e6e346 100644
--- a/expand.c
+++ b/expand.c
@@ -197,7 +197,7 @@ variable_expand_string (char *line, const char *string, long length)
 {
   struct variable *v;
   const char *p, *p1;
-  char *abuf = NULL;
+  char *abuf;
   char *o;
   unsigned int line_offset;
 
@@ -214,14 +214,15 @@ variable_expand_string (char *line, const char *string, long length)
 
   /* If we want a subset of the string, allocate a temporary buffer for it.
      Most of the functions we use here don't work with length limits.  */
-  if (length > 0 && string[length] != '\0')
+  if (length == -1)
     {
-      abuf = xmalloc(length+1);
-      memcpy(abuf, string, length);
-      abuf[length] = '\0';
-      string = abuf;
+      length = strlen (string);
     }
-  p = string;
+
+  abuf = xmalloc(length+1);
+  memcpy(abuf, string, length);
+  abuf[length] = '\0';
+  p = abuf;
 
   while (1)
     {
@@ -411,8 +412,7 @@ variable_expand_string (char *line, const char *string, long length)
       ++p;
     }
 
-  if (abuf)
-    free (abuf);
+  free (abuf);
 
   variable_buffer_output (o, "", 1);
   return (variable_buffer + line_offset);
-- 
1.7.4.1