Coverage Report

Created: 2026-04-20 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/errors.c
Line
Count
Source
1
2
/* Error handling */
3
4
#include "Python.h"
5
#include "pycore_audit.h"         // _PySys_Audit()
6
#include "pycore_call.h"          // _PyObject_CallNoArgs()
7
#include "pycore_fileutils.h"     // _PyFile_Flush
8
#include "pycore_initconfig.h"    // _PyStatus_ERR()
9
#include "pycore_pyerrors.h"      // _PyErr_Format()
10
#include "pycore_pystate.h"       // _PyThreadState_GET()
11
#include "pycore_runtime.h"       // _Py_ID()
12
#include "pycore_structseq.h"     // _PyStructSequence_FiniBuiltin()
13
#include "pycore_traceback.h"     // _PyTraceBack_FromFrame()
14
#include "pycore_unicodeobject.h" // _PyUnicode_Equal()
15
16
#ifdef MS_WINDOWS
17
#  include <windows.h>
18
#  include <winbase.h>
19
#  include <stdlib.h>             // _sys_nerr
20
#endif
21
22
23
void
24
_PyErr_SetRaisedException(PyThreadState *tstate, PyObject *exc)
25
270M
{
26
270M
    PyObject *old_exc = tstate->current_exception;
27
270M
    tstate->current_exception = exc;
28
270M
    Py_XDECREF(old_exc);
29
270M
}
30
31
static PyObject*
32
_PyErr_CreateException(PyObject *exception_type, PyObject *value)
33
14.1M
{
34
14.1M
    PyObject *exc;
35
36
14.1M
    if (value == NULL || value == Py_None) {
37
109k
        exc = _PyObject_CallNoArgs(exception_type);
38
109k
    }
39
14.0M
    else if (PyTuple_Check(value)) {
40
92.8k
        exc = PyObject_Call(exception_type, value, NULL);
41
92.8k
    }
42
13.9M
    else {
43
13.9M
        exc = PyObject_CallOneArg(exception_type, value);
44
13.9M
    }
45
46
14.1M
    if (exc != NULL && !PyExceptionInstance_Check(exc)) {
47
0
        PyErr_Format(PyExc_TypeError,
48
0
                     "calling %R should have returned an instance of "
49
0
                     "BaseException, not %s",
50
0
                     exception_type, Py_TYPE(exc)->tp_name);
51
0
        Py_CLEAR(exc);
52
0
    }
53
54
14.1M
    return exc;
55
14.1M
}
56
57
void
58
_PyErr_Restore(PyThreadState *tstate, PyObject *type, PyObject *value,
59
               PyObject *traceback)
60
88.1M
{
61
88.1M
    if (type == NULL) {
62
46.1M
        assert(value == NULL);
63
46.1M
        assert(traceback == NULL);
64
46.1M
        _PyErr_SetRaisedException(tstate, NULL);
65
46.1M
        return;
66
46.1M
    }
67
88.1M
    assert(PyExceptionClass_Check(type));
68
41.9M
    if (value != NULL && type == (PyObject *)Py_TYPE(value)) {
69
        /* Already normalized */
70
#ifdef Py_DEBUG
71
        PyObject *tb = PyException_GetTraceback(value);
72
        assert(tb != Py_None);
73
        Py_XDECREF(tb);
74
#endif
75
41.9M
    }
76
0
    else {
77
0
        PyObject *exc = _PyErr_CreateException(type, value);
78
0
        Py_XDECREF(value);
79
0
        if (exc == NULL) {
80
0
            Py_DECREF(type);
81
0
            Py_XDECREF(traceback);
82
0
            return;
83
0
        }
84
0
        value = exc;
85
0
    }
86
41.9M
    assert(PyExceptionInstance_Check(value));
87
41.9M
    if (traceback != NULL) {
88
48.5k
        if (PyException_SetTraceback(value, traceback) < 0) {
89
0
            Py_DECREF(traceback);
90
0
            Py_DECREF(value);
91
0
            Py_DECREF(type);
92
0
            return;
93
0
        }
94
48.5k
        Py_DECREF(traceback);
95
48.5k
    }
96
41.9M
    _PyErr_SetRaisedException(tstate, value);
97
41.9M
    Py_DECREF(type);
98
41.9M
}
99
100
void
101
PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
102
130k
{
103
130k
    PyThreadState *tstate = _PyThreadState_GET();
104
130k
    _PyErr_Restore(tstate, type, value, traceback);
105
130k
}
106
107
void
108
PyErr_SetRaisedException(PyObject *exc)
109
176M
{
110
176M
    PyThreadState *tstate = _PyThreadState_GET();
111
176M
    _PyErr_SetRaisedException(tstate, exc);
112
176M
}
113
114
_PyErr_StackItem *
115
_PyErr_GetTopmostException(PyThreadState *tstate)
116
41.8M
{
117
41.8M
    _PyErr_StackItem *exc_info = tstate->exc_info;
118
41.8M
    assert(exc_info);
119
120
89.5M
    while (exc_info->exc_value == NULL && exc_info->previous_item != NULL)
121
47.7M
    {
122
47.7M
        exc_info = exc_info->previous_item;
123
47.7M
    }
124
41.8M
    assert(!Py_IsNone(exc_info->exc_value));
125
41.8M
    return exc_info;
126
41.8M
}
127
128
static PyObject *
129
get_normalization_failure_note(PyThreadState *tstate, PyObject *exception, PyObject *value)
130
0
{
131
0
    PyObject *args = PyObject_Repr(value);
132
0
    if (args == NULL) {
133
0
        _PyErr_Clear(tstate);
134
0
        args = PyUnicode_FromFormat("<unknown>");
135
0
    }
136
0
    PyObject *note;
137
0
    const char *tpname = ((PyTypeObject*)exception)->tp_name;
138
0
    if (args == NULL) {
139
0
        _PyErr_Clear(tstate);
140
0
        note = PyUnicode_FromFormat("Normalization failed: type=%s", tpname);
141
0
    }
142
0
    else {
143
0
        note = PyUnicode_FromFormat("Normalization failed: type=%s args=%S",
144
0
                                    tpname, args);
145
0
        Py_DECREF(args);
146
0
    }
147
0
    return note;
148
0
}
149
150
void
151
_PyErr_SetObject(PyThreadState *tstate, PyObject *exception, PyObject *value)
152
41.7M
{
153
41.7M
    PyObject *exc_value;
154
41.7M
    PyObject *tb = NULL;
155
156
41.7M
    if (exception != NULL &&
157
41.7M
        !PyExceptionClass_Check(exception)) {
158
0
        _PyErr_Format(tstate, PyExc_SystemError,
159
0
                      "_PyErr_SetObject: "
160
0
                      "exception %R is not a BaseException subclass",
161
0
                      exception);
162
0
        return;
163
0
    }
164
    /* Normalize the exception */
165
41.7M
    int is_subclass = 0;
166
41.7M
    if (value != NULL && PyExceptionInstance_Check(value)) {
167
27.6M
        is_subclass = PyObject_IsSubclass((PyObject *)Py_TYPE(value), exception);
168
27.6M
        if (is_subclass < 0) {
169
0
            return;
170
0
        }
171
27.6M
    }
172
41.7M
    Py_XINCREF(value);
173
41.7M
    if (!is_subclass) {
174
        /* We must normalize the value right now */
175
176
        /* Issue #23571: functions must not be called with an
177
            exception set */
178
14.1M
        _PyErr_Clear(tstate);
179
180
14.1M
        PyObject *fixed_value = _PyErr_CreateException(exception, value);
181
14.1M
        if (fixed_value == NULL) {
182
0
            PyObject *exc = _PyErr_GetRaisedException(tstate);
183
0
            assert(PyExceptionInstance_Check(exc));
184
185
0
            PyObject *note = get_normalization_failure_note(tstate, exception, value);
186
0
            Py_XDECREF(value);
187
0
            if (note != NULL) {
188
                /* ignore errors in _PyException_AddNote - they will be overwritten below */
189
0
                _PyException_AddNote(exc, note);
190
0
                Py_DECREF(note);
191
0
            }
192
0
            _PyErr_SetRaisedException(tstate, exc);
193
0
            return;
194
0
        }
195
14.1M
        Py_XSETREF(value, fixed_value);
196
14.1M
    }
197
198
41.7M
    exc_value = _PyErr_GetTopmostException(tstate)->exc_value;
199
41.7M
    if (exc_value != NULL && exc_value != Py_None) {
200
        /* Implicit exception chaining */
201
5.50M
        Py_INCREF(exc_value);
202
        /* Avoid creating new reference cycles through the
203
           context chain, while taking care not to hang on
204
           pre-existing ones.
205
           This is O(chain length) but context chains are
206
           usually very short. Sensitive readers may try
207
           to inline the call to PyException_GetContext. */
208
5.50M
        if (exc_value != value) {
209
5.50M
            PyObject *o = exc_value, *context;
210
5.50M
            PyObject *slow_o = o;  /* Floyd's cycle detection algo */
211
5.50M
            int slow_update_toggle = 0;
212
6.28M
            while ((context = PyException_GetContext(o))) {
213
779k
                Py_DECREF(context);
214
779k
                if (context == value) {
215
0
                    PyException_SetContext(o, NULL);
216
0
                    break;
217
0
                }
218
779k
                o = context;
219
779k
                if (o == slow_o) {
220
                    /* pre-existing cycle - all exceptions on the
221
                       path were visited and checked.  */
222
0
                    break;
223
0
                }
224
779k
                if (slow_update_toggle) {
225
242k
                    slow_o = PyException_GetContext(slow_o);
226
242k
                    Py_DECREF(slow_o);
227
242k
                }
228
779k
                slow_update_toggle = !slow_update_toggle;
229
779k
            }
230
5.50M
            PyException_SetContext(value, exc_value);
231
5.50M
        }
232
4.50k
        else {
233
4.50k
            Py_DECREF(exc_value);
234
4.50k
        }
235
5.50M
    }
236
41.7M
    assert(value != NULL);
237
41.7M
    if (PyExceptionInstance_Check(value))
238
41.7M
        tb = PyException_GetTraceback(value);
239
41.7M
    _PyErr_Restore(tstate, Py_NewRef(Py_TYPE(value)), value, tb);
240
41.7M
}
241
242
void
243
PyErr_SetObject(PyObject *exception, PyObject *value)
244
5.32M
{
245
5.32M
    PyThreadState *tstate = _PyThreadState_GET();
246
5.32M
    _PyErr_SetObject(tstate, exception, value);
247
5.32M
}
248
249
/* Set a key error with the specified argument. This function should be used to
250
 * raise a KeyError with an argument instead of PyErr_SetObject(PyExc_KeyError,
251
 * arg) which has a special behavior. PyErr_SetObject() unpacks arg if it's a
252
 * tuple, and it uses arg instead of creating a new exception if arg is an
253
 * exception.
254
 *
255
 * If an exception is already set, override the exception. */
