Coverage Report

Created: 2026-10-17 06:15

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