Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/traceback.c
Line
Count
Source
1
2
/* Traceback implementation */
3
4
#include "Python.h"
5
#include "pycore_call.h"          // _PyObject_CallMethod()
6
#include "pycore_fileutils.h"     // _Py_BEGIN_SUPPRESS_IPH
7
#include "pycore_freelist.h"      // _Py_FREELIST_POP()
8
#include "pycore_frame.h"         // PyFrameObject
9
#include "pycore_interp.h"        // PyInterpreterState.gc
10
#include "pycore_interpframe.h"   // _PyFrame_GetCode()
11
#include "pycore_pyerrors.h"      // _PyErr_GetRaisedException()
12
#include "pycore_pystate.h"       // _PyThreadState_GET()
13
#include "pycore_traceback.h"     // EXCEPTION_TB_HEADER
14
15
#include "frameobject.h"          // PyFrame_New()
16
#include "../Parser/tokenizer/tokenizer.h"
17
18
#include "osdefs.h"               // SEP
19
#ifdef HAVE_UNISTD_H
20
#  include <unistd.h>             // lseek()
21
#endif
22
23
#if (defined(HAVE_EXECINFO_H) && defined(HAVE_DLFCN_H) && defined(HAVE_LINK_H))
24
#  define _PY_HAS_BACKTRACE_HEADERS 1
25
#endif
26
27
#if (defined(__APPLE__) && defined(HAVE_EXECINFO_H) && defined(HAVE_DLFCN_H))
28
#  define _PY_HAS_BACKTRACE_HEADERS 1
29
#endif
30
31
#ifdef _PY_HAS_BACKTRACE_HEADERS
32
#  include <execinfo.h>           // backtrace(), backtrace_symbols()
33
#  include <dlfcn.h>              // dladdr1()
34
#ifdef HAVE_LINK_H
35
#    include <link.h>               // struct DL_info
36
#endif
37
#  if defined(__APPLE__) && defined(HAVE_BACKTRACE) && defined(HAVE_DLADDR)
38
#    define CAN_C_BACKTRACE
39
#  elif defined(HAVE_BACKTRACE) && defined(HAVE_DLADDR1)
40
#    define CAN_C_BACKTRACE
41
#  endif
42
#endif
43
44
#if defined(__STDC_NO_VLA__) && (__STDC_NO_VLA__ == 1)
45
/* Use alloca() for VLAs. */
46
#  define VLA(type, name, size) type *name = alloca(sizeof(type) * (size))
47
#elif !defined(__STDC_NO_VLA__) || (__STDC_NO_VLA__ == 0)
48
/* Use actual C VLAs.*/
49
0
#  define VLA(type, name, size) type name[size]
50
#elif defined(CAN_C_BACKTRACE)
51
/* VLAs are not possible. Disable C stack trace functions. */
52
#  undef CAN_C_BACKTRACE
53
#endif
54
55
#define OFF(x) offsetof(PyTracebackObject, x)
56
0
#define PUTS(fd, str) (void)_Py_write_noraise(fd, str, strlen(str))
57
58
0
#define MAX_STRING_LENGTH 500
59
0
#define MAX_FRAME_DEPTH 100
60
0
#define DEFAULT_MAX_NTHREADS 100
61
62
/*[clinic input]
63
class traceback "PyTracebackObject *" "&PyTraceback_Type"
64
[clinic start generated code]*/
65
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=cf96294b2bebc811]*/
66
67
66.3M
#define _PyTracebackObject_CAST(op)   ((PyTracebackObject *)(op))
68
69
#include "clinic/traceback.c.h"
70
71
72
#ifdef MS_WINDOWS
73
typedef HRESULT (WINAPI *PF_GET_THREAD_DESCRIPTION)(HANDLE, PWSTR*);
74
static PF_GET_THREAD_DESCRIPTION pGetThreadDescription = NULL;
75
#endif
76
77
78
static PyObject *
79
tb_create_raw(PyTracebackObject *next, PyFrameObject *frame, int lasti,
80
              int lineno)
81
66.0M
{
82
66.0M
    PyTracebackObject *tb;
83
66.0M
    assert(next == NULL || PyTraceBack_Check(next));
84
66.0M
    assert(frame != NULL);
85
66.0M
    assert(PyFrame_Check(frame));
86
66.0M
    tb = _Py_FREELIST_POP(PyTracebackObject, tracebacks);
87
66.0M
    if (tb == NULL) {
88
580k
        tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type);
89
580k
    }
90
66.0M
    if (tb != NULL) {
91
66.0M
        tb->tb_next = (PyTracebackObject*)Py_XNewRef(next);
92
66.0M
        tb->tb_frame = (PyFrameObject*)Py_NewRef(frame);
93
66.0M
        tb->tb_lasti = lasti;
94
66.0M
        tb->tb_lineno = lineno;
95
66.0M
        PyObject_GC_Track(tb);
96
66.0M
    }
97
66.0M
    return (PyObject *)tb;
98
66.0M
}
99
100
/*[clinic input]
101
@classmethod
102
traceback.__new__ as tb_new
103
104
  tb_next: object
105
  tb_frame: object(type='PyFrameObject *', subclass_of='&PyFrame_Type')
106
  tb_lasti: int
107
  tb_lineno: int
108
109
Create a new traceback object.
110
[clinic start generated code]*/
111
112
static PyObject *
113
tb_new_impl(PyTypeObject *type, PyObject *tb_next, PyFrameObject *tb_frame,
114
            int tb_lasti, int tb_lineno)