256
void
257
_PyErr_SetKeyError(PyObject *arg)
258
3.50M
{
259
3.50M
    PyThreadState *tstate = _PyThreadState_GET();
260
261
    // PyObject_CallOneArg() must not be called with an exception set,
262
    // otherwise _Py_CheckFunctionResult() can fail if the function returned
263
    // a result with an excception set.
264
3.50M
    _PyErr_Clear(tstate);
265
266
3.50M
    PyObject *exc = PyObject_CallOneArg(PyExc_KeyError, arg);
267
3.50M
    if (!exc) {
268
        /* caller will expect error to be set anyway */
269
0
        return;
270
0
    }
271
272
3.50M
    _PyErr_SetObject(tstate, (PyObject*)Py_TYPE(exc), exc);
273
3.50M
    Py_DECREF(exc);
274
3.50M
}
275
276
void
277
_PyErr_SetNone(PyThreadState *tstate, PyObject *exception)
278
109k
{
279
109k
    _PyErr_SetObject(tstate, exception, (PyObject *)NULL);
280
109k
}
281
282
283
void
284
PyErr_SetNone(PyObject *exception)
285
109k
{
286
109k
    PyThreadState *tstate = _PyThreadState_GET();
287
109k
    _PyErr_SetNone(tstate, exception);
288
109k
}
289
290
291
void
292
_PyErr_SetString(PyThreadState *tstate, PyObject *exception,
293
                 const char *string)
294
454k
{
295
454k
    PyObject *value = PyUnicode_FromString(string);
296
454k
    if (value != NULL) {
297
454k
        _PyErr_SetObject(tstate, exception, value);
298
454k
        Py_DECREF(value);
299
454k
    }
300
454k
}
301
302
void
303
PyErr_SetString(PyObject *exception, const char *string)
304
454k
{
305
454k
    PyThreadState *tstate = _PyThreadState_GET();
306
454k
    _PyErr_SetString(tstate, exception, string);
307
454k
}
308
309
void
310
_PyErr_SetLocaleString(PyObject *exception, const char *string)
311
0
{
312
0
    PyObject *value = PyUnicode_DecodeLocale(string, "surrogateescape");
313
0
    if (value != NULL) {
314
0
        PyErr_SetObject(exception, value);
315
0
        Py_DECREF(value);
316
0
    }
317
0
}
318
319
PyObject* _Py_HOT_FUNCTION
320
PyErr_Occurred(void)
321
390M
{
322
    /* The caller must hold a thread state. */
323
390M
    _Py_AssertHoldsTstate();
324
325
390M
    PyThreadState *tstate = _PyThreadState_GET();
326
390M
    return _PyErr_Occurred(tstate);
327
390M
}
328
329
330
int
331
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
332
56.8M
{
333
56.8M
    if (err == NULL || exc == NULL) {
334
        /* maybe caused by "import exceptions" that failed early on */
335
12
        return 0;
336
12
    }
337
56.8M
    if (PyTuple_Check(exc)) {
338
444k
        Py_ssize_t i, n;
339
444k
        n = PyTuple_Size(exc);
340
483k
        for (i = 0; i < n; i++) {
341
            /* Test recursively */
342
479k
             if (PyErr_GivenExceptionMatches(
343
479k
                 err, PyTuple_GET_ITEM(exc, i)))
344
441k
             {
345
441k
                 return 1;
346
441k
             }
347
479k
        }
348
3.13k
        return 0;
349
444k
    }
350
    /* err might be an instance, so check its class. */
351
56.3M
    if (PyExceptionInstance_Check(err))
352
33.8M
        err = PyExceptionInstance_Class(err);
353
354
56.3M
    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
355
56.3M
        return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
356
56.3M
    }
357
358
0
    return err == exc;
359
56.3M
}
360
361
362
int
363
_PyErr_ExceptionMatches(PyThreadState *tstate, PyObject *exc)
364
22.5M
{
365
22.5M
    return PyErr_GivenExceptionMatches(_PyErr_Occurred(tstate), exc);
366
22.5M
}
367
368
369
int
370
PyErr_ExceptionMatches(PyObject *exc)
371
7.75M
{
372
7.75M
    PyThreadState *tstate = _PyThreadState_GET();
373
7.75M
    return _PyErr_ExceptionMatches(tstate, exc);
374
7.75M
}
375
376
377
#ifndef Py_NORMALIZE_RECURSION_LIMIT
378
0
#define Py_NORMALIZE_RECURSION_LIMIT 32
379
#endif
380
381
/* Used in many places to normalize a raised exception, including in
382
   eval_code2(), do_raise(), and PyErr_Print()
383
384
   XXX: should PyErr_NormalizeException() also call
385
            PyException_SetTraceback() with the resulting value and tb?
386
*/
387
void
388
_PyErr_NormalizeException(PyThreadState *tstate, PyObject **exc,
389
                          PyObject **val, PyObject **tb)
390
0
{
391
0
    int recursion_depth = 0;
392
0
    tstate->recursion_headroom++;
393
0
    PyObject *type, *value, *initial_tb;
394
395
0
  restart:
396
0
    type = *exc;
397
0
    if (type == NULL) {
398
        /* There was no exception, so nothing to do. */
399
0
        tstate->recursion_headroom--;
400
0
        return;
401
0
    }
402
403
0
    value = *val;
404
    /* If PyErr_SetNone() was used, the value will have been actually
405
       set to NULL.
406
    */
407
0
    if (!value) {
408
0
        value = Py_NewRef(Py_None);
409
0
    }
410
411
    /* Normalize the exception so that if the type is a class, the
412
       value will be an instance.
413
    */
414
0
    if (PyExceptionClass_Check(type)) {
415
0
        PyObject *inclass = NULL;
416
0
        int is_subclass = 0;
417
418
0
        if (PyExceptionInstance_Check(value)) {
419
0
            inclass = PyExceptionInstance_Class(value);
420
0
            is_subclass = PyObject_IsSubclass(inclass, type);
421
0
            if (is_subclass < 0) {
422
0
                goto error;
423
0
            }
424
0
        }
425
426
        /* If the value was not an instance, or is not an instance
427
           whose class is (or is derived from) type, then use the
428
           value as an argument to instantiation of the type
429
           class.
430
        */
431
0
        if (!is_subclass) {
432
0
            PyObject *fixed_value = _PyErr_CreateException(type, value);
433
0
            if (fixed_value == NULL) {
434
0
                goto error;
435
0
            }
436
0
            Py_SETREF(value, fixed_value);
437
0
        }
438
        /* If the class of the instance doesn't exactly match the
439
           class of the type, believe the instance.
440
        */
441
0
        else if (inclass != type) {
442
0
            Py_SETREF(type, Py_NewRef(inclass));
443
0
        }
444
0
    }
445
0
    *exc = type;
446
0
    *val = value;
447
0
    tstate->recursion_headroom--;
448
0
    return;
449
450
0
  error:
451
0
    Py_DECREF(type);
452
0
    Py_DECREF(value);
453
0
    recursion_depth++;
454
0
    if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
455
0
        _PyErr_SetString(tstate, PyExc_RecursionError,
456
0
                         "maximum recursion depth exceeded "
457
0
                         "while normalizing an exception");
458
0
    }
459
    /* If the new exception doesn't set a traceback and the old
460
       exception had a traceback, use the old traceback for the
461
       new exception.  It's better than nothing.
462
    */
463
0
    initial_tb = *tb;
464
0
    _PyErr_Fetch(tstate, exc, val, tb);
465
0
    assert(*exc != NULL);
466
0
    if (initial_tb != NULL) {
467
0
        if (*tb == NULL)
468
0
            *tb = initial_tb;
469
0
        else
470
0
            Py_DECREF(initial_tb);
471
0
    }
472
    /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
473
       corresponding RecursionError could not be normalized, and the
474
       MemoryError raised when normalize this RecursionError could not be
475
       normalized. */
476
0
    if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
477
0
        if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
478
0
            Py_FatalError("Cannot recover from MemoryErrors "
479
0
                          "while normalizing exceptions.");
480
0
        }
481
0
        else {
482
0
            Py_FatalError("Cannot recover from the recursive normalization "
483
0
                          "of an exception.");
484
0
        }
485
0
    }
486
0
    goto restart;
487
0
}
488
489
490
void
491
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
492
0
{
493
0
    PyThreadState *tstate = _PyThreadState_GET();
494
0
    _PyErr_NormalizeException(tstate, exc, val, tb);
495
0
}
496
497
498
PyObject *
499
206M
_PyErr_GetRaisedException(PyThreadState *tstate) {
500
206M
    PyObject *exc = tstate->current_exception;
501
206M
    tstate->current_exception = NULL;
502
206M
    return exc;
503
206M
}
504
505
PyObject *
506
PyErr_GetRaisedException(void)
507
176M
{
508
176M
    PyThreadState *tstate = _PyThreadState_GET();
509
176M
    return _PyErr_GetRaisedException(tstate);
510
176M
}
511
512
void
513
_PyErr_Fetch(PyThreadState *tstate, PyObject **p_type, PyObject **p_value,
514
             PyObject **p_traceback)
