From 424da221cec76ea200cff1fa9b08a6f3d94c28a7 Mon Sep 17 00:00:00 2001
From: Lubomir Rintel <lkundrak@v3.sk>
Date: Wed, 31 Oct 2018 16:39:13 -0700
Subject: [PATCH] Fix error handling with git-style patches

When an error is encountered in output_files(), the subsequent call to
cleanup() calls back into output_files() resulting in an infinte recursion.
This is trivially reproduced with a git-style patch (which utilizes
output_file_later()) that tries to patch a nonexistent or unreadable
file (see attached test case).

* src/patch.c: (output_files) clear the files_to_output list before
iterating it, so that recursive calls won't iterate the same files.
---
 src/patch.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

--- a/src/patch.c
+++ b/src/patch.c
@@ -1938,8 +1938,12 @@ output_files (struct stat const *st)
 {
   gl_list_iterator_t iter;
   const void *elt;
+  gl_list_t files;
 
-  iter = gl_list_iterator (files_to_output);
+  files = files_to_output;
+  init_files_to_output ();
+
+  iter = gl_list_iterator (files);
   while (gl_list_iterator_next (&iter, &elt, NULL))
     {
       const struct file_to_output *file_to_output = elt;
@@ -1957,8 +1961,8 @@ output_files (struct stat const *st)
 	  /* Free the list up to here. */
 	  for (;;)
 	    {
-	      const void *elt2 = gl_list_get_at (files_to_output, 0);
-	      gl_list_remove_at (files_to_output, 0);
+	      const void *elt2 = gl_list_get_at (files, 0);
+	      gl_list_remove_at (files, 0);
 	      if (elt == elt2)
 		break;
 	    }
@@ -1967,7 +1971,7 @@ output_files (struct stat const *st)
 	}
     }
   gl_list_iterator_free (&iter);
-  gl_list_clear (files_to_output);
+  gl_list_clear (files);
 }
 
 /* Fatal exit with cleanup. */
