gh-108082: Use PyErr_FormatUnraisable() (GH-111580)

Replace most of calls of _PyErr_WriteUnraisableMsg() and some
calls of PyErr_WriteUnraisable(NULL) with PyErr_FormatUnraisable().

Co-authored-by: Victor Stinner <vstinner@python.org>
This commit is contained in:
Serhiy Storchaka 2023-11-02 11:16:34 +02:00 committed by GitHub
parent a12f624a9d
commit 970e719a7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 83 additions and 114 deletions

View File

@ -110,9 +110,11 @@ class TestDictWatchers(unittest.TestCase):
with catch_unraisable_exception() as cm: with catch_unraisable_exception() as cm:
d["foo"] = "bar" d["foo"] = "bar"
self.assertIn( self.assertIn(
"PyDict_EVENT_ADDED watcher callback for <dict at", "Exception ignored in "
cm.unraisable.object "PyDict_EVENT_ADDED watcher callback for <dict at ",
cm.unraisable.err_msg
) )
self.assertIsNone(cm.unraisable.object)
self.assertEqual(str(cm.unraisable.exc_value), "boom!") self.assertEqual(str(cm.unraisable.exc_value), "boom!")
self.assert_events([]) self.assert_events([])
@ -278,7 +280,9 @@ class TestTypeWatchers(unittest.TestCase):
self.watch(wid, C) self.watch(wid, C)
with catch_unraisable_exception() as cm: with catch_unraisable_exception() as cm:
C.foo = "bar" C.foo = "bar"
self.assertIs(cm.unraisable.object, C) self.assertEqual(cm.unraisable.err_msg,
f"Exception ignored in type watcher callback #0 for {C!r}")
self.assertIs(cm.unraisable.object, None)
self.assertEqual(str(cm.unraisable.exc_value), "boom!") self.assertEqual(str(cm.unraisable.exc_value), "boom!")
self.assert_events([]) self.assert_events([])
@ -416,9 +420,11 @@ class TestCodeObjectWatchers(unittest.TestCase):
co = _testcapi.code_newempty("test_watchers", "dummy0", 0) co = _testcapi.code_newempty("test_watchers", "dummy0", 0)
self.assertEqual( self.assertEqual(
cm.unraisable.object, cm.unraisable.err_msg,
f"Exception ignored in "
f"PY_CODE_EVENT_CREATE watcher callback for {co!r}" f"PY_CODE_EVENT_CREATE watcher callback for {co!r}"
) )
self.assertIsNone(cm.unraisable.object)
self.assertEqual(str(cm.unraisable.exc_value), "boom!") self.assertEqual(str(cm.unraisable.exc_value), "boom!")
def test_dealloc_error(self): def test_dealloc_error(self):
@ -520,9 +526,11 @@ class TestFuncWatchers(unittest.TestCase):
pass pass
self.assertEqual( self.assertEqual(
cm.unraisable.object, cm.unraisable.err_msg,
f"PyFunction_EVENT_CREATE watcher callback for {myfunc!r}" f"Exception ignored in "
f"PyFunction_EVENT_CREATE watcher callback for {repr(myfunc)[1:-1]}"
) )
self.assertIsNone(cm.unraisable.object)
def test_dealloc_watcher_raises_error(self): def test_dealloc_watcher_raises_error(self):
class MyError(Exception): class MyError(Exception):

View File

@ -479,8 +479,9 @@ class CmdLineTest(unittest.TestCase):
rc, out, err = assert_python_failure('-c', code) rc, out, err = assert_python_failure('-c', code)
self.assertEqual(b'', out) self.assertEqual(b'', out)
self.assertEqual(120, rc) self.assertEqual(120, rc)
self.assertRegex(err.decode('ascii', 'ignore'), self.assertIn(b'Exception ignored on flushing sys.stdout:\n'
'Exception ignored in.*\nOSError: .*') b'OSError: '.replace(b'\n', os.linesep.encode()),
err)
def test_closed_stdout(self): def test_closed_stdout(self):
# Issue #13444: if stdout has been explicitly closed, we should # Issue #13444: if stdout has been explicitly closed, we should

View File