115
/*[clinic end generated code: output=fa077debd72d861a input=b88143145454cb59]*/
116
0
{
117
0
    if (tb_next == Py_None) {
118
0
        tb_next = NULL;
119
0
    } else if (!PyTraceBack_Check(tb_next)) {
120
0
        return PyErr_Format(PyExc_TypeError,
121
0
                            "expected traceback object or None, got '%s'",
122
0
                            Py_TYPE(tb_next)->tp_name);
123
0
    }
124
125
0
    return tb_create_raw((PyTracebackObject *)tb_next, tb_frame, tb_lasti,
126
0
                         tb_lineno);
127
0
}
128
129
static PyObject *
130
tb_dir(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(ignored))
131
0
{
132
0
    return Py_BuildValue("[ssss]", "tb_frame", "tb_next",
133
0
                                   "tb_lasti", "tb_lineno");
134
0
}
135
136
/*[clinic input]
137
@critical_section
138
@getter
139
traceback.tb_next
140
[clinic start generated code]*/
141
142
static PyObject *
143
traceback_tb_next_get_impl(PyTracebackObject *self)
144
/*[clinic end generated code: output=963634df7d5fc837 input=8f6345f2b73cb965]*/
145
0
{
146
0
    PyObject* ret = (PyObject*)self->tb_next;
147
0
    if (!ret) {
148
0
        ret = Py_None;
149
0
    }
150
0
    return Py_NewRef(ret);
151
0
}
152
153
static int
154
tb_get_lineno(PyObject *op)
155
0
{
156
0
    PyTracebackObject *tb = _PyTracebackObject_CAST(op);
157
0
    _PyInterpreterFrame* frame = tb->tb_frame->f_frame;
158
0
    assert(frame != NULL);
159
0
    return PyCode_Addr2Line(_PyFrame_GetCode(frame), tb->tb_lasti);
160
0
}
161
162
static PyObject *
163
tb_lineno_get(PyObject *op, void *Py_UNUSED(_))
164
0
{
165
0
    PyTracebackObject *self = _PyTracebackObject_CAST(op);
166
0
    int lineno = self->tb_lineno;
167
0
    if (lineno == -1) {
168
0
        lineno = tb_get_lineno(op);
169
0
        if (lineno < 0) {
170
0
            Py_RETURN_NONE;
171
0
        }
172
0
    }
173
0
    return PyLong_FromLong(lineno);
174
0
}
175
176
/*[clinic input]
177
@critical_section
178
@setter
179
traceback.tb_next
180
[clinic start generated code]*/
181
182
static int
183
traceback_tb_next_set_impl(PyTracebackObject *self, PyObject *value)
184
/*[clinic end generated code: output=d4868cbc48f2adac input=ce66367f85e3c443]*/
185
0
{
186
    /* We accept None or a traceback object, and map None -> NULL (inverse of
187
       tb_next_get) */
188
0
    if (value == Py_None) {
189
0
        value = NULL;
190
0
    } else if (!PyTraceBack_Check(value)) {
191
0
        PyErr_Format(PyExc_TypeError,
192
0
                     "expected traceback object, got '%s'",
193
0
                     Py_TYPE(value)->tp_name);
194
0
        return -1;
195
0
    }
196
197
    /* Check for loops */
198
0
    PyTracebackObject *cursor = (PyTracebackObject *)value;
199
0
    Py_XINCREF(cursor);
200
0
    while (cursor) {
201
0
        if (cursor == self) {
202
0
            PyErr_Format(PyExc_ValueError, "traceback loop detected");
203
0
            Py_DECREF(cursor);
204
0
            return -1;
205
0
        }
206
0
        Py_BEGIN_CRITICAL_SECTION(cursor);
207
0
        Py_XINCREF(cursor->tb_next);
208
0
        Py_SETREF(cursor, cursor->tb_next);
209
0
        Py_END_CRITICAL_SECTION();
210
0
    }
211
212
0
    Py_XSETREF(self->tb_next, (PyTracebackObject *)Py_XNewRef(value));
213
214
0
    return 0;
215
0
}
216
217
218
static PyMethodDef tb_methods[] = {
219
   {"__dir__", tb_dir, METH_NOARGS, NULL},
220
   {NULL, NULL, 0, NULL},
221
};
222
223
static PyMemberDef tb_memberlist[] = {
224
    {"tb_frame",        _Py_T_OBJECT,       OFF(tb_frame),  Py_READONLY|Py_AUDIT_READ},
225
    {"tb_lasti",        Py_T_INT,          OFF(tb_lasti),  Py_READONLY},
226
    {NULL}      /* Sentinel */
227
};
228
229
static PyGetSetDef tb_getsetters[] = {
230
    TRACEBACK_TB_NEXT_GETSETDEF
231
    {"tb_lineno", tb_lineno_get, NULL, NULL, NULL},
232
    {NULL}      /* Sentinel */
233
};
234
235
static void
236
tb_dealloc(PyObject *op)
237
66.0M
{
238
66.0M
    PyTracebackObject *tb = _PyTracebackObject_CAST(op);
239
66.0M
    PyObject_GC_UnTrack(tb);
240
66.0M
    Py_XDECREF(tb->tb_next);
241
66.0M
    Py_XDECREF(tb->tb_frame);
242
66.0M
    _Py_FREELIST_FREE(tracebacks, tb, PyObject_GC_Del);
243
66.0M
}
244
245
static int
246
tb_traverse(PyObject *op, visitproc visit, void *arg)
247
305k
{
248
305k
    PyTracebackObject *tb = _PyTracebackObject_CAST(op);
249
305k
    Py_VISIT(tb->tb_next);
250
305k
    Py_VISIT(tb->tb_frame);
251
305k
    return 0;
252
305k
}
253
254
static int
255
tb_clear(PyObject *op)
256
0
{
257
0
    PyTracebackObject *tb = _PyTracebackObject_CAST(op);
258
0
    Py_CLEAR(tb->tb_next);
259
0
    Py_CLEAR(tb->tb_frame);
260
0
    return 0;
261
0
}
262
263
PyTypeObject PyTraceBack_Type = {
264
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
265
    "traceback",
266
    sizeof(PyTracebackObject),
267
    0,
268
    tb_dealloc,         /*tp_dealloc*/
269
    0,                  /*tp_vectorcall_offset*/
270
    0,    /*tp_getattr*/
271
    0,                  /*tp_setattr*/
272
    0,                  /*tp_as_async*/
273
    0,                  /*tp_repr*/
274
    0,                  /*tp_as_number*/
275
    0,                  /*tp_as_sequence*/
276
    0,                  /*tp_as_mapping*/
277
    0,                  /* tp_hash */
278
    0,                  /* tp_call */
279
    0,                  /* tp_str */
280
    PyObject_GenericGetAttr,                    /* tp_getattro */
281
    0,                  /* tp_setattro */
282
    0,                                          /* tp_as_buffer */
283
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
284
    tb_new__doc__,                              /* tp_doc */
285
    tb_traverse,                                /* tp_traverse */
286
    tb_clear,                                   /* tp_clear */
287
    0,                                          /* tp_richcompare */
288
    0,                                          /* tp_weaklistoffset */
289
    0,                                          /* tp_iter */
290
    0,                                          /* tp_iternext */
291
    tb_methods,         /* tp_methods */
292
    tb_memberlist,      /* tp_members */
293
    tb_getsetters,                              /* tp_getset */
294
    0,                                          /* tp_base */
295
    0,                                          /* tp_dict */
296
    0,                                          /* tp_descr_get */
297
    0,                                          /* tp_descr_set */
298
    0,                                          /* tp_dictoffset */
299
    0,                                          /* tp_init */
300
    0,                                          /* tp_alloc */
301
    tb_new,                                     /* tp_new */
302
};
303
304
305
PyObject*
306
_PyTraceBack_FromFrame(PyObject *tb_next, PyFrameObject *frame)
307
66.0M
{
308
66.0M
    assert(tb_next == NULL || PyTraceBack_Check(tb_next));
309
66.0M
    assert(frame != NULL);
310
66.0M
    int addr = _PyInterpreterFrame_LASTI(frame->f_frame) * sizeof(_Py_CODEUNIT);
311
66.0M
    return tb_create_raw((PyTracebackObject *)tb_next, frame, addr, -1);
312
66.0M
}
313
314
315
int
316
PyTraceBack_Here(PyFrameObject *frame)
317
66.0M
{
318
66.0M
    PyObject *exc = PyErr_GetRaisedException();
319
66.0M
    assert(PyExceptionInstance_Check(exc));
320
66.0M
    PyObject *tb = PyException_GetTraceback(exc);
321
66.0M
    PyObject *newtb = _PyTraceBack_FromFrame(tb, frame);
322
66.0M
    Py_XDECREF(tb);
323
66.0M
    if (newtb == NULL) {
324
0
        _PyErr_ChainExceptions1(exc);
325
0
        return -1;
326
0
    }
327
66.0M
    PyException_SetTraceback(exc, newtb);
328
66.0M
    Py_XDECREF(newtb);
329
66.0M
    PyErr_SetRaisedException(exc);
330
66.0M
    return 0;
331
66.0M
}
332
333
/* Insert a frame into the traceback for (funcname, filename, lineno). */
334
void _PyTraceback_Add(const char *funcname, const char *filename, int lineno)
335
1.13k
{
336
1.13k
    PyObject *globals;
337
1.13k
    PyCodeObject *code;
338
1.13k
    PyFrameObject *frame;
339
1.13k
    PyThreadState *tstate = _PyThreadState_GET();
340
341
    /* Save and clear the current exception. Python functions must not be
342
       called with an exception set. Calling Python functions happens when
343
       the codec of the filesystem encoding is implemented in pure Python. */
344
1.13k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
345
346
1.13k
    globals = PyDict_New();
347
1.13k
    if (!globals)
348
0
        goto error;
349
1.13k
    code = PyCode_NewEmpty(filename, funcname, lineno);
350
1.13k
    if (!code) {
351
0
        Py_DECREF(globals);
352
0
        goto error;
353
0
    }
354
1.13k
    frame = PyFrame_New(tstate, code, globals, NULL);
355
1.13k
    Py_DECREF(globals);
356
1.13k
    Py_DECREF(code);
357
1.13k
    if (!frame)
358
0
        goto error;
359
1.13k
    frame->f_lineno = lineno;
360
361
1.13k
    _PyErr_SetRaisedException(tstate, exc);
362
1.13k
    PyTraceBack_Here(frame);
363
1.13k
    Py_DECREF(frame);
364
1.13k
    return;
365
366
0
error:
367
0
    _PyErr_ChainExceptions1(exc);
368
0
}
369
370
static PyObject *
371
_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
372
0
{
373
0
    Py_ssize_t i;
374
0
    PyObject *binary;
375
0
    PyObject *v;
376
0
    Py_ssize_t npath;
377
0
    size_t taillen;
378
0
    PyObject *syspath;
379
0
    PyObject *path;
380
0
    const char* tail;
381
0
    PyObject *filebytes;
382
0
    const char* filepath;
383
0
    Py_ssize_t len;
384
0
    PyObject* result;
385
0
    PyObject *open = NULL;
386
387
0
    filebytes = PyUnicode_EncodeFSDefault(filename);
388
0
    if (filebytes == NULL) {
389
0
        PyErr_Clear();
390
0
        return NULL;
391
0
    }
392
0
    filepath = PyBytes_AS_STRING(filebytes);
393
394
    /* Search tail of filename in sys.path before giving up */
395
0
    tail = strrchr(filepath, SEP);
396
0
    if (tail == NULL)
397
0
        tail = filepath;
398
0
    else
399
0
        tail++;
400
0
    taillen = strlen(tail);
401
402
0
    if (PySys_GetOptionalAttr(&_Py_ID(path), &syspath) < 0) {
403
0
        PyErr_Clear();
404
0
        goto error;
405
0
    }
406
0
    if (syspath == NULL || !PyList_Check(syspath)) {
407
0
        goto error;
408
0
    }
409
0
    npath = PyList_Size(syspath);
410
411
0
    open = PyObject_GetAttr(io, &_Py_ID(open));
412
0
    if (open == NULL) {
413
0
        goto error;
414
0
    }
415
0
    for (i = 0; i < npath; i++) {
416
0
        v = PyList_GetItem(syspath, i);
417
0
        if (v == NULL) {
418
0
            PyErr_Clear();
419
0
            break;
420
0
        }
421
0
        if (!PyUnicode_Check(v))
422
0
            continue;
423
0
        path = PyUnicode_EncodeFSDefault(v);
424
0
        if (path == NULL) {
425
0
            PyErr_Clear();
426
0
            continue;
427
0
        }
428
0
        len = PyBytes_GET_SIZE(path);
429
0
        if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) {
430
0
            Py_DECREF(path);
431
0
            continue; /* Too long */
432
0
        }
433
0
        strcpy(namebuf, PyBytes_AS_STRING(path));
434
0
        Py_DECREF(path);
435
0
        if (strlen(namebuf) != (size_t)len)
436
0
            continue; /* v contains '\0' */
437
0
        if (len > 0 && namebuf[len-1] != SEP)
438
0
            namebuf[len++] = SEP;
439
0
        strcpy(namebuf+len, tail);
440
441
0
        binary = PyObject_CallFunction(open, "ss", namebuf, "rb");
442
0
        if (binary != NULL) {
443
0
            result = binary;
444
0
            goto finally;
445
0
        }
446
0
        PyErr_Clear();
447
0
    }
