diff Python/pythonrun.c @ 45914:4284718fb631

Issue2297: Fix a stack overflow in Windows caused by -v and -vv. When python is invoked with -v or -vv under Windows, the process of importing the codec for sys.stderr causes a message to be written to stderr, which in turn causes the codec to be recursively imported. Sometimes the stack overflow exception is swallowed, other times it is not. The bug depends on the particular locale settings of the Windows machine. Kudos to Douglas Greiman for reporting the issue and providing a patch and test case.
author Trent Nelson <trent.nelson@snakebite.org>
date Wed, 19 Mar 2008 06:45:48 +0000
parents 15d5776f2703
children 78504d604b44
line wrap: on
line diff
--- a/Python/pythonrun.c	Wed Mar 19 05:33:36 2008 +0000
+++ b/Python/pythonrun.c	Wed Mar 19 06:45:48 2008 +0000
@@ -512,7 +512,7 @@
 	/* reset file system default encoding */
 	if (!Py_HasFileSystemDefaultEncoding) {
 		free((char*)Py_FileSystemDefaultEncoding);
-        	Py_FileSystemDefaultEncoding = NULL;
+		Py_FileSystemDefaultEncoding = NULL;
 	}
 
 	/* XXX Still allocated:
@@ -733,6 +733,7 @@
 	PyObject *m;
 	PyObject *std = NULL;
 	int status = 0, fd;
+	PyObject * encoding_attr;
 
 	/* Hack to avoid a nasty recursion issue when Python is invoked
 	   in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
@@ -823,6 +824,19 @@
 			goto error;
 		}
 	} /* if (fd < 0) */
+
+	/* Same as hack above, pre-import stderr's codec to avoid recursion
+	   when import.c tries to write to stderr in verbose mode. */
+	encoding_attr = PyObject_GetAttrString(std, "encoding");
+	if (encoding_attr != NULL) {
+		const char * encoding;
+		encoding = PyUnicode_AsString(encoding_attr);
+		if (encoding != NULL) {
+			_PyCodec_Lookup(encoding);
+		}
+	}
+	PyErr_Clear();  /* Not a fatal error if codec isn't available */
+
 	PySys_SetObject("__stderr__", std);
 	PySys_SetObject("stderr", std);
 	Py_DECREF(std);
@@ -1900,8 +1914,8 @@
 		alloca(PYOS_STACK_MARGIN * sizeof(void*));
 		return 0;
 	} __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
-		        EXCEPTION_EXECUTE_HANDLER : 
-		        EXCEPTION_CONTINUE_SEARCH) {
+			EXCEPTION_EXECUTE_HANDLER : 
+			EXCEPTION_CONTINUE_SEARCH) {
 		int errcode = _resetstkoflw();
 		if (errcode)
 		{