@ -113,7 +113,6 @@ bytes(cdata)
#ifdef MS_WIN32 #ifdef MS_WIN32
# include "pycore_modsupport.h" // _PyArg_NoKeywords() # include "pycore_modsupport.h" // _PyArg_NoKeywords()
#endif #endif
#include "pycore_pyerrors.h" // _PyErr_WriteUnraisableMsg()
#include <ffi.h> #include <ffi.h>
@ -185,7 +184,7 @@ _DictRemover_call(PyObject *myself, PyObject *args, PyObject *kw)
DictRemoverObject *self = (DictRemoverObject *)myself; DictRemoverObject *self = (DictRemoverObject *)myself;
if (self->key && self->dict) { if (self->key && self->dict) {
if (-1 == PyDict_DelItem(self->dict, self->key)) { if (-1 == PyDict_DelItem(self->dict, self->key)) {
_PyErr_WriteUnraisableMsg("on calling _ctypes.DictRemover", NULL); PyErr_FormatUnraisable("Exception ignored on calling _ctypes.DictRemover");
} }
Py_CLEAR(self->key); Py_CLEAR(self->key);
Py_CLEAR(self->dict); Py_CLEAR(self->dict);

View File

@ -5,7 +5,6 @@
#include "Python.h" #include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_ceval.h" // _PyEval_SetProfile() #include "pycore_ceval.h" // _PyEval_SetProfile()
#include "pycore_pyerrors.h" // _PyErr_WriteUnraisableMsg()
#include "pycore_pystate.h" // _PyThreadState_GET() #include "pycore_pystate.h" // _PyThreadState_GET()
#include "rotatingtree.h" #include "rotatingtree.h"
@ -847,7 +846,7 @@ profiler_dealloc(ProfilerObject *op)
if (op->flags & POF_ENABLED) { if (op->flags & POF_ENABLED) {
PyThreadState *tstate = _PyThreadState_GET(); PyThreadState *tstate = _PyThreadState_GET();
if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) { if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
_PyErr_WriteUnraisableMsg("When destroying _lsprof profiler", NULL); PyErr_FormatUnraisable("Exception ignored when destroying _lsprof profiler");
} }
} }

View File

@ -1032,8 +1032,8 @@ delete_garbage(PyThreadState *tstate, GCState *gcstate,
Py_INCREF(op); Py_INCREF(op);
(void) clear(op); (void) clear(op);
if (_PyErr_Occurred(tstate)) { if (_PyErr_Occurred(tstate)) {
_PyErr_WriteUnraisableMsg("in tp_clear of", PyErr_FormatUnraisable("Exception ignored in tp_clear of %s",
(PyObject*)Py_TYPE(op)); Py_TYPE(op)->tp_name);
} }
Py_DECREF(op); Py_DECREF(op);
} }
@ -1344,7 +1344,7 @@ gc_collect_main(PyThreadState *tstate, int generation,
_PyErr_Clear(tstate); _PyErr_Clear(tstate);
} }
else { else {
_PyErr_WriteUnraisableMsg("in garbage collection", NULL); PyErr_FormatUnraisable("Exception ignored in garbage collection");
} }
} }
@ -1403,7 +1403,7 @@ invoke_gc_callback(PyThreadState *tstate, const char *phase,
"collected", collected, "collected", collected,
"uncollectable", uncollectable); "uncollectable", uncollectable);
if (info == NULL) { if (info == NULL) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on invoking gc callbacks");
return; return;
} }
} }
@ -1411,7 +1411,7 @@ invoke_gc_callback(PyThreadState *tstate, const char *phase,
PyObject *phase_obj = PyUnicode_FromString(phase); PyObject *phase_obj = PyUnicode_FromString(phase);
if (phase_obj == NULL) { if (phase_obj == NULL) {
Py_XDECREF(info); Py_XDECREF(info);
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on invoking gc callbacks");
return; return;
} }

View File

@ -4,7 +4,6 @@
#include "pycore_fileutils.h" // _Py_abspath() #include "pycore_fileutils.h" // _Py_abspath()
#include "pycore_initconfig.h" // _PyStatus_EXCEPTION() #include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
#include "pycore_pathconfig.h" // _PyPathConfig_ReadGlobal() #include "pycore_pathconfig.h" // _PyPathConfig_ReadGlobal()
#include "pycore_pyerrors.h" // _PyErr_WriteUnraisableMsg()
#include "pycore_pymem.h" // _PyMem_RawWcsdup() #include "pycore_pymem.h" // _PyMem_RawWcsdup()
#include "pycore_pystate.h" // _PyThreadState_GET() #include "pycore_pystate.h" // _PyThreadState_GET()
@ -911,7 +910,7 @@ _PyConfig_InitPathConfig(PyConfig *config, int compute_path_config)
) { ) {
Py_DECREF(co); Py_DECREF(co);
Py_DECREF(dict); Py_DECREF(dict);
_PyErr_WriteUnraisableMsg("error evaluating initial values", NULL); PyErr_FormatUnraisable("Exception ignored in preparing getpath");
return PyStatus_Error("error evaluating initial values"); return PyStatus_Error("error evaluating initial values");
} }
@ -920,13 +919,13 @@ _PyConfig_InitPathConfig(PyConfig *config, int compute_path_config)
if (!r) { if (!r) {
Py_DECREF(dict); Py_DECREF(dict);
_PyErr_WriteUnraisableMsg("error evaluating path", NULL); PyErr_FormatUnraisable("Exception ignored in running getpath");
return PyStatus_Error("error evaluating path"); return PyStatus_Error("error evaluating path");
} }
Py_DECREF(r); Py_DECREF(r);
if (_PyConfig_FromDict(config, configDict) < 0) { if (_PyConfig_FromDict(config, configDict) < 0) {
_PyErr_WriteUnraisableMsg("reading getpath results", NULL); PyErr_FormatUnraisable("Exception ignored in reading getpath results");
Py_DECREF(dict); Py_DECREF(dict);
return PyStatus_Error("error getting getpath results"); return PyStatus_Error("error getting getpath results");
} }