448
0
    goto error;
449
450
0
error:
451
0
    result = NULL;
452
0
finally:
453
0
    Py_XDECREF(open);
454
0
    Py_XDECREF(syspath);
455
0
    Py_DECREF(filebytes);
456
0
    return result;
457
0
}
458
459
/* Writes indent spaces. Returns 0 on success and non-zero on failure.
460
 */
461
int
462
_Py_WriteIndent(int indent, PyObject *f)
463
0
{
464
0
    char buf[11] = "          ";
465
0
    assert(strlen(buf) == 10);
466
0
    while (indent > 0) {
467
0
        if (indent < 10) {
468
0
            buf[indent] = '\0';
469
0
        }
470
0
        if (PyFile_WriteString(buf, f) < 0) {
471
0
            return -1;
472
0
        }
473
0
        indent -= 10;
474
0
    }
475
0
    return 0;
476
0
}
477
478
static int
479
display_source_line(PyObject *f, PyObject *filename, int lineno, int indent,
480
                    int *truncation, PyObject **line)
481
0
{
482
0
    int fd;
483
0
    int i;
484
0
    char *found_encoding;
485
0
    const char *encoding;
486
0
    PyObject *io;
487
0
    PyObject *binary;
488
0
    PyObject *fob = NULL;
489
0
    PyObject *lineobj = NULL;
490
0
    PyObject *res;
491
0
    char buf[MAXPATHLEN+1];
492
0
    int kind;
493
0
    const void *data;
494
495
    /* open the file */
496
0
    if (filename == NULL)
497
0
        return 0;
498
499
    /* Do not attempt to open things like <string> or <stdin> */
500
0
    assert(PyUnicode_Check(filename));
501
0
    if (PyUnicode_READ_CHAR(filename, 0) == '<') {
502
0
        Py_ssize_t len = PyUnicode_GET_LENGTH(filename);
503
0
        if (len > 0 && PyUnicode_READ_CHAR(filename, len - 1) == '>') {
504
0
            return 0;
505
0
        }
506
0
    }
507
508
0
    io = PyImport_ImportModule("io");
509
0
    if (io == NULL) {
510
0
        return -1;
511
0
    }
512
513
0
    binary = _PyObject_CallMethod(io, &_Py_ID(open), "Os", filename, "rb");
514
0
    if (binary == NULL) {
515
0
        PyErr_Clear();
516
517
0
        binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io);
518
0
        if (binary == NULL) {
519
0
            Py_DECREF(io);
520
0
            return -1;
521
0
        }
522
0
    }
523
524
    /* use the right encoding to decode the file as unicode */