515
88.4k
{
516
88.4k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
517
88.4k
    *p_value = exc;
518
88.4k
    if (exc == NULL) {
519
0
        *p_type = NULL;
520
0
        *p_traceback = NULL;
521
0
    }
522
88.4k
    else {
523
88.4k
        *p_type = Py_NewRef(Py_TYPE(exc));
524
88.4k
        *p_traceback = PyException_GetTraceback(exc);
525
88.4k
    }
526
88.4k
}
527
528
529
void
530
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
531
88.4k
{
532
88.4k
    PyThreadState *tstate = _PyThreadState_GET();
533
88.4k
    _PyErr_Fetch(tstate, p_type, p_value, p_traceback);
534
88.4k
}
535
536
537
void
538
_PyErr_Clear(PyThreadState *tstate)
539
46.1M
{
540
46.1M
    _PyErr_Restore(tstate, NULL, NULL, NULL);
541
46.1M
}
542
543
544
void
545
PyErr_Clear(void)
546
2.32M
{
547
2.32M
    PyThreadState *tstate = _PyThreadState_GET();
548
2.32M
    _PyErr_Clear(tstate);
549
2.32M
}
550
551
static PyObject*
552
get_exc_type(PyObject *exc_value)  /* returns a strong ref */
553
0
{
554
0
    if (exc_value == NULL || exc_value == Py_None) {
555
0
        return Py_None;
556
0
    }
557
0
    else {
558
0
        assert(PyExceptionInstance_Check(exc_value));
559
0
        PyObject *type = PyExceptionInstance_Class(exc_value);
560
0
        assert(type != NULL);
561
0
        return Py_NewRef(type);
562
0
    }
563
0
}
564
565
static PyObject*
566
get_exc_traceback(PyObject *exc_value)  /* returns a strong ref */
567
0
{
568
0
    if (exc_value == NULL || exc_value == Py_None) {
569
0
        return Py_None;
570
0
    }
571
0
    else {
572
0
        assert(PyExceptionInstance_Check(exc_value));
573
0
        PyObject *tb = PyException_GetTraceback(exc_value);
574
0
        return tb ? tb : Py_None;
575
0
    }
576
0
}
577
578
void
579
_PyErr_GetExcInfo(PyThreadState *tstate,
580
                  PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
581
0
{
582
0
    _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
583
584
0
    *p_type = get_exc_type(exc_info->exc_value);
585
0
    *p_value = Py_XNewRef(exc_info->exc_value);
586
0
    *p_traceback = get_exc_traceback(exc_info->exc_value);
587
0
}
588
589
PyObject*
590
_PyErr_GetHandledException(PyThreadState *tstate)
591
0
{
592
0
    _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
593
0
    PyObject *exc = exc_info->exc_value;
594
0
    if (exc == NULL || exc == Py_None) {
595
0
        return NULL;
596
0
    }
597
0
    return Py_NewRef(exc);
598
0
}
599
600
PyObject*
601
PyErr_GetHandledException(void)
602
0
{
603
0
    PyThreadState *tstate = _PyThreadState_GET();
604
0
    return _PyErr_GetHandledException(tstate);
605
0
}
606
607
void
608
_PyErr_SetHandledException(PyThreadState *tstate, PyObject *exc)
609
0
{
610
0
    Py_XSETREF(tstate->exc_info->exc_value, Py_XNewRef(exc == Py_None ? NULL : exc));
611
0
}
612
613
void
614
PyErr_SetHandledException(PyObject *exc)
615
0
{
616
0
    PyThreadState *tstate = _PyThreadState_GET();
617
0
    _PyErr_SetHandledException(tstate, exc);
618
0
}
619
620
void
621
PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
622
0
{
623
0
    PyThreadState *tstate = _PyThreadState_GET();
624
0
    _PyErr_GetExcInfo(tstate, p_type, p_value, p_traceback);
625
0
}
626
627
void
628
PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
629
0
{
630
0
    PyErr_SetHandledException(value);
631
0
    Py_XDECREF(value);
632
    /* These args are no longer used, but we still need to steal a ref */
633
0
    Py_XDECREF(type);
634
0
    Py_XDECREF(traceback);
635
0
}
636
637
638
PyObject*
639
_PyErr_StackItemToExcInfoTuple(_PyErr_StackItem *err_info)
640
0
{
641
0
    PyObject *exc_value = err_info->exc_value;
642
643
0
    assert(exc_value == NULL ||
644
0
           exc_value == Py_None ||
645
0
           PyExceptionInstance_Check(exc_value));
646
647
0
    PyObject *ret = PyTuple_New(3);
648
0
    if (ret == NULL) {
649
0
        return NULL;
650
0
    }
651
652
0
    PyObject *exc_type = get_exc_type(exc_value);
653
0
    PyObject *exc_traceback = get_exc_traceback(exc_value);
654
655
0
    PyTuple_SET_ITEM(ret, 0, exc_type ? exc_type : Py_None);
656
0
    PyTuple_SET_ITEM(ret, 1, exc_value ? Py_NewRef(exc_value) : Py_None);
657
0
    PyTuple_SET_ITEM(ret, 2, exc_traceback ? exc_traceback : Py_None);
658
659
0
    return ret;
660
0
}
661
662
663
/* Like PyErr_Restore(), but if an exception is already set,
664
   set the context associated with it.
665
666
   The caller is responsible for ensuring that this call won't create
667
   any cycles in the exception context chain. */
668
void
669
_PyErr_ChainExceptions(PyObject *typ, PyObject *val, PyObject *tb)
670
0
{
671
0
    if (typ == NULL)
672
0
        return;
673
674
0
    PyThreadState *tstate = _PyThreadState_GET();
675
676
0
    if (!PyExceptionClass_Check(typ)) {
677
0
        _PyErr_Format(tstate, PyExc_SystemError,
678
0
                      "_PyErr_ChainExceptions: "
679
0
                      "exception %R is not a BaseException subclass",
680
0
                      typ);
681
0
        return;
682
0
    }
683
684
0
    if (_PyErr_Occurred(tstate)) {
685
0
        _PyErr_NormalizeException(tstate, &typ, &val, &tb);
686
0
        if (tb != NULL) {
687
0
            PyException_SetTraceback(val, tb);
688
0
            Py_DECREF(tb);
689
0
        }
690
0
        Py_DECREF(typ);
691
0
        PyObject *exc2 = _PyErr_GetRaisedException(tstate);
692
0
        PyException_SetContext(exc2, val);
693
0
        _PyErr_SetRaisedException(tstate, exc2);
694
0
    }
695
0
    else {
696
0
        _PyErr_Restore(tstate, typ, val, tb);
697
0
    }
698
0
}
699
700
/* Like PyErr_SetRaisedException(), but if an exception is already set,
701
   set the context associated with it.
702
703
   The caller is responsible for ensuring that this call won't create
704
   any cycles in the exception context chain. */
705
void
706
_PyErr_ChainExceptions1Tstate(PyThreadState *tstate, PyObject *exc)
707
78.8k
{
708
78.8k
    if (exc == NULL) {
709
78.8k
        return;
710
78.8k
    }
711
0
    if (_PyErr_Occurred(tstate)) {
712
0
        PyObject *exc2 = _PyErr_GetRaisedException(tstate);
713
0
        PyException_SetContext(exc2, exc);
714
0
        _PyErr_SetRaisedException(tstate, exc2);
715
0
    }
716
0
    else {
717
0
        _PyErr_SetRaisedException(tstate, exc);
718
0
    }
719
0
}
720
721
void
722
_PyErr_ChainExceptions1(PyObject *exc)
723
78.8k
{
724
78.8k
    PyThreadState *tstate = _PyThreadState_GET();
725
78.8k
    _PyErr_ChainExceptions1Tstate(tstate, exc);
726
78.8k
}
727
728
/* If the current thread is handling an exception (exc_info is ), set this
729
   exception as the context of the current raised exception.
730
731
   This function can only be called when _PyErr_Occurred() is true.
732
   Also, this function won't create any cycles in the exception context
733
   chain to the extent that _PyErr_SetObject ensures this. */
734
void
735
_PyErr_ChainStackItem(void)
736
44.4k
{
737
44.4k
    PyThreadState *tstate = _PyThreadState_GET();
738
44.4k
    assert(_PyErr_Occurred(tstate));
739
740
44.4k
    _PyErr_StackItem *exc_info = tstate->exc_info;
741
44.4k
    if (exc_info->exc_value == NULL || exc_info->exc_value == Py_None) {
742
44.4k
        return;
743
44.4k
    }
744
745
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
746
747
    /* _PyErr_SetObject sets the context from PyThreadState. */
748
0
    _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(exc), exc);
749
0
    Py_DECREF(exc);  // since _PyErr_Occurred was true
750
0
}
751
752
static PyObject *
753
_PyErr_FormatVFromCause(PyThreadState *tstate, PyObject *exception,
754
                        const char *format, va_list vargs)
755
0
{
756
0
    assert(_PyErr_Occurred(tstate));
757
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
758
0
    assert(!_PyErr_Occurred(tstate));
759
0
    _PyErr_FormatV(tstate, exception, format, vargs);
760
0
    PyObject *exc2 = _PyErr_GetRaisedException(tstate);
761
0
    PyException_SetCause(exc2, Py_NewRef(exc));
762
0
    PyException_SetContext(exc2, Py_NewRef(exc));
763
0
    Py_DECREF(exc);
764
0
    _PyErr_SetRaisedException(tstate, exc2);
765
0
    return NULL;
766
0
}
767
768
PyObject *
769
_PyErr_FormatFromCauseTstate(PyThreadState *tstate, PyObject *exception,
770
                             const char *format, ...)