View File

@ -244,8 +244,7 @@ report_wakeup_write_error(void *data)
errno = (int) (intptr_t) data; errno = (int) (intptr_t) data;
PyObject *exc = PyErr_GetRaisedException(); PyObject *exc = PyErr_GetRaisedException();
PyErr_SetFromErrno(PyExc_OSError); PyErr_SetFromErrno(PyExc_OSError);
_PyErr_WriteUnraisableMsg("when trying to write to the signal wakeup fd", PyErr_FormatUnraisable("Exception ignored when trying to write to the signal wakeup fd");
NULL);
PyErr_SetRaisedException(exc); PyErr_SetRaisedException(exc);
errno = save_errno; errno = save_errno;
return 0; return 0;
@ -262,7 +261,7 @@ report_wakeup_send_error(void* data)
recognizes the error codes used by both GetLastError() and recognizes the error codes used by both GetLastError() and
WSAGetLastError */ WSAGetLastError */
PyErr_SetExcFromWindowsErr(PyExc_OSError, send_errno); PyErr_SetExcFromWindowsErr(PyExc_OSError, send_errno);
_PyErr_WriteUnraisableMsg("when trying to send to the signal wakeup fd", NULL); PyErr_FormatUnraisable("Exception ignored when trying to send to the signal wakeup fd");
PyErr_SetRaisedException(exc); PyErr_SetRaisedException(exc);
return 0; return 0;
} }

View File