525
0
    fd = PyObject_AsFileDescriptor(binary);
526
0
    if (fd < 0) {
527
0
        Py_DECREF(io);
528
0
        Py_DECREF(binary);
529
0
        return 0;
530
0
    }
531
0
    found_encoding = _PyTokenizer_FindEncodingFilename(fd, filename);
532
0
    if (found_encoding == NULL)
533
0
        PyErr_Clear();
534
0
    encoding = (found_encoding != NULL) ? found_encoding : "utf-8";
535
    /* Reset position */
536
0
    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
537
0
        Py_DECREF(io);
538
0
        Py_DECREF(binary);
539
0
        PyMem_Free(found_encoding);
540
0
        return 0;
541
0
    }
542
0
    fob = _PyObject_CallMethod(io, &_Py_ID(TextIOWrapper),
543
0
                               "Os", binary, encoding);
544
0
    Py_DECREF(io);
545
0
    PyMem_Free(found_encoding);
546
547
0
    if (fob == NULL) {
548
0
        PyErr_Clear();
549
550
0
        res = PyObject_CallMethodNoArgs(binary, &_Py_ID(close));
551
0
        Py_DECREF(binary);
552
0
        if (res)
553
0
            Py_DECREF(res);
554
0
        else
555
0
            PyErr_Clear();
556
0
        return 0;
557
0
    }
558
0
    Py_DECREF(binary);
559
560
    /* get the line number lineno */
561
0
    for (i = 0; i < lineno; i++) {
562
0
        Py_XDECREF(lineobj);
563
0
        lineobj = PyFile_GetLine(fob, -1);
564
0
        if (!lineobj) {
565
0
            PyErr_Clear();
566
0
            break;
567
0
        }
568
0
    }
569
0
    res = PyObject_CallMethodNoArgs(fob, &_Py_ID(close));
570
0
    if (res) {
571
0
        Py_DECREF(res);
572
0
    }
573
0
    else {
574
0
        PyErr_Clear();
575
0
    }
576
0
    Py_DECREF(fob);
577
0
    if (!lineobj || !PyUnicode_Check(lineobj)) {
578
0
        Py_XDECREF(lineobj);
579
0
        return -1;
580
0
    }
581
582
0
    if (line) {
583
0
        *line = Py_NewRef(lineobj);
584
0
    }
585
586
    /* remove the indentation of the line */
587
0
    kind = PyUnicode_KIND(lineobj);
588
0
    data = PyUnicode_DATA(lineobj);
589
0
    for (i=0; i < PyUnicode_GET_LENGTH(lineobj); i++) {
590
0
        Py_UCS4 ch = PyUnicode_READ(kind, data, i);
591
0
        if (ch != ' ' && ch != '\t' && ch != '\014')
592
0
            break;
593
0
    }
594
0
    if (i) {
595
0
        PyObject *truncated;
596
0
        truncated = PyUnicode_Substring(lineobj, i, PyUnicode_GET_LENGTH(lineobj));
597
0
        if (truncated) {
598
0
            Py_SETREF(lineobj, truncated);
599
0
        } else {
600
0
            PyErr_Clear();
601
0
        }
602
0
    }
603
604
0
    if (truncation != NULL) {
605
0
        *truncation = i - indent;
606
0
    }
607
608
    /* Write some spaces before the line */
609
0
    if (_Py_WriteIndent(indent, f) < 0) {
610
0
        goto error;
611
0
    }
612
613
    /* finally display the line */
614
0
    if (PyFile_WriteObject(lineobj, f, Py_PRINT_RAW) < 0) {
615
0
        goto error;
616
0
    }
617
618
0
    if (PyFile_WriteString("\n", f) < 0) {
619
0
        goto error;
620
0
    }
621
622
0
    Py_DECREF(lineobj);
623
0
    return 0;
624
0
error:
625
0
    Py_DECREF(lineobj);
626
0
    return -1;
627
0
}
628
629
int
630
_Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent,
631
                      int *truncation, PyObject **line)
632
0
{
633
0
    return display_source_line(f, filename, lineno, indent, truncation, line);
634
0
}
635
636
637
#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\f'))
638
0
#define _TRACEBACK_SOURCE_LINE_INDENT 4
639
640
static inline int
641
0
ignore_source_errors(void) {
642
0
    if (PyErr_Occurred()) {
643
0
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
644
0
            return -1;
645
0
        }
646
0
        PyErr_Clear();
647
0
    }
648
0
    return 0;
649
0
}
650
651
static int
652
tb_displayline(PyTracebackObject* tb, PyObject *f, PyObject *filename, int lineno,
653
               PyFrameObject *frame, PyObject *name)