771
0
{
772
0
    va_list vargs;
773
0
    va_start(vargs, format);
774
0
    _PyErr_FormatVFromCause(tstate, exception, format, vargs);
775
0
    va_end(vargs);
776
0
    return NULL;
777
0
}
778
779
PyObject *
780
_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
781
0
{
782
0
    PyThreadState *tstate = _PyThreadState_GET();
783
0
    va_list vargs;
784
0
    va_start(vargs, format);
785
0
    _PyErr_FormatVFromCause(tstate, exception, format, vargs);
786
0
    va_end(vargs);
787
0
    return NULL;
788
0
}
789
790
/* Convenience functions to set a type error exception and return 0 */
791
792
int
793
PyErr_BadArgument(void)
794
0
{
795
0
    PyThreadState *tstate = _PyThreadState_GET();
796
0
    _PyErr_SetString(tstate, PyExc_TypeError,
797
0
                     "bad argument type for built-in operation");
798
0
    return 0;
799
0
}
800
801
PyObject *
802
PyErr_NoMemory(void)
803
0
{
804
0
    PyThreadState *tstate = _PyThreadState_GET();
805
0
    return _PyErr_NoMemory(tstate);
806
0
}
807
808
PyObject *
809
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
810
389k
{
811
389k
    return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
812
389k
}
813
814
PyObject *
815
PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
816
389k
{
817
389k
    PyThreadState *tstate = _PyThreadState_GET();
818
389k
    PyObject *message;
819
389k
    PyObject *v, *args;
820
389k
    int i = errno;
821
#ifdef MS_WINDOWS
822
    WCHAR *s_buf = NULL;
823
#endif /* Unix/Windows */
824
825
389k
#ifdef EINTR
826
389k
    if (i == EINTR && PyErr_CheckSignals())
827
0
        return NULL;
828
389k
#endif
829
830
389k
#ifndef MS_WINDOWS
831
389k
    if (i != 0) {
832
389k
        const char *s = strerror(i);
833
389k
        message = PyUnicode_DecodeLocale(s, "surrogateescape");
834
389k
    }
835
0
    else {
836
        /* Sometimes errno didn't get set */
837
0
        message = PyUnicode_FromString("Error");
838
0
    }
839
#else
840
    if (i == 0)
841
        message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
842
    else
843
    {
844
        /* Note that the Win32 errors do not lineup with the
845
           errno error.  So if the error is in the MSVC error
846
           table, we use it, otherwise we assume it really _is_
847
           a Win32 error code
848
        */
849
        if (i > 0 && i < _sys_nerr) {
850
            message = PyUnicode_FromString(_sys_errlist[i]);
851
        }
852
        else {
853
            int len = FormatMessageW(
854
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
855
                FORMAT_MESSAGE_FROM_SYSTEM |
856
                FORMAT_MESSAGE_IGNORE_INSERTS,
857
                NULL,                   /* no message source */
858
                i,
859
                MAKELANGID(LANG_NEUTRAL,
860
                           SUBLANG_DEFAULT),
861
                           /* Default language */
862
                (LPWSTR) &s_buf,
863
                0,                      /* size not used */
864
                NULL);                  /* no args */
865
            if (len==0) {
866
                /* Only ever seen this in out-of-mem
867
                   situations */
868
                s_buf = NULL;
869
                message = PyUnicode_FromFormat("Windows Error 0x%x", i);
870
            } else {
871
                /* remove trailing cr/lf and dots */
872
                while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
873
                    s_buf[--len] = L'\0';
874
                message = PyUnicode_FromWideChar(s_buf, len);
875
            }
876
        }
877
    }
878
#endif /* Unix/Windows */
879
880
389k
    if (message == NULL)
881
0
    {
882
#ifdef MS_WINDOWS
883
        LocalFree(s_buf);
884
#endif
885
0
        return NULL;
886
0
    }
887
888
389k
    if (filenameObject != NULL) {
889
389k
        if (filenameObject2 != NULL)
890
0
            args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
891
389k
        else
892
389k
            args = Py_BuildValue("(iOO)", i, message, filenameObject);
893
389k
    } else {
894
180
        assert(filenameObject2 == NULL);
895
180
        args = Py_BuildValue("(iO)", i, message);
896
180
    }
897
389k
    Py_DECREF(message);
898
899
389k
    if (args != NULL) {
900
389k
        v = PyObject_Call(exc, args, NULL);
901
389k
        Py_DECREF(args);
902
389k
        if (v != NULL) {
903
389k
            _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
904
389k
            Py_DECREF(v);
905
389k
        }
906
389k
    }
907
#ifdef MS_WINDOWS
908
    LocalFree(s_buf);
909
#endif
910
389k
    return NULL;
911
389k
}
912
913
PyObject *
914
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
915
0
{
916
0
    PyObject *name = NULL;
917
0
    if (filename) {
918
0
        int i = errno;
919
0
        name = PyUnicode_DecodeFSDefault(filename);
920
0
        if (name == NULL) {
921
0
            return NULL;
922
0
        }
923
0
        errno = i;
924
0
    }
925
0
    PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
926
0
    Py_XDECREF(name);
927
0
    return result;
928
0
}
929
930
PyObject *
931
PyErr_SetFromErrno(PyObject *exc)
932
180
{
933
180
    return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
934
180
}
935
936
#ifdef MS_WINDOWS
937
/* Windows specific error code handling */
938
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
939
    PyObject *exc,
940
    int ierr,
941
    PyObject *filenameObject)
942
{
943
    return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
944
        filenameObject, NULL);
945
}
946
947
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
948
    PyObject *exc,
949
    int ierr,
950
    PyObject *filenameObject,
951
    PyObject *filenameObject2)
952
{
953
    PyThreadState *tstate = _PyThreadState_GET();
954
    int len;
955
    WCHAR *s_buf = NULL; /* Free via LocalFree */
956
    PyObject *message;
957
    PyObject *args, *v;
958
959
    DWORD err = (DWORD)ierr;
960
    if (err==0) {
961
        err = GetLastError();
962
    }
963
964
    len = FormatMessageW(
965
        /* Error API error */
966
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
967
        FORMAT_MESSAGE_FROM_SYSTEM |
968
        FORMAT_MESSAGE_IGNORE_INSERTS,
969
        NULL,           /* no message source */
970
        err,
971
        MAKELANGID(LANG_NEUTRAL,
972
        SUBLANG_DEFAULT), /* Default language */
973
        (LPWSTR) &s_buf,
974
        0,              /* size not used */
975
        NULL);          /* no args */
976
    if (len==0) {
977
        /* Only seen this in out of mem situations */
978
        message = PyUnicode_FromFormat("Windows Error 0x%x", err);
979
        s_buf = NULL;
980
    } else {
981
        /* remove trailing cr/lf and dots */
982
        while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
983
            s_buf[--len] = L'\0';
984
        message = PyUnicode_FromWideChar(s_buf, len);
985
    }
986
987
    if (message == NULL)
988
    {
989
        LocalFree(s_buf);
990
        return NULL;
991
    }
992
993
    if (filenameObject == NULL) {
994
        assert(filenameObject2 == NULL);
995
        filenameObject = filenameObject2 = Py_None;
996
    }
997
    else if (filenameObject2 == NULL)
998
        filenameObject2 = Py_None;
999
    /* This is the constructor signature for OSError.
1000
       The POSIX translation will be figured out by the constructor. */
1001
    args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
1002
    Py_DECREF(message);
1003
1004
    if (args != NULL) {
1005
        v = PyObject_Call(exc, args, NULL);
1006
        Py_DECREF(args);
1007
        if (v != NULL) {
1008
            _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
1009
            Py_DECREF(v);
1010
        }
1011
    }
1012
    LocalFree(s_buf);
1013
    return NULL;
1014
}
1015
1016
PyObject *PyErr_SetExcFromWindowsErrWithFilename(
1017
    PyObject *exc,
1018
    int ierr,
1019
    const char *filename)
1020
{
1021
    PyObject *name = NULL;
1022
    if (filename) {
1023
        if ((DWORD)ierr == 0) {
1024
            ierr = (int)GetLastError();
1025
        }
1026
        name = PyUnicode_DecodeFSDefault(filename);
1027
        if (name == NULL) {
1028
            return NULL;
1029
        }
1030
    }
1031
    PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
1032
                                                                 ierr,
1033
                                                                 name,
1034
                                                                 NULL);
1035
    Py_XDECREF(name);
1036
    return ret;
1037
}
1038
1039
PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
1040
{
1041
    return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
1042
}
1043
1044
PyObject *PyErr_SetFromWindowsErr(int ierr)
1045
{
1046
    return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
1047
                                                  ierr, NULL);
1048
}
1049
1050
PyObject *PyErr_SetFromWindowsErrWithFilename(
1051
    int ierr,
1052
    const char *filename)
1053
{
1054
    PyObject *name = NULL;
1055
    if (filename) {
1056
        if ((DWORD)ierr == 0) {
1057
            ierr = (int)GetLastError();
1058
        }
1059
        name = PyUnicode_DecodeFSDefault(filename);
1060
        if (name == NULL) {
1061
            return NULL;
1062
        }
1063
    }
1064
    PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
1065
                                                  PyExc_OSError,
1066
                                                  ierr, name, NULL);
1067
    Py_XDECREF(name);
1068
    return result;
1069
}
1070
1071
#endif /* MS_WINDOWS */
1072
1073
static PyObject *
1074
new_importerror(
1075
    PyThreadState *tstate, PyObject *exctype, PyObject *msg,
1076
    PyObject *name, PyObject *path, PyObject* from_name)