@ -12,8 +12,6 @@
#include "pycore_tuple.h" // _PyTuple_ITEMS() #include "pycore_tuple.h" // _PyTuple_ITEMS()
#include "clinic/codeobject.c.h" #include "clinic/codeobject.c.h"
static PyObject* code_repr(PyCodeObject *co);
static const char * static const char *
code_event_name(PyCodeEvent event) { code_event_name(PyCodeEvent event) {
switch (event) { switch (event) {
@ -41,21 +39,9 @@ notify_code_watchers(PyCodeEvent event, PyCodeObject *co)
// callback must be non-null if the watcher bit is set // callback must be non-null if the watcher bit is set
assert(cb != NULL); assert(cb != NULL);
if (cb(event, co) < 0) { if (cb(event, co) < 0) {
// Don't risk resurrecting the object if an unraisablehook keeps PyErr_FormatUnraisable(
// a reference; pass a string as context. "Exception ignored in %s watcher callback for %R",
PyObject *context = NULL; code_event_name(event), co);
PyObject *repr = code_repr(co);
if (repr) {
context = PyUnicode_FromFormat(
"%s watcher callback for %U",
code_event_name(event), repr);
Py_DECREF(repr);
}
if (context == NULL) {
context = Py_NewRef(Py_None);
}
PyErr_WriteUnraisable(context);
Py_DECREF(context);
} }
} }
i++; i++;

View File

@ -5912,14 +5912,9 @@ _PyDict_SendEvent(int watcher_bits,
// unraisablehook keep a reference to it, so we don't pass the // unraisablehook keep a reference to it, so we don't pass the
// dict as context, just an informative string message. Dict // dict as context, just an informative string message. Dict
// repr can call arbitrary code, so we invent a simpler version. // repr can call arbitrary code, so we invent a simpler version.
PyObject *context = PyUnicode_FromFormat( PyErr_FormatUnraisable(
"%s watcher callback for <dict at %p>", "Exception ignored in %s watcher callback for <dict at %p>",
dict_event_name(event), mp); dict_event_name(event), mp);
if (context == NULL) {
context = Py_NewRef(Py_None);
}
PyErr_WriteUnraisable(context);
Py_DECREF(context);
} }
} }
watcher_bits >>= 1; watcher_bits >>= 1;

View File

@ -8,8 +8,6 @@
#include "pycore_pyerrors.h" // _PyErr_Occurred() #include "pycore_pyerrors.h" // _PyErr_Occurred()
static PyObject* func_repr(PyFunctionObject *op);
static const char * static const char *
func_event_name(PyFunction_WatchEvent event) { func_event_name(PyFunction_WatchEvent event) {
switch (event) { switch (event) {
@ -35,21 +33,9 @@ notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
// callback must be non-null if the watcher bit is set // callback must be non-null if the watcher bit is set
assert(cb != NULL); assert(cb != NULL);
if (cb(event, func, new_value) < 0) { if (cb(event, func, new_value) < 0) {
// Don't risk resurrecting the func if an unraisablehook keeps a PyErr_FormatUnraisable(
// reference; pass a string as context. "Exception ignored in %s watcher callback for function %U at %p",
PyObject *context = NULL; func_event_name(event), func->func_qualname, func);
PyObject *repr = func_repr(func);
if (repr != NULL) {
context = PyUnicode_FromFormat(
"%s watcher callback for %U",
func_event_name(event), repr);
Py_DECREF(repr);
}
if (context == NULL) {
context = Py_NewRef(Py_None);
}
PyErr_WriteUnraisable(context);
Py_DECREF(context);
} }
} }
i++; i++;

View File

@ -647,7 +647,7 @@ _PyModule_ClearDict(PyObject *d)
PyErr_Clear(); PyErr_Clear();
} }
if (PyDict_SetItem(d, key, Py_None) != 0) { if (PyDict_SetItem(d, key, Py_None) != 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing module dict");
} }
} }
} }
@ -668,7 +668,7 @@ _PyModule_ClearDict(PyObject *d)
PyErr_Clear(); PyErr_Clear();
} }
if (PyDict_SetItem(d, key, Py_None) != 0) { if (PyDict_SetItem(d, key, Py_None) != 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing module dict");
} }
} }
} }
@ -902,10 +902,9 @@ module_clear(PyModuleObject *m)
{ {
int res = m->md_def->m_clear((PyObject*)m); int res = m->md_def->m_clear((PyObject*)m);
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
PySys_FormatStderr("Exception ignored in m_clear of module%s%V\n", PyErr_FormatUnraisable("Exception ignored in m_clear of module%s%V",
m->md_name ? " " : "", m->md_name ? " " : "",
m->md_name, ""); m->md_name, "");
PyErr_WriteUnraisable(NULL);
} }
if (res) if (res)
return res; return res;

View File

