]> granicus.if.org Git - python/commitdiff
iterators passed to writelines() can close their files; don't segfault #10125
authorBenjamin Peterson <benjamin@python.org>
Sat, 16 Oct 2010 19:20:12 +0000 (19:20 +0000)
committerBenjamin Peterson <benjamin@python.org>
Sat, 16 Oct 2010 19:20:12 +0000 (19:20 +0000)
Lib/test/test_file2k.py
Misc/NEWS
Objects/fileobject.c

index fc8bfe9c5d7f5564a74250227ff1e93e99c419d6..ab09f2161ba516ef0e8f9e5f985153e1c1cbde2d 100644 (file)
@@ -135,6 +135,14 @@ class AutoFileTests(unittest.TestCase):
     def testReadWhenWriting(self):
         self.assertRaises(IOError, self.f.read)
 
+    def testNastyWritelinesGenerator(self):
+        def nasty():
+            for i in range(5):
+                if i == 3:
+                    self.f.close()
+                yield str(i)
+        self.assertRaises(ValueError, self.f.writelines, nasty())
+
     def testIssue5677(self):
         # Remark: Do not perform more than one test per open file,
         # since that does NOT catch the readline error on Windows.
index c2b674b24527add65af5d3da9be2d1e18504f080..b597bd57839beabcdc29bef59e58a21be58426e1 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@ What's New in Python 2.7.1?
 Core and Builtins
 -----------------
 
+- Issue #10125: Don't segfault when the iterator passed to ``file.writelines()``
+  closes the file.
+
 - Issue #9997: Don't let the name "top" have special significance in scope
   resolution.
 
index b7de6a10cd7a6f4add3cf84b2a71e06121cc2c04..2647b54269ca864a8c6c74e0b07072bcb7db0099 100644 (file)
@@ -1849,6 +1849,11 @@ file_writelines(PyFileObject *f, PyObject *seq)
                 }
                 PyList_SetItem(list, j, line);
             }
+            /* The iterator might have closed the file on us. */
+            if (f->f_fp == NULL) {
+                err_closed();
+                goto error;
+            }
         }
         if (j == 0)
             break;