1077
34
{
1078
34
    PyObject *exc = NULL;
1079
34
    PyObject *kwargs = NULL;
1080
1081
34
    int issubclass = PyObject_IsSubclass(exctype, PyExc_ImportError);
1082
34
    if (issubclass < 0) {
1083
0
        return NULL;
1084
0
    }
1085
34
    else if (!issubclass) {
1086
0
        _PyErr_SetString(tstate, PyExc_TypeError,
1087
0
                         "expected a subclass of ImportError");
1088
0
        return NULL;
1089
0
    }
1090
1091
34
    if (msg == NULL) {
1092
0
        _PyErr_SetString(tstate, PyExc_TypeError,
1093
0
                         "expected a message argument");
1094
0
        return NULL;
1095
0
    }
1096
1097
34
    if (name == NULL) {
1098
0
        name = Py_None;
1099
0
    }
1100
34
    if (path == NULL) {
1101
28
        path = Py_None;
1102
28
    }
1103
34
    if (from_name == NULL) {
1104
4
        from_name = Py_None;
1105
4
    }
1106
1107
34
    kwargs = PyDict_New();
1108
34
    if (kwargs == NULL) {
1109
0
        return NULL;
1110
0
    }
1111
34
    if (PyDict_SetItemString(kwargs, "name", name) < 0) {
1112
0
        goto finally;
1113
0
    }
1114
34
    if (PyDict_SetItemString(kwargs, "path", path) < 0) {
1115
0
        goto finally;
1116
0
    }
1117
34
    if (PyDict_SetItemString(kwargs, "name_from", from_name) < 0) {
1118
0
        goto finally;
1119
0
    }
1120
34
    exc = PyObject_VectorcallDict(exctype, &msg, 1, kwargs);
1121
1122
34
finally:
1123
34
    Py_DECREF(kwargs);
1124
34
    return exc;
1125
34
}
1126
1127
static PyObject *
1128
_PyErr_SetImportErrorSubclassWithNameFrom(
1129
    PyObject *exception, PyObject *msg,
1130
    PyObject *name, PyObject *path, PyObject* from_name)
1131
34
{
1132
34
    PyThreadState *tstate = _PyThreadState_GET();
1133
34
    PyObject *error = new_importerror(
1134
34
                        tstate, exception, msg, name, path, from_name);
1135
34
    if (error != NULL) {
1136
34
        _PyErr_SetObject(tstate, (PyObject *)Py_TYPE(error), error);
1137
34
        Py_DECREF(error);
1138
34
    }
1139
34
    return NULL;
1140
34
}
1141
1142
1143
PyObject *
1144
PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
1145
    PyObject *name, PyObject *path)
1146
4
{
1147
4
    return _PyErr_SetImportErrorSubclassWithNameFrom(exception, msg, name, path, NULL);
1148
4
}
1149
1150
PyObject *
1151
_PyErr_SetImportErrorWithNameFrom(PyObject *msg, PyObject *name, PyObject *path, PyObject* from_name)
1152
30
{
1153
30
    return _PyErr_SetImportErrorSubclassWithNameFrom(PyExc_ImportError, msg, name, path, from_name);
1154
30
}
1155
1156
PyObject *
1157
PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
1158
4
{
1159
4
    return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
1160
4
}
1161
1162
int
1163
_PyErr_SetModuleNotFoundError(PyObject *name)
1164
0
{
1165
0
    PyThreadState *tstate = _PyThreadState_GET();
1166
0
    if (name == NULL) {
1167
0
        _PyErr_SetString(tstate, PyExc_TypeError, "expected a name argument");
1168
0
        return -1;
1169
0
    }
1170
0
    PyObject *msg = PyUnicode_FromFormat("%S module not found", name);
1171
0
    if (msg == NULL) {
1172
0
        return -1;
1173
0
    }
1174
0
    PyObject *exctype = PyExc_ModuleNotFoundError;
1175
0
    PyObject *exc = new_importerror(tstate, exctype, msg, name, NULL, NULL);
1176
0
    Py_DECREF(msg);
1177
0
    if (exc == NULL) {
1178
0
        return -1;
1179
0
    }
1180
0
    _PyErr_SetObject(tstate, exctype, exc);
1181
0
    Py_DECREF(exc);
1182
0
    return 0;
1183
0
}
1184
1185
void
1186
_PyErr_BadInternalCall(const char *filename, int lineno)
1187
0
{
1188
0
    PyThreadState *tstate = _PyThreadState_GET();
1189
0
    _PyErr_Format(tstate, PyExc_SystemError,
1190
0
                  "%s:%d: bad argument to internal function",
1191
0
                  filename, lineno);
1192
0
}
1193
1194
/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
1195
   export the entry point for existing object code: */
1196
#undef PyErr_BadInternalCall
1197
void
1198
PyErr_BadInternalCall(void)
1199
0
{
1200
0
    assert(0 && "bad argument to internal function");
1201
0
    PyThreadState *tstate = _PyThreadState_GET();
1202
0
    _PyErr_SetString(tstate, PyExc_SystemError,
1203
0
                     "bad argument to internal function");
1204
0
}
1205
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
1206
1207
1208
PyObject *
1209
_PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
1210
               const char *format, va_list vargs)
1211
11.4M
{
1212
11.4M
    PyObject* string;
1213
1214
    /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
1215
       exception set, it calls arbitrary Python code like PyObject_Repr() */
1216
11.4M
    _PyErr_Clear(tstate);
1217
1218
11.4M
    string = PyUnicode_FromFormatV(format, vargs);
1219
11.4M
    if (string != NULL) {
1220
11.4M
        _PyErr_SetObject(tstate, exception, string);
1221
11.4M
        Py_DECREF(string);
1222
11.4M
    }
1223
11.4M
    return NULL;
1224
11.4M
}
1225
1226
1227
PyObject *
1228
PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
1229
0
{
1230
0
    PyThreadState *tstate = _PyThreadState_GET();
1231
0
    return _PyErr_FormatV(tstate, exception, format, vargs);
1232
0
}
1233
1234
1235
PyObject *
1236
_PyErr_Format(PyThreadState *tstate, PyObject *exception,
1237
              const char *format, ...)
1238
4.22M
{
1239
4.22M
    va_list vargs;
1240
4.22M
    va_start(vargs, format);
1241
4.22M
    _PyErr_FormatV(tstate, exception, format, vargs);
1242
4.22M
    va_end(vargs);
1243
4.22M
    return NULL;
1244
4.22M
}
1245
1246
1247
PyObject *
1248
PyErr_Format(PyObject *exception, const char *format, ...)
1249
7.18M
{
1250
7.18M
    PyThreadState *tstate = _PyThreadState_GET();
1251
7.18M
    va_list vargs;
1252
7.18M
    va_start(vargs, format);
1253
7.18M
    _PyErr_FormatV(tstate, exception, format, vargs);
1254
7.18M
    va_end(vargs);
1255
7.18M
    return NULL;
1256
7.18M
}
1257
1258
1259
/* Adds a note to the current exception (if any) */
1260
void
1261
_PyErr_FormatNote(const char *format, ...)
1262
55.0k
{
1263
55.0k
    PyObject *exc = PyErr_GetRaisedException();
1264
55.0k
    if (exc == NULL) {
1265
0
        return;
1266
0
    }
1267
55.0k
    va_list vargs;
1268
55.0k
    va_start(vargs, format);
1269
55.0k
    PyObject *note = PyUnicode_FromFormatV(format, vargs);
1270
55.0k
    va_end(vargs);
1271
55.0k
    if (note == NULL) {
1272
0
        goto error;
1273
0
    }
1274
55.0k
    int res = _PyException_AddNote(exc, note);
1275
55.0k
    Py_DECREF(note);
1276
55.0k
    if (res < 0) {
1277
0
        goto error;
1278
0
    }
1279
55.0k
    PyErr_SetRaisedException(exc);
1280
55.0k
    return;
1281
0
error:
1282
0
    _PyErr_ChainExceptions1(exc);
1283
0
}
1284
1285
1286
PyObject *
1287
PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
1288
234
{
1289
234
    PyThreadState *tstate = _PyThreadState_GET();
1290
234
    PyObject *modulename = NULL;
1291
234
    PyObject *mydict = NULL;
1292
234
    PyObject *bases = NULL;
1293
234
    PyObject *result = NULL;
1294
1295
234
    const char *dot = strrchr(name, '.');
1296
234
    if (dot == NULL) {
1297
0
        _PyErr_SetString(tstate, PyExc_SystemError,
1298
0
                         "PyErr_NewException: name must be module.class");
1299
0
        return NULL;
1300
0
    }
1301
234
    if (base == NULL) {
1302
58
        base = PyExc_Exception;
1303
58
    }
1304
234
    if (dict == NULL) {
1305
186
        dict = mydict = PyDict_New();
1306
186
        if (dict == NULL)
1307
0
            goto failure;
1308
186
    }
1309
1310
234
    int r = PyDict_Contains(dict, &_Py_ID(__module__));
1311
234
    if (r < 0) {
1312
0
        goto failure;
1313
0
    }
1314
234
    if (r == 0) {
1315
234
        modulename = PyUnicode_FromStringAndSize(name,
1316
234
                                             (Py_ssize_t)(dot-name));
1317
234
        if (modulename == NULL)
1318
0
            goto failure;
1319
234
        if (PyDict_SetItem(dict, &_Py_ID(__module__), modulename) != 0)
1320
0
            goto failure;
1321
234
    }
1322
234
    if (PyTuple_Check(base)) {
1323
42
        bases = Py_NewRef(base);
1324
192
    } else {
1325
192
        bases = PyTuple_Pack(1, base);
1326
192
        if (bases == NULL)
1327
0
            goto failure;
1328
192
    }
1329
    /* Create a real class. */
1330
234
    result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
1331
234
                                   dot+1, bases, dict);
1332
234
  failure:
1333
234
    Py_XDECREF(bases);
1334
234
    Py_XDECREF(mydict);
1335
234
    Py_XDECREF(modulename);
1336
234
    return result;
1337
234
}
1338
1339
1340
/* Create an exception with docstring */
1341
PyObject *
1342
PyErr_NewExceptionWithDoc(const char *name, const char *doc,
1343
                          PyObject *base, PyObject *dict)