654
0
{
655
0
    if (filename == NULL || name == NULL) {
656
0
        return -1;
657
0
    }
658
659
0
    PyObject *line = PyUnicode_FromFormat("  File \"%U\", line %d, in %U\n",
660
0
                                          filename, lineno, name);
661
0
    if (line == NULL) {
662
0
        return -1;
663
0
    }
664
665
0
    int res = PyFile_WriteObject(line, f, Py_PRINT_RAW);
666
0
    Py_DECREF(line);
667
0
    if (res < 0) {
668
0
        return -1;
669
0
    }
670
671
0
    int err = 0;
672
673
0
    int truncation = _TRACEBACK_SOURCE_LINE_INDENT;
674
0
    PyObject* source_line = NULL;
675
0
    int rc = display_source_line(
676
0
            f, filename, lineno, _TRACEBACK_SOURCE_LINE_INDENT,
677
0
            &truncation, &source_line);
678
0
    if (rc != 0 || !source_line) {
679
        /* ignore errors since we can't report them, can we? */
680
0
        err = ignore_source_errors();
681
0
    }
682
0
    Py_XDECREF(source_line);
683
0
    return err;
684
0
}
685
686
static const int TB_RECURSIVE_CUTOFF = 3; // Also hardcoded in traceback.py.
687
688
static int
689
tb_print_line_repeated(PyObject *f, long cnt)
690
0
{
691
0
    cnt -= TB_RECURSIVE_CUTOFF;
692
0
    PyObject *line = PyUnicode_FromFormat(
693
0
        (cnt > 1)
694
0
          ? "  [Previous line repeated %ld more times]\n"
695
0
          : "  [Previous line repeated %ld more time]\n",
696
0
        cnt);
697
0
    if (line == NULL) {
698
0
        return -1;
699
0
    }
700
0
    int err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
701
0
    Py_DECREF(line);
702
0
    return err;
703
0
}
704
705
static int
706
tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit)
707
0
{
708
0
    PyCodeObject *code = NULL;
709
0
    Py_ssize_t depth = 0;
710
0
    PyObject *last_file = NULL;
711
0
    int last_line = -1;
712
0
    PyObject *last_name = NULL;
713
0
    long cnt = 0;
714
0
    PyTracebackObject *tb1 = tb;
715
0
    while (tb1 != NULL) {
716
0
        depth++;
717
0
        tb1 = tb1->tb_next;
718
0
    }
719
0
    while (tb != NULL && depth > limit) {
720
0
        depth--;
721
0
        tb = tb->tb_next;
722
0
    }
723
0
    while (tb != NULL) {
724
0
        code = PyFrame_GetCode(tb->tb_frame);
725
0
        int tb_lineno = tb->tb_lineno;
726
0
        if (tb_lineno == -1) {
727
0
            tb_lineno = tb_get_lineno((PyObject *)tb);
728
0
        }
729
0
        if (last_file == NULL ||
730
0
            code->co_filename != last_file ||
731
0
            last_line == -1 || tb_lineno != last_line ||
732
0
            last_name == NULL || code->co_name != last_name) {
733
0
            if (cnt > TB_RECURSIVE_CUTOFF) {
734
0
                if (tb_print_line_repeated(f, cnt) < 0) {
735
0
                    goto error;
736
0
                }
737
0
            }
738
0
            last_file = code->co_filename;
739
0
            last_line = tb_lineno;
740
0
            last_name = code->co_name;
741
0
            cnt = 0;
742
0
        }
743
0
        cnt++;
744
0
        if (cnt <= TB_RECURSIVE_CUTOFF) {
745
0
            if (tb_displayline(tb, f, code->co_filename, tb_lineno,
746
0
                               tb->tb_frame, code->co_name) < 0) {
747
0
                goto error;
748
0
            }
749
750
0
            if (PyErr_CheckSignals() < 0) {
751
0
                goto error;
752
0
            }
753
0
        }
754
0
        Py_CLEAR(code);
755
0
        tb = tb->tb_next;
756
0
    }
757
0
    if (cnt > TB_RECURSIVE_CUTOFF) {
758
0
        if (tb_print_line_repeated(f, cnt) < 0) {
759
0
            goto error;
760
0
        }
761
0
    }
762
0
    return 0;
763
0
error:
764
0
    Py_XDECREF(code);
765
0
    return -1;
766
0
}
767
768
0
#define PyTraceBack_LIMIT 1000
769
770
int
771
_PyTraceBack_Print(PyObject *v, const char *header, PyObject *f)
772
0
{
773
0
    PyObject *limitv;
774
0
    long limit = PyTraceBack_LIMIT;
775
776
0
    if (v == NULL) {
777
0
        return 0;
778
0
    }
779
0
    if (!PyTraceBack_Check(v)) {
780
0
        PyErr_BadInternalCall();
781
0
        return -1;
782
0
    }
783
0
    if (PySys_GetOptionalAttrString("tracebacklimit", &limitv) < 0) {
784
0
        return -1;
785
0
    }
786
0
    else if (limitv != NULL && PyLong_Check(limitv)) {
787
0
        int overflow;
788
0
        limit = PyLong_AsLongAndOverflow(limitv, &overflow);
789
0
        if (overflow > 0) {
790
0
            limit = LONG_MAX;
791
0
        }
792
0
        else if (limit <= 0) {
793
0
            Py_DECREF(limitv);
794
0
            return 0;
795
0
        }
796
0
    }
797
0
    Py_XDECREF(limitv);
798
799
0
    if (PyFile_WriteString(header, f) < 0) {
800
0
        return -1;
801
0
    }
802
803
0
    if (tb_printinternal((PyTracebackObject *)v, f, limit) < 0) {
804
0
        return -1;
805
0
    }
806
807
0
    return 0;
808
0
}
809
810
int
811
PyTraceBack_Print(PyObject *v, PyObject *f)
812
0
{
813
0
    const char *header = EXCEPTION_TB_HEADER;
814
0
    return _PyTraceBack_Print(v, header, f);
815
0
}
816
817
/* Format an integer in range [0; 0xffffffff] to decimal and write it
818
   into the file fd.
819
820
   This function is signal safe. */
821
822
void
823
_Py_DumpDecimal(int fd, size_t value)
824
0
{
825
    /* maximum number of characters required for output of %lld or %p.
826
       We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
827
       plus 1 for the null byte.  53/22 is an upper bound for log10(256). */
828
0
    char buffer[1 + (sizeof(size_t)*53-1) / 22 + 1];
829
0
    char *ptr, *end;
830
831
0
    end = &buffer[Py_ARRAY_LENGTH(buffer) - 1];
832
0
    ptr = end;
833
0
    *ptr = '\0';
834
0
    do {
835
0
        --ptr;
836
0
        assert(ptr >= buffer);
837
0
        *ptr = '0' + (value % 10);
838
0
        value /= 10;
839
0
    } while (value);
840
841
0
    (void)_Py_write_noraise(fd, ptr, end - ptr);
842
0
}
843
844
/* Format an integer as hexadecimal with width digits into fd file descriptor.
845
   The function is signal safe. */
