|
13 | 13 | #include "pycore_traceback.h" // _PyTraceBack_FromFrame() |
14 | 14 | #include "pycore_unicodeobject.h" // _PyUnicode_Equal() |
15 | 15 |
|
| 16 | +#include <stdio.h> // fopen, fclose |
| 17 | +#include <limits.h> // PATH_MAX |
| 18 | +#include <string.h> // strlen |
| 19 | + |
16 | 20 | #ifdef MS_WINDOWS |
17 | 21 | # include <windows.h> |
18 | 22 | # include <winbase.h> |
@@ -1488,25 +1492,27 @@ write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type, |
1488 | 1492 | } |
1489 | 1493 | } |
1490 | 1494 |
|
1491 | | - // Try printing the exception using the stdlib module. |
1492 | | - // If this fails, then we have to use the C implementation. |
1493 | | - PyObject *print_exception_fn = PyImport_ImportModuleAttrString("traceback", |
1494 | | - "_print_exception_bltin"); |
1495 | | - if (print_exception_fn != NULL && PyCallable_Check(print_exception_fn)) { |
1496 | | - PyObject *args[2] = {exc_value, file}; |
1497 | | - PyObject *result = PyObject_Vectorcall(print_exception_fn, args, 2, NULL); |
1498 | | - int ok = (result != NULL); |
1499 | | - Py_DECREF(print_exception_fn); |
1500 | | - Py_XDECREF(result); |
1501 | | - if (ok) { |
1502 | | - // Nothing else to do |
1503 | | - return 0; |
| 1495 | + // Try printing the exception using the stdlib module, but be careful about |
| 1496 | + // traceback module shadowing (issue gh-138170). Use safe import check. |
| 1497 | + if (_PyTraceback_IsSafeToImport()) { |
| 1498 | + PyObject *print_exception_fn = PyImport_ImportModuleAttrString("traceback", "_print_exception_bltin"); |
| 1499 | + if (print_exception_fn != NULL && PyCallable_Check(print_exception_fn)) { |
| 1500 | + PyObject *args[2] = {exc_value, file}; |
| 1501 | + PyObject *result = PyObject_Vectorcall(print_exception_fn, args, 2, NULL); |
| 1502 | + int ok = (result != NULL); |
| 1503 | + Py_DECREF(print_exception_fn); |
| 1504 | + Py_XDECREF(result); |
| 1505 | + if (ok) { |
| 1506 | + // Nothing else to do |
| 1507 | + return 0; |
| 1508 | + } |
| 1509 | + } |
| 1510 | + else { |
| 1511 | + Py_XDECREF(print_exception_fn); |
1504 | 1512 | } |
1505 | 1513 | } |
1506 | | - else { |
1507 | | - Py_XDECREF(print_exception_fn); |
1508 | | - } |
1509 | | - // traceback module failed, fall back to pure C |
| 1514 | + |
| 1515 | + // traceback module failed or unsafe, fall back to pure C |
1510 | 1516 | _PyErr_Clear(tstate); |
1511 | 1517 |
|
1512 | 1518 | if (exc_tb != NULL && exc_tb != Py_None) { |
|
0 commit comments