1344
48
{
1345
48
    int result;
1346
48
    PyObject *ret = NULL;
1347
48
    PyObject *mydict = NULL; /* points to the dict only if we create it */
1348
48
    PyObject *docobj;
1349
1350
48
    if (dict == NULL) {
1351
48
        dict = mydict = PyDict_New();
1352
48
        if (dict == NULL) {
1353
0
            return NULL;
1354
0
        }
1355
48
    }
1356
1357
48
    if (doc != NULL) {
1358
48
        docobj = PyUnicode_FromString(doc);
1359
48
        if (docobj == NULL)
1360
0
            goto failure;
1361
48
        result = PyDict_SetItemString(dict, "__doc__", docobj);
1362
48
        Py_DECREF(docobj);
1363
48
        if (result < 0)
1364
0
            goto failure;
1365
48
    }
1366
1367
48
    ret = PyErr_NewException(name, base, dict);
1368
48
  failure:
1369
48
    Py_XDECREF(mydict);
1370
48
    return ret;
1371
48
}
1372
1373
1374
PyDoc_STRVAR(UnraisableHookArgs__doc__,
1375
"UnraisableHookArgs\n\
1376
\n\
1377
Type used to pass arguments to sys.unraisablehook.");
1378
1379
static PyTypeObject UnraisableHookArgsType;
1380
1381
static PyStructSequence_Field UnraisableHookArgs_fields[] = {
1382
    {"exc_type", "Exception type"},
1383
    {"exc_value", "Exception value"},
1384
    {"exc_traceback", "Exception traceback"},
1385
    {"err_msg", "Error message"},
1386
    {"object", "Object causing the exception"},
1387
    {0}
1388
};
1389
1390
static PyStructSequence_Desc UnraisableHookArgs_desc = {
1391
    .name = "UnraisableHookArgs",
1392
    .doc = UnraisableHookArgs__doc__,
1393
    .fields = UnraisableHookArgs_fields,
1394
    .n_in_sequence = 5
1395
};
1396
1397
1398
PyStatus
1399
_PyErr_InitTypes(PyInterpreterState *interp)
1400
36
{
1401
36
    if (_PyStructSequence_InitBuiltin(interp, &UnraisableHookArgsType,
1402
36
                                      &UnraisableHookArgs_desc) < 0)
1403
0
    {
1404
0
        return _PyStatus_ERR("failed to initialize UnraisableHookArgs type");
1405
0
    }
1406
36
    return _PyStatus_OK();
1407
36
}
1408
1409
1410
void
1411
_PyErr_FiniTypes(PyInterpreterState *interp)
1412
0
{
1413
0
    _PyStructSequence_FiniBuiltin(interp, &UnraisableHookArgsType);
1414
0
}
1415
1416
1417
static PyObject *
1418
make_unraisable_hook_args(PyThreadState *tstate, PyObject *exc_type,
1419
                          PyObject *exc_value, PyObject *exc_tb,
1420
                          PyObject *err_msg, PyObject *obj)
1421
0
{
1422
0
    PyObject *args = PyStructSequence_New(&UnraisableHookArgsType);
1423
0
    if (args == NULL) {
1424
0
        return NULL;
1425
0
    }
1426
1427
0
    Py_ssize_t pos = 0;
1428
0
#define ADD_ITEM(exc_type) \
1429
0
        do { \
1430
0
            if (exc_type == NULL) { \
1431
0
                exc_type = Py_None; \
1432
0
            } \
1433
0
            PyStructSequence_SET_ITEM(args, pos++, Py_NewRef(exc_type)); \
1434
0
        } while (0)
1435
1436
1437
0
    ADD_ITEM(exc_type);
1438
0
    ADD_ITEM(exc_value);
1439
0
    ADD_ITEM(exc_tb);
1440
0
    ADD_ITEM(err_msg);
1441
0
    ADD_ITEM(obj);
1442
0
#undef ADD_ITEM
1443
1444
0
    if (_PyErr_Occurred(tstate)) {
1445
0
        Py_DECREF(args);
1446
0
        return NULL;
1447
0
    }
1448
0
    return args;
1449
0
}
1450
1451
1452
1453
/* Default implementation of sys.unraisablehook.
1454
1455
   It can be called to log the exception of a custom sys.unraisablehook.
1456
1457
   This assumes 'file' is neither NULL nor None.
1458
 */
1459
static int
1460
write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type,
1461
                          PyObject *exc_value, PyObject *exc_tb,
1462
                          PyObject *err_msg, PyObject *obj, PyObject *file)
1463
0
{
1464
0
    assert(file != NULL);
1465
0
    assert(!Py_IsNone(file));
1466
1467
0
    if (obj != NULL && obj != Py_None) {
1468
0
        if (err_msg != NULL && err_msg != Py_None) {
1469
0
            if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
1470
0
                return -1;
1471
0
            }
1472
0
            if (PyFile_WriteString(": ", file) < 0) {
1473
0
                return -1;
1474
0
            }
1475
0
        }
1476
0
        else {
1477
0
            if (PyFile_WriteString("Exception ignored in: ", file) < 0) {
1478
0
                return -1;
1479
0
            }
1480
0
        }
1481
1482
0
        if (PyFile_WriteObject(obj, file, 0) < 0) {
1483
0
            _PyErr_Clear(tstate);
1484
0
            if (PyFile_WriteString("<object repr() failed>", file) < 0) {
1485
0
                return -1;
1486
0
            }
1487
0
        }
1488
0
        if (PyFile_WriteString("\n", file) < 0) {
1489
0
            return -1;
1490
0
        }
1491
0
    }
1492
0
    else if (err_msg != NULL && err_msg != Py_None) {
1493
0
        if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
1494
0
            return -1;
1495
0
        }
1496
0
        if (PyFile_WriteString(":\n", file) < 0) {
1497
0
            return -1;
1498
0
        }
1499
0
    }
1500
1501
    // Try printing the exception using the stdlib module.
1502
    // If this fails, then we have to use the C implementation.
1503
0
    PyObject *print_exception_fn = PyImport_ImportModuleAttrString("traceback",
1504
0
                                                                   "_print_exception_bltin");
1505
0
    if (print_exception_fn != NULL && PyCallable_Check(print_exception_fn)) {
1506
0
        PyObject *args[2] = {exc_value, file};
1507
0
        PyObject *result = PyObject_Vectorcall(print_exception_fn, args, 2, NULL);
1508
0
        int ok = (result != NULL);
1509
0
        Py_DECREF(print_exception_fn);
1510
0
        Py_XDECREF(result);
1511
0
        if (ok) {
1512
            // Nothing else to do
1513
0
            return 0;
1514
0
        }
1515
0
    }
1516
0
    else {
1517
0
        Py_XDECREF(print_exception_fn);
1518
0
    }
1519
    // traceback module failed, fall back to pure C
1520
0
    _PyErr_Clear(tstate);
1521
1522
0
    if (exc_tb != NULL && exc_tb != Py_None) {
1523
0
        if (PyTraceBack_Print(exc_tb, file) < 0) {
1524
            /* continue even if writing the traceback failed */
1525
0
            _PyErr_Clear(tstate);
1526
0
        }
1527
0
    }
1528
1529
0
    if (exc_type == NULL || exc_type == Py_None) {
1530
0
        return -1;
1531
0
    }
1532
1533
0
    assert(PyExceptionClass_Check(exc_type));
1534
1535
0
    PyObject *modulename = PyObject_GetAttr(exc_type, &_Py_ID(__module__));
1536
0
    if (modulename == NULL || !PyUnicode_Check(modulename)) {
1537
0
        Py_XDECREF(modulename);
1538
0
        _PyErr_Clear(tstate);
1539
0
        if (PyFile_WriteString("<unknown>", file) < 0) {
1540
0
            return -1;
1541
0
        }
1542
0
    }
1543
0
    else {
1544
0
        if (!_PyUnicode_Equal(modulename, &_Py_ID(builtins)) &&
1545
0
            !_PyUnicode_Equal(modulename, &_Py_ID(__main__))) {
1546
0
            if (PyFile_WriteObject(modulename, file, Py_PRINT_RAW) < 0) {
1547
0
                Py_DECREF(modulename);
1548
0
                return -1;
1549
0
            }
1550
0
            Py_DECREF(modulename);
1551
0
            if (PyFile_WriteString(".", file) < 0) {
1552
0
                return -1;
1553
0
            }
1554
0
        }
1555
0
        else {
1556
0
            Py_DECREF(modulename);
1557
0
        }
1558
0
    }
1559
1560
0
    PyObject *qualname = PyType_GetQualName((PyTypeObject *)exc_type);
1561
0
    if (qualname == NULL || !PyUnicode_Check(qualname)) {
1562
0
        Py_XDECREF(qualname);
1563
0
        _PyErr_Clear(tstate);
1564
0
        if (PyFile_WriteString("<unknown>", file) < 0) {
1565
0
            return -1;
1566
0
        }
1567
0
    }
1568
0
    else {
1569
0
        if (PyFile_WriteObject(qualname, file, Py_PRINT_RAW) < 0) {
1570
0
            Py_DECREF(qualname);
1571
0
            return -1;
1572
0
        }
1573
0
        Py_DECREF(qualname);
1574
0
    }
1575
1576
0
    if (exc_value && exc_value != Py_None) {
1577
0
        if (PyFile_WriteString(": ", file) < 0) {
1578
0
            return -1;
1579
0
        }
1580
0
        if (PyFile_WriteObject(exc_value, file, Py_PRINT_RAW) < 0) {
1581
0
            _PyErr_Clear(tstate);
1582
0
            if (PyFile_WriteString("<exception str() failed>", file) < 0) {
1583
0
                return -1;
1584
0
            }
1585
0
        }
1586
0
    }
1587
1588
0
    if (PyFile_WriteString("\n", file) < 0) {
1589
0
        return -1;
1590
0
    }
1591
1592
    /* Explicitly call file.flush() */
1593
0
    if (_PyFile_Flush(file) < 0) {
1594
0
        return -1;
1595
0
    }
1596
1597
0
    return 0;
1598
0
}
1599
1600
1601
static int
1602
write_unraisable_exc(PyThreadState *tstate, PyObject *exc_type,
1603
                     PyObject *exc_value, PyObject *exc_tb, PyObject *err_msg,
1604
                     PyObject *obj)