846
static void
847
dump_hexadecimal(int fd, uintptr_t value, Py_ssize_t width, int strip_zeros)
848
0
{
849
0
    char buffer[sizeof(uintptr_t) * 2 + 1], *ptr, *end;
850
0
    Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1;
851
852
0
    if (width > size)
853
0
        width = size;
854
    /* it's ok if width is negative */
855
856
0
    end = &buffer[size];
857
0
    ptr = end;
858
0
    *ptr = '\0';
859
0
    do {
860
0
        --ptr;
861
0
        assert(ptr >= buffer);
862
0
        *ptr = Py_hexdigits[value & 15];
863
0
        value >>= 4;
864
0
    } while ((end - ptr) < width || value);
865
866
0
    size = end - ptr;
867
0
    if (strip_zeros) {
868
0
        while (*ptr == '0' && size >= 2) {
869
0
            ptr++;
870
0
            size--;
871
0
        }
872
0
    }
873
874
0
    (void)_Py_write_noraise(fd, ptr, size);
875
0
}
876
877
void
878
_Py_DumpHexadecimal(int fd, uintptr_t value, Py_ssize_t width)
879
0
{
880
0
    dump_hexadecimal(fd, value, width, 0);
881
0
}
882
883
#ifdef CAN_C_BACKTRACE
884
static void
885
dump_pointer(int fd, void *ptr)
886
0
{
887
0
    PUTS(fd, "0x");
888
0
    dump_hexadecimal(fd, (uintptr_t)ptr, sizeof(void*), 1);
889
0
}
890
#endif
891
892
static void
893
dump_char(int fd, char ch)
894
0
{
895
0
    char buf[1] = {ch};
896
0
    (void)_Py_write_noraise(fd, buf, 1);
897
0
}
898
899
void
900
_Py_DumpASCII(int fd, PyObject *text)
901
0
{
902
0
    PyASCIIObject *ascii = _PyASCIIObject_CAST(text);
903
0
    Py_ssize_t i, size;
904
0
    int truncated;
905
0
    int kind;
906
0
    void *data = NULL;
907
0
    Py_UCS4 ch;
908
909
0
    if (!PyUnicode_Check(text))
910
0
        return;
911
912
0
    size = ascii->length;
913
0
    kind = ascii->state.kind;
914
0
    if (ascii->state.compact) {
915
0
        if (ascii->state.ascii)
916
0
            data = ascii + 1;
917
0
        else
918
0
            data = _PyCompactUnicodeObject_CAST(text) + 1;
919
0
    }
920
0
    else {
921
0
        data = _PyUnicodeObject_CAST(text)->data.any;
922
0
        if (data == NULL)
923
0
            return;
924
0
    }
925
926
0
    if (MAX_STRING_LENGTH < size) {
927
0
        size = MAX_STRING_LENGTH;
928
0
        truncated = 1;
929
0
    }
930
0
    else {
931
0
        truncated = 0;
932
0
    }
933
934
    // Is an ASCII string?
935
0
    if (ascii->state.ascii) {
936
0
        assert(kind == PyUnicode_1BYTE_KIND);
937
0
        char *str = data;
938
939
0
        int need_escape = 0;
940
0
        for (i=0; i < size; i++) {
941
0
            ch = str[i];
942
0
            if (!(' ' <= ch && ch <= 126)) {
943
0
                need_escape = 1;
944
0
                break;
945
0
            }
946
0
        }
947
0
        if (!need_escape) {
948
            // The string can be written with a single write() syscall
949
0
            (void)_Py_write_noraise(fd, str, size);
950
0
            goto done;
951
0
        }
952
0
    }
953
954
0
    for (i=0; i < size; i++) {
955
0
        ch = PyUnicode_READ(kind, data, i);
956
0
        if (' ' <= ch && ch <= 126) {
957
            /* printable ASCII character */
958
0
            dump_char(fd, (char)ch);
959
0
        }
960
0
        else if (ch <= 0xff) {
961
0
            PUTS(fd, "\\x");
962
0
            _Py_DumpHexadecimal(fd, ch, 2);
963
0
        }
964
0
        else if (ch <= 0xffff) {
965
0
            PUTS(fd, "\\u");
966
0
            _Py_DumpHexadecimal(fd, ch, 4);
967
0
        }
968
0
        else {
969
0
            PUTS(fd, "\\U");
970
0
            _Py_DumpHexadecimal(fd, ch, 8);
971
0
        }
972
0
    }
973
974
0
done:
975
0
    if (truncated) {
976
0
        PUTS(fd, "...");
977
0
    }
978
0
}
979
980
981
#ifdef MS_WINDOWS
982
static void
983
_Py_DumpWideString(int fd, wchar_t *str)
984
{
985
    Py_ssize_t size = wcslen(str);
986
    int truncated;
987
    if (MAX_STRING_LENGTH < size) {
988
        size = MAX_STRING_LENGTH;
989
        truncated = 1;
990
    }
991
    else {
992
        truncated = 0;
993
    }
994
995
    for (Py_ssize_t i=0; i < size; i++) {
996
        Py_UCS4 ch = str[i];
997
        if (' ' <= ch && ch <= 126) {
998
            /* printable ASCII character */
999
            dump_char(fd, (char)ch);
1000
        }
1001
        else if (ch <= 0xff) {
1002
            PUTS(fd, "\\x");
1003
            _Py_DumpHexadecimal(fd, ch, 2);
1004
        }
1005
        else if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
1006
                 && Py_UNICODE_IS_LOW_SURROGATE(str[i+1])) {
1007
            ch = Py_UNICODE_JOIN_SURROGATES(ch, str[i+1]);
1008
            i++;  // Skip the low surrogate character
1009
            PUTS(fd, "\\U");
1010
            _Py_DumpHexadecimal(fd, ch, 8);
1011
        }
1012
        else {
1013
            Py_BUILD_ASSERT(sizeof(wchar_t) == 2);
1014
            PUTS(fd, "\\u");
1015
            _Py_DumpHexadecimal(fd, ch, 4);
1016
        }
1017
    }
1018
1019
    if (truncated) {
1020
        PUTS(fd, "...");
1021
    }
1022
}
1023
#endif
1024
1025
1026
/* Write a frame into the file fd: "File "xxx", line xxx in xxx".
1027
1028
   This function is signal safe.
1029
1030
   Return 0 on success. Return -1 if the frame is invalid. */
1031
1032
static int _Py_NO_SANITIZE_THREAD
1033
dump_frame(int fd, _PyInterpreterFrame *frame)
1034
0
{
1035
0
    if (frame->owner == FRAME_OWNED_BY_INTERPRETER) {
1036
        /* Ignore trampoline frames and base frame sentinel */
1037
0
        return 0;
1038
0
    }
1039
1040
0
    PyCodeObject *code = _PyFrame_SafeGetCode(frame);
1041
0
    if (code == NULL) {
1042
0
        return -1;
1043
0
    }
1044
1045
0
    int res = 0;
1046
0
    PUTS(fd, "  File ");
1047
0
    if (code->co_filename != NULL
1048
0
        && PyUnicode_Check(code->co_filename))
1049
0
    {
1050
0
        PUTS(fd, "\"");
1051
0
        _Py_DumpASCII(fd, code->co_filename);
1052
0
        PUTS(fd, "\"");
1053
0
    }
1054
0
    else {
1055
0
        PUTS(fd, "???");
1056
0
        res = -1;
1057
0
    }
1058
1059
0
    PUTS(fd, ", line ");
1060
0
    int lasti = _PyFrame_SafeGetLasti(frame);
1061
0
    int lineno = -1;
1062
0
    if (lasti >= 0) {
1063
0
        lineno = _PyCode_SafeAddr2Line(code, lasti);
1064
0
    }
1065
0
    if (lineno >= 0) {
1066
0
        _Py_DumpDecimal(fd, (size_t)lineno);
1067
0
    }
1068
0
    else {
1069
0
        PUTS(fd, "???");
1070
0
        res = -1;
1071
0
    }
1072
1073
0
    PUTS(fd, " in ");
1074
0
    if (code->co_name != NULL && PyUnicode_Check(code->co_name)) {
1075
0
        _Py_DumpASCII(fd, code->co_name);
1076
0
    }
1077
0
    else {
1078
0
        PUTS(fd, "???");
1079
0
        res = -1;
1080
0
    }
1081
0
    PUTS(fd, "\n");
1082
0
    return res;
1083
0
}
1084
1085
static int _Py_NO_SANITIZE_THREAD
1086
tstate_is_freed(PyThreadState *tstate)
1087
0
{
1088
0
    if (_PyMem_IsPtrFreed(tstate)) {
1089
0
        return 1;
1090
0
    }
1091
0
    if (_PyMem_IsPtrFreed(tstate->interp)) {
1092
0
        return 1;
1093
0
    }
1094
0
    if (_PyMem_IsULongFreed(tstate->thread_id)) {
1095
0
        return 1;
1096
0
    }
1097
0
    return 0;
1098
0
}
1099
1100
1101
static int _Py_NO_SANITIZE_THREAD
1102
interp_is_freed(PyInterpreterState *interp)
1103
0
{
1104
0
    return _PyMem_IsPtrFreed(interp);
1105
0
}
1106
1107
1108
static void _Py_NO_SANITIZE_THREAD
1109
dump_traceback(int fd, PyThreadState *tstate, int write_header)
1110
0
{
1111
0
    if (write_header) {
1112
0
        PUTS(fd, "Stack (most recent call first):\n");
1113
0
    }
1114
1115
0
    if (tstate_is_freed(tstate)) {
1116
0
        PUTS(fd, "  <freed thread state>\n");
1117
0
        return;
1118
0
    }
1119
1120
0
    _PyInterpreterFrame *frame = tstate->current_frame;
1121
0
    if (frame == NULL) {
1122
0
        PUTS(fd, "  <no Python frame>\n");
1123
0
        return;
1124
0
    }
1125
1126
0
    unsigned int depth = 0;
1127
0
    while (1) {
1128
0
        if (MAX_FRAME_DEPTH <= depth) {
1129
0
            if (MAX_FRAME_DEPTH < depth) {
1130
0
                PUTS(fd, "plus ");
1131
0
                _Py_DumpDecimal(fd, depth);
1132
0
                PUTS(fd, " frames\n");
1133
0
            }
1134
0
            break;
1135
0
        }
1136
1137
0
        if (_PyMem_IsPtrFreed(frame)) {
1138
0
            PUTS(fd, "  <freed frame>\n");
1139
0
            break;
1140
0
        }
1141
        // Read frame->previous early since memory can be freed during
1142
        // dump_frame()
1143
0
        _PyInterpreterFrame *previous = frame->previous;
1144
1145
0
        if (dump_frame(fd, frame) < 0) {
1146
0
            PUTS(fd, "  <invalid frame>\n");
1147
0
            break;
1148
0
        }
1149
1150
0
        frame = previous;
1151
0
        if (frame == NULL) {
1152
0
            break;
1153
0
        }
1154
0
        depth++;
1155
0
    }
1156
0
}
1157
1158
/* Dump the traceback of a Python thread into fd. Use write() to write the
1159
   traceback and retry if write() is interrupted by a signal (failed with
1160
   EINTR), but don't call the Python signal handler.
1161
1162
   The caller is responsible to call PyErr_CheckSignals() to call Python signal
1163
   handlers if signals were received. */
