]> granicus.if.org Git - python/commitdiff
Issue #6697: Fix a crash if code of "python -c code" contains surrogates
authorVictor Stinner <victor.stinner@haypocalc.com>
Mon, 17 May 2010 01:13:37 +0000 (01:13 +0000)
committerVictor Stinner <victor.stinner@haypocalc.com>
Mon, 17 May 2010 01:13:37 +0000 (01:13 +0000)
Lib/test/test_sys.py
Modules/main.c

index a9f3f5ed6405b584c6fe1c71d0de2d7e1105a8c0..abbd7592c72a3c949a1c7fc6f3c84ae1c3da2452 100644 (file)
@@ -449,6 +449,24 @@ class SysModuleTest(unittest.TestCase):
 
         self.assertRaises(TypeError, sys.intern, S("abc"))
 
+    def test_main_invalid_unicode(self):
+        import locale
+        non_decodable = b"\xff"
+        encoding = locale.getpreferredencoding()
+        try:
+            non_decodable.decode(encoding)
+        except UnicodeDecodeError:
+            pass
+        else:
+            self.skipTest('%r is decodable with encoding %s'
+                % (non_decodable, encoding))
+        code = b'print("' + non_decodable + b'")'
+        p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE)
+        stdout, stderr = p.communicate()
+        self.assertEqual(p.returncode, 1)
+        self.assert_(stderr.startswith(b"UnicodeEncodeError: "
+            b"'utf-8' codec can't encode character '\\udcff' in "
+            b"position 7: surrogates not allowed"), stderr)
 
     def test_sys_flags(self):
         self.assertTrue(sys.flags)
index 32139f6364ab090fbf7e70fe53f62f4b1b8d2941..92b971fb0fdd5ca0a6b114a609ed6adfecc67901 100644 (file)
@@ -563,18 +563,22 @@ Py_Main(int argc, wchar_t **argv)
     }
 
     if (command) {
+        char *commandStr;
         PyObject *commandObj = PyUnicode_FromWideChar(
             command, wcslen(command));
         free(command);
-        if (commandObj != NULL) {
-            sts = PyRun_SimpleStringFlags(
-                _PyUnicode_AsString(commandObj), &cf) != 0;
+        if (commandObj != NULL)
+            commandStr = _PyUnicode_AsString(commandObj);
+        else
+            commandStr = NULL;
+        if (commandStr != NULL) {
+            sts = PyRun_SimpleStringFlags(commandStr, &cf) != 0;
+            Py_DECREF(commandObj);
         }
         else {
             PyErr_Print();
             sts = 1;
         }
-        Py_DECREF(commandObj);
     } else if (module) {
         sts = RunModule(module, 1);
     }