1605
0
{
1606
0
    PyObject *file;
1607
0
    if (PySys_GetOptionalAttr(&_Py_ID(stderr), &file) < 0) {
1608
0
        return -1;
1609
0
    }
1610
0
    if (file == NULL || file == Py_None) {
1611
0
        Py_XDECREF(file);
1612
0
        return 0;
1613
0
    }
1614
1615
0
    int res = write_unraisable_exc_file(tstate, exc_type, exc_value, exc_tb,
1616
0
                                        err_msg, obj, file);
1617
0
    Py_DECREF(file);
1618
1619
0
    return res;
1620
0
}
1621
1622
1623
PyObject*
1624
_PyErr_WriteUnraisableDefaultHook(PyObject *args)
1625
0
{
1626
0
    PyThreadState *tstate = _PyThreadState_GET();
1627
1628
0
    if (!Py_IS_TYPE(args, &UnraisableHookArgsType)) {
1629
0
        _PyErr_SetString(tstate, PyExc_TypeError,
1630
0
                         "sys.unraisablehook argument type "
1631
0
                         "must be UnraisableHookArgs");
1632
0
        return NULL;
1633
0
    }
1634
1635
    /* Borrowed references */
1636
0
    PyObject *exc_type = PyStructSequence_GET_ITEM(args, 0);
1637
0
    PyObject *exc_value = PyStructSequence_GET_ITEM(args, 1);
1638
0
    PyObject *exc_tb = PyStructSequence_GET_ITEM(args, 2);
1639
0
    PyObject *err_msg = PyStructSequence_GET_ITEM(args, 3);
1640
0
    PyObject *obj = PyStructSequence_GET_ITEM(args, 4);
1641
1642
0
    if (write_unraisable_exc(tstate, exc_type, exc_value, exc_tb, err_msg, obj) < 0) {
1643
0
        return NULL;
1644
0
    }
1645
0
    Py_RETURN_NONE;
1646
0
}
1647
1648
1649
/* Call sys.unraisablehook().
1650
1651
   This function can be used when an exception has occurred but there is no way
1652
   for Python to handle it. For example, when a destructor raises an exception
1653
   or during garbage collection (gc.collect()).
1654
1655
   If format is non-NULL, the error message is formatted using format and
1656
   variable arguments as in PyUnicode_FromFormat().
1657
   Otherwise, use "Exception ignored in" error message.
1658
1659
   An exception must be set when calling this function. */
1660
1661
static void
1662
format_unraisable_v(const char *format, va_list va, PyObject *obj)
1663
0
{
1664
0
    const char *err_msg_str;
1665
0
    PyThreadState *tstate = _PyThreadState_GET();
1666
0
    _Py_EnsureTstateNotNULL(tstate);
1667
1668
0
    PyObject *err_msg = NULL;
1669
0
    PyObject *hook = NULL;
1670
0
    PyObject *exc_type, *exc_value, *exc_tb;
1671
0
    _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
1672
1673
0
    assert(exc_type != NULL);
1674
1675
0
    if (exc_type == NULL) {
1676
        /* sys.unraisablehook requires that at least exc_type is set */
1677
0
        goto default_hook;
1678
0
    }
1679
1680
0
    if (exc_tb == NULL) {
1681
0
        PyFrameObject *frame = PyThreadState_GetFrame(tstate);
1682
0
        if (frame != NULL) {
1683
0
            exc_tb = _PyTraceBack_FromFrame(NULL, frame);
1684
0
            if (exc_tb == NULL) {
1685
0
                _PyErr_Clear(tstate);
1686
0
            }
1687
0
            Py_DECREF(frame);
1688
0
        }
1689
0
    }
1690
1691
0
    _PyErr_NormalizeException(tstate, &exc_type, &exc_value, &exc_tb);
1692
1693
0
    if (exc_tb != NULL && exc_tb != Py_None && PyTraceBack_Check(exc_tb)) {
1694
0
        if (PyException_SetTraceback(exc_value, exc_tb) < 0) {
1695
0
            _PyErr_Clear(tstate);
1696
0
        }
1697
0
    }
1698
1699
0
    if (format != NULL) {
1700
0
        err_msg = PyUnicode_FromFormatV(format, va);
1701
0
        if (err_msg == NULL) {
1702
0
            PyErr_Clear();
1703
0
        }
1704
0
    }
1705
1706
0
    PyObject *hook_args = make_unraisable_hook_args(
1707
0
        tstate, exc_type, exc_value, exc_tb, err_msg, obj);
1708
0
    if (hook_args == NULL) {
1709
0
        err_msg_str = ("Exception ignored while building "
1710
0
                       "sys.unraisablehook arguments");
1711
0
        goto error;
1712
0
    }
1713
1714
0
    if (PySys_GetOptionalAttr(&_Py_ID(unraisablehook), &hook) < 0) {
1715
0
        Py_DECREF(hook_args);
1716
0
        err_msg_str = NULL;
1717
0
        obj = NULL;
1718
0
        goto error;
1719
0
    }
1720
0
    if (hook == NULL) {
1721
0
        Py_DECREF(hook_args);
1722
0
        goto default_hook;
1723
0
    }
1724
1725
0
    if (_PySys_Audit(tstate, "sys.unraisablehook", "OO", hook, hook_args) < 0) {
1726
0
        Py_DECREF(hook_args);
1727
0
        err_msg_str = "Exception ignored in audit hook";
1728
0
        obj = NULL;
1729
0
        goto error;
1730
0
    }
1731
1732
0
    if (hook == Py_None) {
1733
0
        Py_DECREF(hook_args);
1734
0
        goto default_hook;
1735
0
    }
1736
1737
0
    PyObject *res = PyObject_CallOneArg(hook, hook_args);
1738
0
    Py_DECREF(hook_args);
1739
0
    if (res != NULL) {
1740
0
        Py_DECREF(res);
1741
0
        goto done;
1742
0
    }
1743
1744
    /* sys.unraisablehook failed: log its error using default hook */
1745
0
    obj = hook;
1746
0
    err_msg_str = NULL;
1747
1748
0
error:
1749
    /* err_msg_str and obj have been updated and we have a new exception */
1750
0
    Py_XSETREF(err_msg, PyUnicode_FromString(err_msg_str ?
1751
0
        err_msg_str : "Exception ignored in sys.unraisablehook"));
1752
0
    Py_XDECREF(exc_type);
1753
0
    Py_XDECREF(exc_value);
1754
0
    Py_XDECREF(exc_tb);
1755
0
    _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
1756
1757
0
default_hook:
1758
    /* Call the default unraisable hook (ignore failure) */
1759
0
    (void)write_unraisable_exc(tstate, exc_type, exc_value, exc_tb,
1760
0
                               err_msg, obj);
1761
1762
0
done:
1763
0
    Py_XDECREF(exc_type);
1764
0
    Py_XDECREF(exc_value);
1765
0
    Py_XDECREF(exc_tb);
1766
0
    Py_XDECREF(err_msg);
1767
0
    Py_XDECREF(hook);
1768
0
    _PyErr_Clear(tstate); /* Just in case */
1769
0
}
1770
1771
void
1772
PyErr_FormatUnraisable(const char *format, ...)
1773
0
{
1774
0
    va_list va;
1775
1776
0
    va_start(va, format);
1777
0
    format_unraisable_v(format, va, NULL);
1778
0
    va_end(va);
1779
0
}
1780
1781
static void
1782
format_unraisable(PyObject *obj, const char *format, ...)
1783
0
{
1784
0
    va_list va;
1785
1786
0
    va_start(va, format);
1787
0
    format_unraisable_v(format, va, obj);
1788
0
    va_end(va);
1789
0
}
1790
1791
void
1792
PyErr_WriteUnraisable(PyObject *obj)
1793
0
{
1794
0
    format_unraisable(obj, NULL);
1795
0
}
1796
1797
1798
void
1799
PyErr_SyntaxLocation(const char *filename, int lineno)
1800
0
{
1801
0
    PyErr_SyntaxLocationEx(filename, lineno, -1);
1802
0
}
1803
1804
1805
/* Set file and line information for the current exception.
1806
   If the exception is not a SyntaxError, also sets additional attributes
1807
   to make printing of exceptions believe it is a syntax error. */
1808
1809
static void
1810
PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset,
1811
                             int end_lineno, int end_col_offset)