1164
const char*
1165
PyUnstable_DumpTraceback(int fd, PyThreadState *tstate)
1166
0
{
1167
0
    dump_traceback(fd, tstate, 1);
1168
0
    return NULL;
1169
0
}
1170
1171
#if defined(HAVE_PTHREAD_GETNAME_NP) || defined(HAVE_PTHREAD_GET_NAME_NP)
1172
# if defined(__OpenBSD__)
1173
    /* pthread_*_np functions, especially pthread_{get,set}_name_np().
1174
       pthread_np.h exists on both OpenBSD and FreeBSD but the latter declares
1175
       pthread_getname_np() and pthread_setname_np() in pthread.h as long as
1176
       __BSD_VISIBLE remains set.
1177
     */
1178
#   include <pthread_np.h>
1179
# endif
1180
#endif
1181
1182
1183
// Write the thread name
1184
static void _Py_NO_SANITIZE_THREAD
1185
write_thread_name(int fd, PyThreadState *tstate)
1186
0
{
1187
0
#ifndef MS_WINDOWS
1188
0
#if defined(HAVE_PTHREAD_GETNAME_NP) || defined(HAVE_PTHREAD_GET_NAME_NP)
1189
0
    char name[100];
1190
0
    pthread_t thread = (pthread_t)tstate->thread_id;
1191
0
#ifdef HAVE_PTHREAD_GETNAME_NP
1192
0
    int rc = pthread_getname_np(thread, name, Py_ARRAY_LENGTH(name));
1193
#else /* defined(HAVE_PTHREAD_GET_NAME_NP) */
1194
    int rc = 0; /* pthread_get_name_np() returns void */
1195
    pthread_get_name_np(thread, name, Py_ARRAY_LENGTH(name));
1196
#endif
1197
0
    if (!rc) {
1198
0
        size_t len = strlen(name);
1199
0
        if (len) {
1200
0
            PUTS(fd, " [");
1201
0
            (void)_Py_write_noraise(fd, name, len);
1202
0
            PUTS(fd, "]");
1203
0
        }
1204
0
    }
1205
0
#endif
1206
#else
1207
    // Windows implementation
1208
    if (pGetThreadDescription == NULL) {
1209
        return;
1210
    }
1211
1212
    HANDLE thread = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, tstate->thread_id);
1213
    if (thread == NULL) {
1214
        return;
1215
    }
1216
1217
    wchar_t *name;
1218
    HRESULT hr = pGetThreadDescription(thread, &name);
1219
    if (!FAILED(hr)) {
1220
        if (name[0] != 0) {
1221
            PUTS(fd, " [");
1222
            _Py_DumpWideString(fd, name);
1223
            PUTS(fd, "]");
1224
        }
1225
        LocalFree(name);
1226
    }
1227
    CloseHandle(thread);
1228
#endif
1229
0
}
1230
1231
1232
/* Write the thread identifier into the file 'fd': "Current thread 0xHHHH:\" if
1233
   is_current is true, "Thread 0xHHHH:\n" otherwise.
1234
1235
   This function is signal safe (except on Windows). */
1236
1237
static void _Py_NO_SANITIZE_THREAD
1238
write_thread_id(int fd, PyThreadState *tstate, int is_current)
1239
0
{
1240
0
    if (is_current)
1241
0
        PUTS(fd, "Current thread 0x");
1242
0
    else
1243
0
        PUTS(fd, "Thread 0x");
1244
0
    _Py_DumpHexadecimal(fd,
1245
0
                        tstate->thread_id,
1246
0
                        sizeof(unsigned long) * 2);
1247
1248
0
    if (!_PyMem_IsULongFreed(tstate->thread_id)) {
1249
0
        write_thread_name(fd, tstate);
1250
0
    }
1251
1252
0
    PUTS(fd, " (most recent call first):\n");
1253
0
}
1254
1255
/* Dump the traceback of all Python threads into fd. Use write() to write the
1256
   traceback and retry if write() is interrupted by a signal (failed with
1257
   EINTR), but don't call the Python signal handler.
1258
1259
   The caller is responsible to call PyErr_CheckSignals() to call Python signal
1260
   handlers if signals were received. */
1261
const char* _Py_NO_SANITIZE_THREAD
1262
PyUnstable_DumpTracebackThreads(int fd, PyInterpreterState *interp,
1263
                                PyThreadState *current_tstate,
1264
                                Py_ssize_t max_threads)