@ -828,7 +828,9 @@ PyType_Modified(PyTypeObject *type)
if (bits & 1) { if (bits & 1) {
PyType_WatchCallback cb = interp->type_watchers[i]; PyType_WatchCallback cb = interp->type_watchers[i];
if (cb && (cb(type) < 0)) { if (cb && (cb(type) < 0)) {
PyErr_WriteUnraisable((PyObject *)type); PyErr_FormatUnraisable(
"Exception ignored in type watcher callback #%d for %R",
i, type);
} }
} }
i++; i++;
@ -9291,7 +9293,7 @@ releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
// from a Python __buffer__ function. // from a Python __buffer__ function.
mv = PyMemoryView_FromBuffer(buffer); mv = PyMemoryView_FromBuffer(buffer);
if (mv == NULL) { if (mv == NULL) {
PyErr_WriteUnraisable(self); PyErr_FormatUnraisable("Exception ignored in bf_releasebuffer of %s", Py_TYPE(self)->tp_name);
goto end; goto end;
} }
// Set the memoryview to restricted mode, which forbids // Set the memoryview to restricted mode, which forbids
@ -9304,7 +9306,7 @@ releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
PyObject *stack[2] = {self, mv}; PyObject *stack[2] = {self, mv};
PyObject *ret = vectorcall_method(&_Py_ID(__release_buffer__), stack, 2); PyObject *ret = vectorcall_method(&_Py_ID(__release_buffer__), stack, 2);
if (ret == NULL) { if (ret == NULL) {
PyErr_WriteUnraisable(self); PyErr_FormatUnraisable("Exception ignored in __release_buffer__ of %s", Py_TYPE(self)->tp_name);
} }
else { else {
Py_DECREF(ret); Py_DECREF(ret);
@ -9312,7 +9314,7 @@ releasebuffer_call_python(PyObject *self, Py_buffer *buffer)
if (!is_buffer_wrapper) { if (!is_buffer_wrapper) {
PyObject *res = PyObject_CallMethodNoArgs(mv, &_Py_ID(release)); PyObject *res = PyObject_CallMethodNoArgs(mv, &_Py_ID(release));
if (res == NULL) { if (res == NULL) {
PyErr_WriteUnraisable(self); PyErr_FormatUnraisable("Exception ignored in bf_releasebuffer of %s", Py_TYPE(self)->tp_name);
} }
else { else {
Py_DECREF(res); Py_DECREF(res);

View File

@ -2235,7 +2235,7 @@ PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
PyThreadState *tstate = _PyThreadState_GET(); PyThreadState *tstate = _PyThreadState_GET();
if (_PyEval_SetProfile(tstate, func, arg) < 0) { if (_PyEval_SetProfile(tstate, func, arg) < 0) {
/* Log _PySys_Audit() error */ /* Log _PySys_Audit() error */
_PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL); PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfile");
} }
} }
@ -2252,7 +2252,7 @@ PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *arg)
while (ts) { while (ts) {
if (_PyEval_SetProfile(ts, func, arg) < 0) { if (_PyEval_SetProfile(ts, func, arg) < 0) {
_PyErr_WriteUnraisableMsg("in PyEval_SetProfileAllThreads", NULL); PyErr_FormatUnraisable("Exception ignored in PyEval_SetProfileAllThreads");
} }
HEAD_LOCK(runtime); HEAD_LOCK(runtime);
ts = PyThreadState_Next(ts); ts = PyThreadState_Next(ts);
@ -2266,7 +2266,7 @@ PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
PyThreadState *tstate = _PyThreadState_GET(); PyThreadState *tstate = _PyThreadState_GET();
if (_PyEval_SetTrace(tstate, func, arg) < 0) { if (_PyEval_SetTrace(tstate, func, arg) < 0) {
/* Log _PySys_Audit() error */ /* Log _PySys_Audit() error */
_PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL); PyErr_FormatUnraisable("Exception ignored in PyEval_SetTrace");
} }
} }
@ -2283,7 +2283,7 @@ PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *arg)
while (ts) { while (ts) {
if (_PyEval_SetTrace(ts, func, arg) < 0) { if (_PyEval_SetTrace(ts, func, arg) < 0) {
_PyErr_WriteUnraisableMsg("in PyEval_SetTraceAllThreads", NULL); PyErr_FormatUnraisable("Exception ignored in PyEval_SetTraceAllThreads");
} }
HEAD_LOCK(runtime); HEAD_LOCK(runtime);
ts = PyThreadState_Next(ts); ts = PyThreadState_Next(ts);

View File

@ -34,7 +34,6 @@
#include "pycore_flowgraph.h" #include "pycore_flowgraph.h"
#include "pycore_intrinsics.h" #include "pycore_intrinsics.h"
#include "pycore_long.h" // _PyLong_GetZero() #include "pycore_long.h" // _PyLong_GetZero()
#include "pycore_pyerrors.h" // _PyErr_WriteUnraisableMsg()
#include "pycore_pystate.h" // _Py_GetConfig() #include "pycore_pystate.h" // _Py_GetConfig()
#include "pycore_setobject.h" // _PySet_NextEntry() #include "pycore_setobject.h" // _PySet_NextEntry()
#include "pycore_symtable.h" // PySTEntryObject, _PyFuture_FromAST() #include "pycore_symtable.h" // PySTEntryObject, _PyFuture_FromAST()
@ -1407,8 +1406,8 @@ compiler_exit_scope(struct compiler *c)
assert(c->u); assert(c->u);
/* we are deleting from a list so this really shouldn't fail */ /* we are deleting from a list so this really shouldn't fail */
if (PySequence_DelItem(c->c_stack, n) < 0) { if (PySequence_DelItem(c->c_stack, n) < 0) {
_PyErr_WriteUnraisableMsg("on removing the last compiler " PyErr_FormatUnraisable("Exception ignored on removing "
"stack item", NULL); "the last compiler stack item");
} }
} }
else { else {

View File

@ -584,7 +584,7 @@ _PyImport_ClearModulesByIndex(PyInterpreterState *interp)
if (PyList_SetSlice(MODULES_BY_INDEX(interp), if (PyList_SetSlice(MODULES_BY_INDEX(interp),
0, PyList_GET_SIZE(MODULES_BY_INDEX(interp)), 0, PyList_GET_SIZE(MODULES_BY_INDEX(interp)),
NULL)) { NULL)) {
PyErr_WriteUnraisable(MODULES_BY_INDEX(interp)); PyErr_FormatUnraisable("Exception ignored on clearing interpreters module list");
} }
} }
@ -3156,13 +3156,13 @@ _PyImport_FiniCore(PyInterpreterState *interp)
int verbose = _PyInterpreterState_GetConfig(interp)->verbose; int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) { if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing sys.meta_path");
} }
// XXX Pull in most of finalize_modules() in pylifecycle.c. // XXX Pull in most of finalize_modules() in pylifecycle.c.
if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) { if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing sys.modules");
} }
if (IMPORT_LOCK(interp) != NULL) { if (IMPORT_LOCK(interp) != NULL) {
@ -3242,10 +3242,10 @@ _PyImport_FiniExternal(PyInterpreterState *interp)
// XXX Uninstall importlib metapath importers here? // XXX Uninstall importlib metapath importers here?
if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) { if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing sys.path_importer_cache");
} }
if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) { if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing sys.path_hooks");
} }
} }

