diff -r 113cdce4663c Lib/test/test_cmd_line.py --- a/Lib/test/test_cmd_line.py Wed Jun 06 01:37:37 2012 +0200 +++ b/Lib/test/test_cmd_line.py Wed Jun 06 01:50:05 2012 +0200 @@ -341,6 +341,18 @@ class CmdLineTest(unittest.TestCase): self.assertEqual(rc, 0) self.assertIn(b'random is 1', out) + def test_del___main__(self): + # Issue #15001: PyRun_SimpleFileExFlags() did crash because it kept a + # borrowed reference to the dict of __main__ module and later modify + # the dict whereas the module was destroyed + filename = test.support.TESTFN + self.addCleanup(test.support.unlink, filename) + with open(filename, "w") as script: + print("import sys", file=script) + print("del sys.modules['__main__']", file=script) + assert_python_ok(filename) + + def test_main(): test.support.run_unittest(CmdLineTest) test.support.reap_children() diff -r 113cdce4663c Python/pythonrun.c --- a/Python/pythonrun.c Wed Jun 06 01:37:37 2012 +0200 +++ b/Python/pythonrun.c Wed Jun 06 01:50:05 2012 +0200 @@ -1323,25 +1323,26 @@ PyRun_SimpleFileExFlags(FILE *fp, const { PyObject *m, *d, *v; const char *ext; - int set_file_name = 0, ret; + int set_file_name = 0, ret = -1; size_t len; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; + Py_INCREF(m); d = PyModule_GetDict(m); if (PyDict_GetItemString(d, "__file__") == NULL) { PyObject *f; f = PyUnicode_DecodeFSDefault(filename); if (f == NULL) - return -1; + goto done; if (PyDict_SetItemString(d, "__file__", f) < 0) { Py_DECREF(f); - return -1; + goto done; } if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) { Py_DECREF(f); - return -1; + goto done; } set_file_name = 1; Py_DECREF(f); @@ -1354,7 +1355,6 @@ PyRun_SimpleFileExFlags(FILE *fp, const fclose(fp); if ((fp = fopen(filename, "rb")) == NULL) { fprintf(stderr, "python: Can't reopen .pyc file\n"); - ret = -1; goto done; } /* Turn on optimization if a .pyo file is given */ @@ -1368,7 +1368,6 @@ PyRun_SimpleFileExFlags(FILE *fp, const flush_io(); if (v == NULL) { PyErr_Print(); - ret = -1; goto done; } Py_DECREF(v); @@ -1376,6 +1375,7 @@ PyRun_SimpleFileExFlags(FILE *fp, const done: if (set_file_name && PyDict_DelItemString(d, "__file__")) PyErr_Clear(); + Py_DECREF(m); return ret; }