1265
0
{
1266
0
    if (max_threads == 0) {
1267
0
        max_threads = DEFAULT_MAX_NTHREADS;
1268
0
    }
1269
1270
0
    if (current_tstate == NULL) {
1271
        /* PyUnstable_DumpTracebackThreads() is called from signal handlers by
1272
           faulthandler.
1273
1274
           SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals
1275
           and are thus delivered to the thread that caused the fault. Get the
1276
           Python thread state of the current thread.
1277
1278
           PyThreadState_Get() doesn't give the state of the thread that caused
1279
           the fault if the thread released the GIL, and so
1280
           _PyThreadState_GET() cannot be used. Read the thread specific
1281
           storage (TSS) instead: call PyGILState_GetThisThreadState(). */
1282
0
        current_tstate = PyGILState_GetThisThreadState();
1283
0
    }
1284
1285
0
    if (current_tstate != NULL && tstate_is_freed(current_tstate)) {
1286
0
        return "tstate is freed";
1287
0
    }
1288
1289
0
    if (interp == NULL) {
1290
0
        if (current_tstate == NULL) {
1291
0
            interp = _PyGILState_GetInterpreterStateUnsafe();
1292
0
            if (interp == NULL) {
1293
                /* We need the interpreter state to get Python threads */
1294
0
                return "unable to get the interpreter state";
1295
0
            }
1296
0
        }
1297
0
        else {
1298
0
            interp = current_tstate->interp;
1299
0
        }
1300
0
    }
1301
0
    assert(interp != NULL);
1302
1303
0
    if (interp_is_freed(interp)) {
1304
0
        return "interp is freed";
1305
0
    }
1306
1307
    /* Get the current interpreter from the current thread */
1308
0
    PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1309
0
    if (tstate == NULL)
1310
0
        return "unable to get the thread head state";
1311
1312
    /* Dump the traceback of each thread */
1313
0
    Py_ssize_t nthreads = 0;
1314
0
    _Py_BEGIN_SUPPRESS_IPH
1315
0
    do
1316
0
    {
1317
0
        if (nthreads != 0)
1318
0
            PUTS(fd, "\n");
1319
0
        if (nthreads >= max_threads) {
1320
0
            PUTS(fd, "...\n");
1321
0
            break;
1322
0
        }
1323
1324
0
        if (tstate_is_freed(tstate)) {
1325
0
            PUTS(fd, "<freed thread state>\n");
1326
0
            break;
1327
0
        }
1328
1329
0
        write_thread_id(fd, tstate, tstate == current_tstate);
1330
0
        if (tstate == current_tstate && tstate->interp->gc.collecting) {
1331
0
            PUTS(fd, "  Garbage-collecting\n");
1332
0
        }
1333
0
        dump_traceback(fd, tstate, 0);
1334
1335
0
        tstate = tstate->next;
1336
0
        nthreads++;
1337
0
    } while (tstate != NULL);
1338
0
    _Py_END_SUPPRESS_IPH
1339
1340
0
    return NULL;
1341
0
}
1342
1343
#ifdef CAN_C_BACKTRACE
1344
/* Based on glibc's implementation of backtrace_symbols(), but only uses stack memory. */
1345
void
1346
_Py_backtrace_symbols_fd(int fd, void *const *array, Py_ssize_t size)
1347
0
{
1348
0
    VLA(Dl_info, info, size);
1349
0
    VLA(int, status, size);
1350
    /* Fill in the information we can get from dladdr() */
1351
0
    for (Py_ssize_t i = 0; i < size; ++i) {
1352
#ifdef __APPLE__
1353
        status[i] = dladdr(array[i], &info[i]);
1354
#else
1355
0
        struct link_map *map;
1356
0
        status[i] = dladdr1(array[i], &info[i], (void **)&map, RTLD_DL_LINKMAP);
1357
0
        if (status[i] != 0
1358
0
            && info[i].dli_fname != NULL
1359
0
            && info[i].dli_fname[0] != '\0') {
1360
            /* The load bias is more useful to the user than the load
1361
               address. The use of these addresses is to calculate an
1362
               address in the ELF file, so its prelinked bias is not
1363
               something we want to subtract out */
1364
0
            info[i].dli_fbase = (void *) map->l_addr;
1365
0
        }
1366
0
#endif
1367
0
    }
1368
0
    for (Py_ssize_t i = 0; i < size; ++i) {
1369
0
        if (status[i] == 0
1370
0
            || info[i].dli_fname == NULL
1371
0
            || info[i].dli_fname[0] == '\0'
1372
0
        ) {
1373
0
            PUTS(fd, "  Binary file '<unknown>' [");
1374
0
            dump_pointer(fd, array[i]);
1375
0
            PUTS(fd, "]\n");
1376
0
            continue;
1377
0
        }
1378
1379
0
        if (info[i].dli_sname == NULL) {
1380
            /* We found no symbol name to use, so describe it as
1381
               relative to the file. */
1382
0
            info[i].dli_saddr = info[i].dli_fbase;
1383
0
        }
1384
1385
0
        if (info[i].dli_sname == NULL && info[i].dli_saddr == 0) {
1386
0
            PUTS(fd, "  Binary file \"");
1387
0
            PUTS(fd, info[i].dli_fname);
1388
0
            PUTS(fd, "\" [");
1389
0
            dump_pointer(fd, array[i]);
1390
0
            PUTS(fd, "]\n");
1391
0
        }
1392
0
        else {
1393
0
            char sign;
1394
0
            ptrdiff_t offset;
1395
0
            if (array[i] >= (void *) info[i].dli_saddr) {
1396
0
                sign = '+';
1397
0
                offset = array[i] - info[i].dli_saddr;
1398
0
            }
1399
0
            else {
1400
0
                sign = '-';
1401
0
                offset = info[i].dli_saddr - array[i];
1402
0
            }
1403
0
            const char *symbol_name = info[i].dli_sname != NULL ? info[i].dli_sname : "";
1404
0
            PUTS(fd, "  Binary file \"");
1405
0
            PUTS(fd, info[i].dli_fname);
1406
0
            PUTS(fd, "\", at ");
1407
0
            PUTS(fd, symbol_name);
1408
0
            dump_char(fd, sign);
1409
0
            PUTS(fd, "0x");
1410
0
            dump_hexadecimal(fd, offset, sizeof(offset), 1);
1411
0
            PUTS(fd, " [");
1412
0
            dump_pointer(fd, array[i]);
1413
0
            PUTS(fd, "]\n");
1414
0
        }
1415
0
    }
1416
0
}
1417
1418
void
1419
_Py_DumpStack(int fd)
1420
0
{
1421
0
#define BACKTRACE_SIZE 32
1422
0
    PUTS(fd, "Current thread's C stack trace (most recent call first):\n");
1423
0
    VLA(void *, callstack, BACKTRACE_SIZE);
1424
0
    int frames = backtrace(callstack, BACKTRACE_SIZE);
1425
0
    if (frames == 0) {
1426
        // Some systems won't return anything for the stack trace
1427
0
        PUTS(fd, "  <system returned no stack trace>\n");
1428
0
        return;
1429
0
    }
1430
1431
0
    _Py_backtrace_symbols_fd(fd, callstack, frames);
1432
0
    if (frames == BACKTRACE_SIZE) {
1433
0
        PUTS(fd, "  <truncated rest of calls>\n");
1434
0
    }
1435
1436
0
#undef BACKTRACE_SIZE
1437
0
}
1438
#else
1439
void
1440
_Py_DumpStack(int fd)
1441
{
1442
    PUTS(fd, "Current thread's C stack trace (most recent call first):\n");
1443
    PUTS(fd, "  <cannot get C stack on this system>\n");
1444
}
1445
#endif
1446
1447
void
1448
_Py_InitDumpStack(void)
1449
0
{
1450
0
#ifdef CAN_C_BACKTRACE
1451
    // gh-137185: Call backtrace() once to force libgcc to be loaded early.
1452
0
    void *callstack[1];
1453
0
    (void)backtrace(callstack, 1);
1454
0
#endif
1455
0
}
1456
1457
1458
void
1459
_Py_DumpTraceback_Init(void)
1460
37
{
1461
#ifdef MS_WINDOWS
1462
    if (pGetThreadDescription != NULL) {
1463
        return;
1464
    }
1465
1466
    HMODULE kernelbase = GetModuleHandleW(L"kernelbase.dll");
1467
    if (kernelbase != NULL) {
1468
        pGetThreadDescription = (PF_GET_THREAD_DESCRIPTION)GetProcAddress(
1469
                                    kernelbase, "GetThreadDescription");
1470
    }
1471
#endif
1472
37
}