1812
21
{
1813
21
    PyThreadState *tstate = _PyThreadState_GET();
1814
1815
    /* add attributes for the line number and filename for the error */
1816
21
    PyObject *exc = _PyErr_GetRaisedException(tstate);
1817
    /* XXX check that it is, indeed, a syntax error. It might not
1818
     * be, though. */
1819
21
    PyObject *tmp = PyLong_FromLong(lineno);
1820
21
    if (tmp == NULL) {
1821
0
        _PyErr_Clear(tstate);
1822
0
    }
1823
21
    else {
1824
21
        if (PyObject_SetAttr(exc, &_Py_ID(lineno), tmp)) {
1825
0
            _PyErr_Clear(tstate);
1826
0
        }
1827
21
        Py_DECREF(tmp);
1828
21
    }
1829
21
    tmp = NULL;
1830
21
    if (col_offset >= 0) {
1831
21
        tmp = PyLong_FromLong(col_offset);
1832
21
        if (tmp == NULL) {
1833
0
            _PyErr_Clear(tstate);
1834
0
        }
1835
21
    }
1836
21
    if (PyObject_SetAttr(exc, &_Py_ID(offset), tmp ? tmp : Py_None)) {
1837
0
        _PyErr_Clear(tstate);
1838
0
    }
1839
21
    Py_XDECREF(tmp);
1840
1841
21
    tmp = NULL;
1842
21
    if (end_lineno >= 0) {
1843
21
        tmp = PyLong_FromLong(end_lineno);
1844
21
        if (tmp == NULL) {
1845
0
            _PyErr_Clear(tstate);
1846
0
        }
1847
21
    }
1848
21
    if (PyObject_SetAttr(exc, &_Py_ID(end_lineno), tmp ? tmp : Py_None)) {
1849
0
        _PyErr_Clear(tstate);
1850
0
    }
1851
21
    Py_XDECREF(tmp);
1852
1853
21
    tmp = NULL;
1854
21
    if (end_col_offset >= 0) {
1855
21
        tmp = PyLong_FromLong(end_col_offset);
1856
21
        if (tmp == NULL) {
1857
0
            _PyErr_Clear(tstate);
1858
0
        }
1859
21
    }
1860
21
    if (PyObject_SetAttr(exc, &_Py_ID(end_offset), tmp ? tmp : Py_None)) {
1861
0
        _PyErr_Clear(tstate);
1862
0
    }
1863
21
    Py_XDECREF(tmp);
1864
1865
21
    tmp = NULL;
1866
21
    if (filename != NULL) {
1867
21
        if (PyObject_SetAttr(exc, &_Py_ID(filename), filename)) {
1868
0
            _PyErr_Clear(tstate);
1869
0
        }
1870
1871
21
        tmp = PyErr_ProgramTextObject(filename, lineno);
1872
21
        if (tmp) {
1873
0
            if (PyObject_SetAttr(exc, &_Py_ID(text), tmp)) {
1874
0
                _PyErr_Clear(tstate);
1875
0
            }
1876
0
            Py_DECREF(tmp);
1877
0
        }
1878
21
        else {
1879
21
            _PyErr_Clear(tstate);
1880
21
        }
1881
21
    }
1882
21
    if ((PyObject *)Py_TYPE(exc) != PyExc_SyntaxError) {
1883
0
        int rc = PyObject_HasAttrWithError(exc, &_Py_ID(msg));
1884
0
        if (rc < 0) {
1885
0
            _PyErr_Clear(tstate);
1886
0
        }
1887
0
        else if (!rc) {
1888
0
            tmp = PyObject_Str(exc);
1889
0
            if (tmp) {
1890
0
                if (PyObject_SetAttr(exc, &_Py_ID(msg), tmp)) {
1891
0
                    _PyErr_Clear(tstate);
1892
0
                }
1893
0
                Py_DECREF(tmp);
1894
0
            }
1895
0
            else {
1896
0
                _PyErr_Clear(tstate);
1897
0
            }
1898
0
        }
1899
1900
0
        rc = PyObject_HasAttrWithError(exc, &_Py_ID(print_file_and_line));
1901
0
        if (rc < 0) {
1902
0
            _PyErr_Clear(tstate);
1903
0
        }
1904
0
        else if (!rc) {
1905
0
            if (PyObject_SetAttr(exc, &_Py_ID(print_file_and_line), Py_None)) {
1906
0
                _PyErr_Clear(tstate);
1907
0
            }
1908
0
        }
1909
0
    }
1910
21
    _PyErr_SetRaisedException(tstate, exc);
1911
21
}
1912
1913
void
1914
0
PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) {
1915
0
    PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, lineno, -1);
1916
0
}
1917
1918
void
1919
PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset,
1920
21
                                 int end_lineno, int end_col_offset) {
1921
21
    PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, end_lineno, end_col_offset);
1922
21
}
1923
1924
void
1925
PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1926
0
{
1927
0
    PyThreadState *tstate = _PyThreadState_GET();
1928
0
    PyObject *fileobj;
1929
0
    if (filename != NULL) {
1930
0
        fileobj = PyUnicode_DecodeFSDefault(filename);
1931
0
        if (fileobj == NULL) {
1932
0
            _PyErr_Clear(tstate);
1933
0
        }
1934
0
    }
1935
0
    else {
1936
0
        fileobj = NULL;
1937
0
    }
1938
0
    PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1939
0
    Py_XDECREF(fileobj);
1940
0
}
1941
1942
/* Raises a SyntaxError.
1943
 * If something goes wrong, a different exception may be raised.
1944
 */
1945
void
1946
_PyErr_RaiseSyntaxError(PyObject *msg, PyObject *filename, int lineno, int col_offset,
1947
                        int end_lineno, int end_col_offset)
1948
0
{
1949
0
    PyObject *text = PyErr_ProgramTextObject(filename, lineno);
1950
0
    if (text == NULL) {
1951
0
        text = Py_NewRef(Py_None);
1952
0
    }
1953
0
    PyObject *args = Py_BuildValue("O(OiiOii)", msg, filename,
1954
0
                                   lineno, col_offset, text,
1955
0
                                   end_lineno, end_col_offset);
1956
0
    if (args == NULL) {
1957
0
        goto exit;
1958
0
    }
1959
0
    PyErr_SetObject(PyExc_SyntaxError, args);
1960
0
 exit:
1961
0
    Py_DECREF(text);
1962
0
    Py_XDECREF(args);
1963
0
}
1964
1965
/* Emits a SyntaxWarning and returns 0 on success.
1966
   If a SyntaxWarning is raised as error, replaces it with a SyntaxError
1967
   and returns -1.
1968
*/
1969
int
1970
_PyErr_EmitSyntaxWarning(PyObject *msg, PyObject *filename, int lineno, int col_offset,
1971
                         int end_lineno, int end_col_offset,
1972
                         PyObject *module)
1973
0
{
1974
0
    if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, filename, lineno,
1975
0
                                 module, NULL) < 0)
1976
0
    {
1977
0
        if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
1978
            /* Replace the SyntaxWarning exception with a SyntaxError
1979
               to get a more accurate error report */
1980
0
            PyErr_Clear();
1981
0
            _PyErr_RaiseSyntaxError(msg, filename, lineno, col_offset,
1982
0
                                    end_lineno, end_col_offset);
1983
0
        }
1984
0
        return -1;
1985
0
    }
1986
0
    return 0;
1987
0
}
1988
1989
/* Attempt to load the line of text that the exception refers to.  If it
1990
   fails, it will return NULL but will not set an exception.
1991
1992
   XXX The functionality of this function is quite similar to the
1993
   functionality in tb_displayline() in traceback.c. */
1994
1995
static PyObject *
1996
err_programtext(FILE *fp, int lineno, const char* encoding)
1997
0
{
1998
0
    char linebuf[1000];
1999
0
    size_t line_size = 0;
2000
2001
0
    for (int i = 0; i < lineno; ) {
2002
0
        line_size = 0;
2003
0
        if (_Py_UniversalNewlineFgetsWithSize(linebuf, sizeof(linebuf),
2004
0
                                              fp, NULL, &line_size) == NULL)
2005
0
        {
2006
            /* Error or EOF. */
2007
0
            return NULL;
2008
0
        }
2009
        /* fgets read *something*; if it didn't fill the
2010
           whole buffer, it must have found a newline
2011
           or hit the end of the file; if the last character is \n,
2012
           it obviously found a newline; else we haven't
2013
           yet seen a newline, so must continue */
2014
0
        if (i + 1 < lineno
2015
0
            && line_size == sizeof(linebuf) - 1
2016
0
            && linebuf[sizeof(linebuf) - 2] != '\n')
2017
0
        {
2018
0
            continue;
2019
0
        }
2020
0
        i++;
2021
0
    }
2022
2023
0
    const char *line = linebuf;
2024
    /* Skip BOM. */
2025
0
    if (lineno == 1 && line_size >= 3 && memcmp(line, "\xef\xbb\xbf", 3) == 0) {
2026
0
        line += 3;
2027
0
        line_size -= 3;
2028
0
    }
2029
0
    PyObject *res = PyUnicode_Decode(line, line_size, encoding, "replace");
2030
0
    if (res == NULL) {
2031
0
        PyErr_Clear();
2032
0
    }
2033
0
    return res;
2034
0
}
2035
2036
PyObject *
2037
PyErr_ProgramText(const char *filename, int lineno)
2038
0
{
2039
0
    if (filename == NULL) {
2040
0
        return NULL;
2041
0
    }
2042
2043
0
    PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
2044
0
    if (filename_obj == NULL) {
2045
0
        PyErr_Clear();
2046
0
        return NULL;
2047
0
    }
2048
0
    PyObject *res = PyErr_ProgramTextObject(filename_obj, lineno);
2049
0
    Py_DECREF(filename_obj);
2050
0
    return res;
2051
0
}
2052
2053
/* Function from Parser/tokenizer/file_tokenizer.c */
2054
extern char* _PyTokenizer_FindEncodingFilename(int, PyObject *);
2055
2056
PyObject *
2057
_PyErr_ProgramDecodedTextObject(PyObject *filename, int lineno, const char* encoding)
2058
87.9k
{
2059
87.9k
    char *found_encoding = NULL;
2060
87.9k
    if (filename == NULL || lineno <= 0) {
2061
0
        return NULL;
2062
0
    }
2063
2064
87.9k
    FILE *fp = Py_fopen(filename, "r" PY_STDIOTEXTMODE);
2065
87.9k
    if (fp == NULL) {
2066
87.9k
        PyErr_Clear();
2067
87.9k
        return NULL;
2068
87.9k
    }
2069
0
    if (encoding == NULL) {
2070
0
        int fd = fileno(fp);
2071
0
        found_encoding = _PyTokenizer_FindEncodingFilename(fd, filename);
2072
0
        encoding = found_encoding;
2073
0
        if (encoding == NULL) {
2074
0
            PyErr_Clear();
2075
0
            encoding = "utf-8";
2076
0
        }
2077
        /* Reset position */
2078
0
        if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
2079
0
            fclose(fp);
2080
0
            PyMem_Free(found_encoding);
2081
0
            return NULL;
2082
0
        }
2083
0
    }
2084
0
    PyObject *res = err_programtext(fp, lineno, encoding);
2085
0
    fclose(fp);
2086
0
    PyMem_Free(found_encoding);
2087
0
    return res;
2088
0
}
2089
2090
PyObject *
2091
PyErr_ProgramTextObject(PyObject *filename, int lineno)
2092
21
{
2093
    return _PyErr_ProgramDecodedTextObject(filename, lineno, NULL);
2094
21
}