View File

@ -133,7 +133,6 @@ any DWARF information available for them).
#include "pycore_ceval.h" // _PyPerf_Callbacks #include "pycore_ceval.h" // _PyPerf_Callbacks
#include "pycore_frame.h" #include "pycore_frame.h"
#include "pycore_interp.h" #include "pycore_interp.h"
#include "pycore_pyerrors.h" // _PyErr_WriteUnraisableMsg()
#ifdef PY_HAVE_PERF_TRAMPOLINE #ifdef PY_HAVE_PERF_TRAMPOLINE
@ -236,8 +235,7 @@ new_code_arena(void)
0); // offset (not used here) 0); // offset (not used here)
if (!memory) { if (!memory) {
PyErr_SetFromErrno(PyExc_OSError); PyErr_SetFromErrno(PyExc_OSError);
_PyErr_WriteUnraisableMsg( PyErr_FormatUnraisable("Failed to create new mmap for perf trampoline");
"Failed to create new mmap for perf trampoline", NULL);
perf_status = PERF_STATUS_FAILED; perf_status = PERF_STATUS_FAILED;
return -1; return -1;
} }
@ -261,9 +259,8 @@ new_code_arena(void)
if (res == -1) { if (res == -1) {
PyErr_SetFromErrno(PyExc_OSError); PyErr_SetFromErrno(PyExc_OSError);
munmap(memory, mem_size); munmap(memory, mem_size);
_PyErr_WriteUnraisableMsg( PyErr_FormatUnraisable("Failed to set mmap for perf trampoline to "
"Failed to set mmap for perf trampoline to PROT_READ | PROT_EXEC", "PROT_READ | PROT_EXEC");
NULL);
return -1; return -1;
} }
@ -277,8 +274,7 @@ new_code_arena(void)
if (new_arena == NULL) { if (new_arena == NULL) {
PyErr_NoMemory(); PyErr_NoMemory();
munmap(memory, mem_size); munmap(memory, mem_size);
_PyErr_WriteUnraisableMsg("Failed to allocate new code arena struct", PyErr_FormatUnraisable("Failed to allocate new code arena struct for perf trampoline");
NULL);
return -1; return -1;
} }

