]> granicus.if.org Git - python/commitdiff
#3242: fix a crash in "print", if sys.stdout is set to a custom object,
authorAmaury Forgeot d'Arc <amauryfa@gmail.com>
Tue, 1 Jul 2008 20:52:56 +0000 (20:52 +0000)
committerAmaury Forgeot d'Arc <amauryfa@gmail.com>
Tue, 1 Jul 2008 20:52:56 +0000 (20:52 +0000)
whose write() method installs another sys.stdout.

Backport of r64633

Lib/test/test_file.py
Misc/NEWS
Python/ceval.c

index 73cb5b2412780a695befde5047cf61e7719d85f6..0a8114a0c7bf4a2b277a7ae1485944dc25a143bc 100644 (file)
@@ -323,11 +323,30 @@ class OtherFileTests(unittest.TestCase):
             os.unlink(TESTFN)
 
 
+class StdoutTests(unittest.TestCase):
+
+    def test_move_stdout_on_write(self):
+        # Issue 3242: sys.stdout can be replaced (and freed) during a
+        # print statement; prevent a segfault in this case
+        save_stdout = sys.stdout
+
+        class File:
+            def write(self, data):
+                if '\n' in data:
+                    sys.stdout = save_stdout
+
+        try:
+            sys.stdout = File()
+            print "some text"
+        finally:
+            sys.stdout = save_stdout
+
+
 def test_main():
     # Historically, these tests have been sloppy about removing TESTFN.
     # So get rid of it no matter what.
     try:
-        run_unittest(AutoFileTests, OtherFileTests)
+        run_unittest(AutoFileTests, OtherFileTests, StdoutTests)
     finally:
         if os.path.exists(TESTFN):
             os.unlink(TESTFN)
index 27c12c1425aefc5254569f4ac290c8757fb91837..4d6dd8344bc2dd26cfb6560b71f69612ea947085 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,10 @@ What's New in Python 2.5.3?
 Core and builtins
 -----------------
 
+- Issue #3242: Fix a crash inside the print statement, if sys.stdout is
+  set to a custom object whose write() method happens to install
+  another file in sys.stdout.
+
 - Issue #3100: Corrected a crash on deallocation of a subclassed weakref which
   holds the last (strong) reference to its referent.
 
index 06d524b275d118a863e618f3597fb0bd31fdf27f..9bc147b78d89eaff6f93601736142ca692c9e856 100644 (file)
@@ -1603,9 +1603,11 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
                                                        "lost sys.stdout");
                        }
                        if (w != NULL) {
+                               Py_INCREF(w);
                                err = PyFile_WriteString("\n", w);
                                if (err == 0)
                                        PyFile_SoftSpace(w, 0);
+                               Py_DECREF(w);
                        }
                        Py_XDECREF(stream);
                        stream = NULL;