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