View File

@ -1419,13 +1419,13 @@ finalize_modules_delete_special(PyThreadState *tstate, int verbose)
PySys_WriteStderr("# clear builtins._\n"); PySys_WriteStderr("# clear builtins._\n");
} }
if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) { if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on setting builtin variable _");
} }
const char * const *p; const char * const *p;
for (p = sys_deletes; *p != NULL; p++) { for (p = sys_deletes; *p != NULL; p++) {
if (_PySys_ClearAttrString(interp, *p, verbose) < 0) { if (_PySys_ClearAttrString(interp, *p, verbose) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing sys.%s", *p);
} }
} }
for (p = sys_files; *p != NULL; p+=2) { for (p = sys_files; *p != NULL; p+=2) {
@ -1436,13 +1436,13 @@ finalize_modules_delete_special(PyThreadState *tstate, int verbose)
} }
PyObject *value; PyObject *value;
if (PyDict_GetItemStringRef(interp->sysdict, orig_name, &value) < 0) { if (PyDict_GetItemStringRef(interp->sysdict, orig_name, &value) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on restoring sys.%s", name);
} }
if (value == NULL) { if (value == NULL) {
value = Py_NewRef(Py_None); value = Py_NewRef(Py_None);
} }
if (PyDict_SetItemString(interp->sysdict, name, value) < 0) { if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on restoring sys.%s", name);
} }
Py_DECREF(value); Py_DECREF(value);
} }
@ -1454,7 +1454,7 @@ finalize_remove_modules(PyObject *modules, int verbose)
{ {
PyObject *weaklist = PyList_New(0); PyObject *weaklist = PyList_New(0);
if (weaklist == NULL) { if (weaklist == NULL) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on removing modules");
} }
#define STORE_MODULE_WEAKREF(name, mod) \ #define STORE_MODULE_WEAKREF(name, mod) \
@ -1463,13 +1463,13 @@ finalize_remove_modules(PyObject *modules, int verbose)
if (wr) { \ if (wr) { \
PyObject *tup = PyTuple_Pack(2, name, wr); \ PyObject *tup = PyTuple_Pack(2, name, wr); \
if (!tup || PyList_Append(weaklist, tup) < 0) { \ if (!tup || PyList_Append(weaklist, tup) < 0) { \
PyErr_WriteUnraisable(NULL); \ PyErr_FormatUnraisable("Exception ignored on removing modules"); \
} \ } \
Py_XDECREF(tup); \ Py_XDECREF(tup); \
Py_DECREF(wr); \ Py_DECREF(wr); \
} \ } \
else { \ else { \
PyErr_WriteUnraisable(NULL); \ PyErr_FormatUnraisable("Exception ignored on removing modules"); \
} \ } \
} }
@ -1480,7 +1480,7 @@ finalize_remove_modules(PyObject *modules, int verbose)
} \ } \
STORE_MODULE_WEAKREF(name, mod); \ STORE_MODULE_WEAKREF(name, mod); \
if (PyObject_SetItem(modules, name, Py_None) < 0) { \ if (PyObject_SetItem(modules, name, Py_None) < 0) { \
PyErr_WriteUnraisable(NULL); \ PyErr_FormatUnraisable("Exception ignored on removing modules"); \
} \ } \
} }
@ -1494,14 +1494,14 @@ finalize_remove_modules(PyObject *modules, int verbose)
else { else {
PyObject *iterator = PyObject_GetIter(modules); PyObject *iterator = PyObject_GetIter(modules);
if (iterator == NULL) { if (iterator == NULL) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on removing modules");
} }
else { else {
PyObject *key; PyObject *key;
while ((key = PyIter_Next(iterator))) { while ((key = PyIter_Next(iterator))) {
PyObject *value = PyObject_GetItem(modules, key); PyObject *value = PyObject_GetItem(modules, key);
if (value == NULL) { if (value == NULL) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on removing modules");
continue; continue;
} }
CLEAR_MODULE(key, value); CLEAR_MODULE(key, value);
@ -1509,7 +1509,7 @@ finalize_remove_modules(PyObject *modules, int verbose)
Py_DECREF(key); Py_DECREF(key);
} }
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on removing modules");
} }
Py_DECREF(iterator); Py_DECREF(iterator);
} }
@ -1529,7 +1529,7 @@ finalize_clear_modules_dict(PyObject *modules)
} }
else { else {
if (PyObject_CallMethodNoArgs(modules, &_Py_ID(clear)) == NULL) { if (PyObject_CallMethodNoArgs(modules, &_Py_ID(clear)) == NULL) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on clearing sys.modules");
} }
} }
} }
@ -1541,11 +1541,11 @@ finalize_restore_builtins(PyThreadState *tstate)
PyInterpreterState *interp = tstate->interp; PyInterpreterState *interp = tstate->interp;
PyObject *dict = PyDict_Copy(interp->builtins); PyObject *dict = PyDict_Copy(interp->builtins);
if (dict == NULL) { if (dict == NULL) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on restoring builtins");
} }
PyDict_Clear(interp->builtins); PyDict_Clear(interp->builtins);
if (PyDict_Update(interp->builtins, interp->builtins_copy)) { if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on restoring builtins");
} }
Py_XDECREF(dict); Py_XDECREF(dict);
} }
@ -1707,7 +1707,7 @@ flush_std_files(void)
if (fout != NULL && fout != Py_None && !file_is_closed(fout)) { if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
if (_PyFile_Flush(fout) < 0) { if (_PyFile_Flush(fout) < 0) {
PyErr_WriteUnraisable(fout); PyErr_FormatUnraisable("Exception ignored on flushing sys.stdout");
status = -1; status = -1;
} }
} }
@ -3037,14 +3037,14 @@ wait_for_thread_shutdown(PyThreadState *tstate)
PyObject *threading = PyImport_GetModule(&_Py_ID(threading)); PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
if (threading == NULL) { if (threading == NULL) {
if (_PyErr_Occurred(tstate)) { if (_PyErr_Occurred(tstate)) {
PyErr_WriteUnraisable(NULL); PyErr_FormatUnraisable("Exception ignored on threading shutdown");
} }
/* else: threading not imported */ /* else: threading not imported */
return; return;
} }
result = PyObject_CallMethodNoArgs(threading, &_Py_ID(_shutdown)); result = PyObject_CallMethodNoArgs(threading, &_Py_ID(_shutdown));
if (result == NULL) { if (result == NULL) {
PyErr_WriteUnraisable(threading); PyErr_FormatUnraisable("Exception ignored on threading shutdown");
} }
else { else {
Py_DECREF(result); Py_DECREF(result);

View File

@ -650,7 +650,7 @@ _PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
PyErr_Clear(); PyErr_Clear();
goto done; goto done;
} }
_PyErr_WriteUnraisableMsg("in audit hook", NULL); PyErr_FormatUnraisable("Exception ignored in audit hook");
} }
if (hook) { if (hook) {
PyObject* args[3] = {typ, exc, tb}; PyObject* args[3] = {typ, exc, tb};
@ -1093,7 +1093,8 @@ fallback:
_PyRuntime.signals.unhandled_keyboard_interrupt = unhandled_keyboard_interrupt; _PyRuntime.signals.unhandled_keyboard_interrupt = unhandled_keyboard_interrupt;
#ifdef Py_DEBUG #ifdef Py_DEBUG
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
_PyErr_WriteUnraisableMsg("in the internal traceback machinery", NULL); PyErr_FormatUnraisable(
"Exception ignored in the internal traceback machinery");
} }
#endif #endif
PyErr_Clear(); PyErr_Clear();