ยปCore Development>Code coverage>Python/errors.c

Python code coverage for Python/errors.c

#countcontent
1n/a
2n/a/* Error handling */
3n/a
4n/a#include "Python.h"
5n/a
6n/a#ifndef __STDC__
7n/a#ifndef MS_WINDOWS
8n/aextern char *strerror(int);
9n/a#endif
10n/a#endif
11n/a
12n/a#ifdef MS_WINDOWS
13n/a#include <windows.h>
14n/a#include <winbase.h>
15n/a#endif
16n/a
17n/a#include <ctype.h>
18n/a
19n/a#ifdef __cplusplus
20n/aextern "C" {
21n/a#endif
22n/a
23n/a_Py_IDENTIFIER(builtins);
24n/a_Py_IDENTIFIER(stderr);
25n/a
26n/a
27n/avoid
28n/aPyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
29n/a{
30n/a PyThreadState *tstate = PyThreadState_GET();
31n/a PyObject *oldtype, *oldvalue, *oldtraceback;
32n/a
33n/a if (traceback != NULL && !PyTraceBack_Check(traceback)) {
34n/a /* XXX Should never happen -- fatal error instead? */
35n/a /* Well, it could be None. */
36n/a Py_DECREF(traceback);
37n/a traceback = NULL;
38n/a }
39n/a
40n/a /* Save these in locals to safeguard against recursive
41n/a invocation through Py_XDECREF */
42n/a oldtype = tstate->curexc_type;
43n/a oldvalue = tstate->curexc_value;
44n/a oldtraceback = tstate->curexc_traceback;
45n/a
46n/a tstate->curexc_type = type;
47n/a tstate->curexc_value = value;
48n/a tstate->curexc_traceback = traceback;
49n/a
50n/a Py_XDECREF(oldtype);
51n/a Py_XDECREF(oldvalue);
52n/a Py_XDECREF(oldtraceback);
53n/a}
54n/a
55n/astatic PyObject*
56n/a_PyErr_CreateException(PyObject *exception, PyObject *value)
57n/a{
58n/a if (value == NULL || value == Py_None) {
59n/a return _PyObject_CallNoArg(exception);
60n/a }
61n/a else if (PyTuple_Check(value)) {
62n/a return PyObject_Call(exception, value, NULL);
63n/a }
64n/a else {
65n/a return PyObject_CallFunctionObjArgs(exception, value, NULL);
66n/a }
67n/a}
68n/a
69n/avoid
70n/aPyErr_SetObject(PyObject *exception, PyObject *value)
71n/a{
72n/a PyThreadState *tstate = PyThreadState_GET();
73n/a PyObject *exc_value;
74n/a PyObject *tb = NULL;
75n/a
76n/a if (exception != NULL &&
77n/a !PyExceptionClass_Check(exception)) {
78n/a PyErr_Format(PyExc_SystemError,
79n/a "exception %R not a BaseException subclass",
80n/a exception);
81n/a return;
82n/a }
83n/a
84n/a Py_XINCREF(value);
85n/a exc_value = tstate->exc_value;
86n/a if (exc_value != NULL && exc_value != Py_None) {
87n/a /* Implicit exception chaining */
88n/a Py_INCREF(exc_value);
89n/a if (value == NULL || !PyExceptionInstance_Check(value)) {
90n/a /* We must normalize the value right now */
91n/a PyObject *fixed_value;
92n/a
93n/a /* Issue #23571: functions must not be called with an
94n/a exception set */
95n/a PyErr_Clear();
96n/a
97n/a fixed_value = _PyErr_CreateException(exception, value);
98n/a Py_XDECREF(value);
99n/a if (fixed_value == NULL) {
100n/a return;
101n/a }
102n/a
103n/a value = fixed_value;
104n/a }
105n/a
106n/a /* Avoid reference cycles through the context chain.
107n/a This is O(chain length) but context chains are
108n/a usually very short. Sensitive readers may try
109n/a to inline the call to PyException_GetContext. */
110n/a if (exc_value != value) {
111n/a PyObject *o = exc_value, *context;
112n/a while ((context = PyException_GetContext(o))) {
113n/a Py_DECREF(context);
114n/a if (context == value) {
115n/a PyException_SetContext(o, NULL);
116n/a break;
117n/a }
118n/a o = context;
119n/a }
120n/a PyException_SetContext(value, exc_value);
121n/a }
122n/a else {
123n/a Py_DECREF(exc_value);
124n/a }
125n/a }
126n/a if (value != NULL && PyExceptionInstance_Check(value))
127n/a tb = PyException_GetTraceback(value);
128n/a Py_XINCREF(exception);
129n/a PyErr_Restore(exception, value, tb);
130n/a}
131n/a
132n/a/* Set a key error with the specified argument, wrapping it in a
133n/a * tuple automatically so that tuple keys are not unpacked as the
134n/a * exception arguments. */
135n/avoid
136n/a_PyErr_SetKeyError(PyObject *arg)
137n/a{
138n/a PyObject *tup;
139n/a tup = PyTuple_Pack(1, arg);
140n/a if (!tup)
141n/a return; /* caller will expect error to be set anyway */
142n/a PyErr_SetObject(PyExc_KeyError, tup);
143n/a Py_DECREF(tup);
144n/a}
145n/a
146n/avoid
147n/aPyErr_SetNone(PyObject *exception)
148n/a{
149n/a PyErr_SetObject(exception, (PyObject *)NULL);
150n/a}
151n/a
152n/avoid
153n/aPyErr_SetString(PyObject *exception, const char *string)
154n/a{
155n/a PyObject *value = PyUnicode_FromString(string);
156n/a PyErr_SetObject(exception, value);
157n/a Py_XDECREF(value);
158n/a}
159n/a
160n/a
161n/aPyObject* _Py_HOT_FUNCTION
162n/aPyErr_Occurred(void)
163n/a{
164n/a PyThreadState *tstate = PyThreadState_GET();
165n/a return tstate == NULL ? NULL : tstate->curexc_type;
166n/a}
167n/a
168n/a
169n/aint
170n/aPyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
171n/a{
172n/a if (err == NULL || exc == NULL) {
173n/a /* maybe caused by "import exceptions" that failed early on */
174n/a return 0;
175n/a }
176n/a if (PyTuple_Check(exc)) {
177n/a Py_ssize_t i, n;
178n/a n = PyTuple_Size(exc);
179n/a for (i = 0; i < n; i++) {
180n/a /* Test recursively */
181n/a if (PyErr_GivenExceptionMatches(
182n/a err, PyTuple_GET_ITEM(exc, i)))
183n/a {
184n/a return 1;
185n/a }
186n/a }
187n/a return 0;
188n/a }
189n/a /* err might be an instance, so check its class. */
190n/a if (PyExceptionInstance_Check(err))
191n/a err = PyExceptionInstance_Class(err);
192n/a
193n/a if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
194n/a int res = 0;
195n/a PyObject *exception, *value, *tb;
196n/a PyErr_Fetch(&exception, &value, &tb);
197n/a /* PyObject_IsSubclass() can recurse and therefore is
198n/a not safe (see test_bad_getattr in test.pickletester). */
199n/a res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
200n/a /* This function must not fail, so print the error here */
201n/a if (res == -1) {
202n/a PyErr_WriteUnraisable(err);
203n/a res = 0;
204n/a }
205n/a PyErr_Restore(exception, value, tb);
206n/a return res;
207n/a }
208n/a
209n/a return err == exc;
210n/a}
211n/a
212n/a
213n/aint
214n/aPyErr_ExceptionMatches(PyObject *exc)
215n/a{
216n/a return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
217n/a}
218n/a
219n/a
220n/a/* Used in many places to normalize a raised exception, including in
221n/a eval_code2(), do_raise(), and PyErr_Print()
222n/a
223n/a XXX: should PyErr_NormalizeException() also call
224n/a PyException_SetTraceback() with the resulting value and tb?
225n/a*/
226n/avoid
227n/aPyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
228n/a{
229n/a PyObject *type = *exc;
230n/a PyObject *value = *val;
231n/a PyObject *inclass = NULL;
232n/a PyObject *initial_tb = NULL;
233n/a PyThreadState *tstate = NULL;
234n/a
235n/a if (type == NULL) {
236n/a /* There was no exception, so nothing to do. */
237n/a return;
238n/a }
239n/a
240n/a /* If PyErr_SetNone() was used, the value will have been actually
241n/a set to NULL.
242n/a */
243n/a if (!value) {
244n/a value = Py_None;
245n/a Py_INCREF(value);
246n/a }
247n/a
248n/a if (PyExceptionInstance_Check(value))
249n/a inclass = PyExceptionInstance_Class(value);
250n/a
251n/a /* Normalize the exception so that if the type is a class, the
252n/a value will be an instance.
253n/a */
254n/a if (PyExceptionClass_Check(type)) {
255n/a int is_subclass;
256n/a if (inclass) {
257n/a is_subclass = PyObject_IsSubclass(inclass, type);
258n/a if (is_subclass < 0)
259n/a goto finally;
260n/a }
261n/a else
262n/a is_subclass = 0;
263n/a
264n/a /* if the value was not an instance, or is not an instance
265n/a whose class is (or is derived from) type, then use the
266n/a value as an argument to instantiation of the type
267n/a class.
268n/a */
269n/a if (!inclass || !is_subclass) {
270n/a PyObject *fixed_value;
271n/a
272n/a fixed_value = _PyErr_CreateException(type, value);
273n/a if (fixed_value == NULL) {
274n/a goto finally;
275n/a }
276n/a
277n/a Py_DECREF(value);
278n/a value = fixed_value;
279n/a }
280n/a /* if the class of the instance doesn't exactly match the
281n/a class of the type, believe the instance
282n/a */
283n/a else if (inclass != type) {
284n/a Py_DECREF(type);
285n/a type = inclass;
286n/a Py_INCREF(type);
287n/a }
288n/a }
289n/a *exc = type;
290n/a *val = value;
291n/a return;
292n/afinally:
293n/a Py_DECREF(type);
294n/a Py_DECREF(value);
295n/a /* If the new exception doesn't set a traceback and the old
296n/a exception had a traceback, use the old traceback for the
297n/a new exception. It's better than nothing.
298n/a */
299n/a initial_tb = *tb;
300n/a PyErr_Fetch(exc, val, tb);
301n/a if (initial_tb != NULL) {
302n/a if (*tb == NULL)
303n/a *tb = initial_tb;
304n/a else
305n/a Py_DECREF(initial_tb);
306n/a }
307n/a /* normalize recursively */
308n/a tstate = PyThreadState_GET();
309n/a if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
310n/a --tstate->recursion_depth;
311n/a /* throw away the old exception and use the recursion error instead */
312n/a Py_INCREF(PyExc_RecursionError);
313n/a Py_SETREF(*exc, PyExc_RecursionError);
314n/a Py_INCREF(PyExc_RecursionErrorInst);
315n/a Py_SETREF(*val, PyExc_RecursionErrorInst);
316n/a /* just keeping the old traceback */
317n/a return;
318n/a }
319n/a PyErr_NormalizeException(exc, val, tb);
320n/a --tstate->recursion_depth;
321n/a}
322n/a
323n/a
324n/avoid
325n/aPyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
326n/a{
327n/a PyThreadState *tstate = PyThreadState_GET();
328n/a
329n/a *p_type = tstate->curexc_type;
330n/a *p_value = tstate->curexc_value;
331n/a *p_traceback = tstate->curexc_traceback;
332n/a
333n/a tstate->curexc_type = NULL;
334n/a tstate->curexc_value = NULL;
335n/a tstate->curexc_traceback = NULL;
336n/a}
337n/a
338n/avoid
339n/aPyErr_Clear(void)
340n/a{
341n/a PyErr_Restore(NULL, NULL, NULL);
342n/a}
343n/a
344n/avoid
345n/aPyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
346n/a{
347n/a PyThreadState *tstate = PyThreadState_GET();
348n/a
349n/a *p_type = tstate->exc_type;
350n/a *p_value = tstate->exc_value;
351n/a *p_traceback = tstate->exc_traceback;
352n/a
353n/a Py_XINCREF(*p_type);
354n/a Py_XINCREF(*p_value);
355n/a Py_XINCREF(*p_traceback);
356n/a}
357n/a
358n/avoid
359n/aPyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
360n/a{
361n/a PyObject *oldtype, *oldvalue, *oldtraceback;
362n/a PyThreadState *tstate = PyThreadState_GET();
363n/a
364n/a oldtype = tstate->exc_type;
365n/a oldvalue = tstate->exc_value;
366n/a oldtraceback = tstate->exc_traceback;
367n/a
368n/a tstate->exc_type = p_type;
369n/a tstate->exc_value = p_value;
370n/a tstate->exc_traceback = p_traceback;
371n/a
372n/a Py_XDECREF(oldtype);
373n/a Py_XDECREF(oldvalue);
374n/a Py_XDECREF(oldtraceback);
375n/a}
376n/a
377n/a/* Like PyErr_Restore(), but if an exception is already set,
378n/a set the context associated with it.
379n/a */
380n/avoid
381n/a_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
382n/a{
383n/a if (exc == NULL)
384n/a return;
385n/a
386n/a if (PyErr_Occurred()) {
387n/a PyObject *exc2, *val2, *tb2;
388n/a PyErr_Fetch(&exc2, &val2, &tb2);
389n/a PyErr_NormalizeException(&exc, &val, &tb);
390n/a if (tb != NULL) {
391n/a PyException_SetTraceback(val, tb);
392n/a Py_DECREF(tb);
393n/a }
394n/a Py_DECREF(exc);
395n/a PyErr_NormalizeException(&exc2, &val2, &tb2);
396n/a PyException_SetContext(val2, val);
397n/a PyErr_Restore(exc2, val2, tb2);
398n/a }
399n/a else {
400n/a PyErr_Restore(exc, val, tb);
401n/a }
402n/a}
403n/a
404n/astatic PyObject *
405n/a_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
406n/a{
407n/a PyObject *exc, *val, *val2, *tb;
408n/a
409n/a assert(PyErr_Occurred());
410n/a PyErr_Fetch(&exc, &val, &tb);
411n/a PyErr_NormalizeException(&exc, &val, &tb);
412n/a if (tb != NULL) {
413n/a PyException_SetTraceback(val, tb);
414n/a Py_DECREF(tb);
415n/a }
416n/a Py_DECREF(exc);
417n/a assert(!PyErr_Occurred());
418n/a
419n/a PyErr_FormatV(exception, format, vargs);
420n/a
421n/a PyErr_Fetch(&exc, &val2, &tb);
422n/a PyErr_NormalizeException(&exc, &val2, &tb);
423n/a Py_INCREF(val);
424n/a PyException_SetCause(val2, val);
425n/a PyException_SetContext(val2, val);
426n/a PyErr_Restore(exc, val2, tb);
427n/a
428n/a return NULL;
429n/a}
430n/a
431n/aPyObject *
432n/a_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
433n/a{
434n/a va_list vargs;
435n/a#ifdef HAVE_STDARG_PROTOTYPES
436n/a va_start(vargs, format);
437n/a#else
438n/a va_start(vargs);
439n/a#endif
440n/a _PyErr_FormatVFromCause(exception, format, vargs);
441n/a va_end(vargs);
442n/a return NULL;
443n/a}
444n/a
445n/a/* Convenience functions to set a type error exception and return 0 */
446n/a
447n/aint
448n/aPyErr_BadArgument(void)
449n/a{
450n/a PyErr_SetString(PyExc_TypeError,
451n/a "bad argument type for built-in operation");
452n/a return 0;
453n/a}
454n/a
455n/aPyObject *
456n/aPyErr_NoMemory(void)
457n/a{
458n/a if (Py_TYPE(PyExc_MemoryError) == NULL) {
459n/a /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
460n/a initialized by _PyExc_Init() */
461n/a Py_FatalError("Out of memory and PyExc_MemoryError is not "
462n/a "initialized yet");
463n/a }
464n/a PyErr_SetNone(PyExc_MemoryError);
465n/a return NULL;
466n/a}
467n/a
468n/aPyObject *
469n/aPyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
470n/a{
471n/a return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
472n/a}
473n/a
474n/aPyObject *
475n/aPyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
476n/a{
477n/a PyObject *message;
478n/a PyObject *v, *args;
479n/a int i = errno;
480n/a#ifdef MS_WINDOWS
481n/a WCHAR *s_buf = NULL;
482n/a#endif /* Unix/Windows */
483n/a
484n/a#ifdef EINTR
485n/a if (i == EINTR && PyErr_CheckSignals())
486n/a return NULL;
487n/a#endif
488n/a
489n/a#ifndef MS_WINDOWS
490n/a if (i != 0) {
491n/a char *s = strerror(i);
492n/a message = PyUnicode_DecodeLocale(s, "surrogateescape");
493n/a }
494n/a else {
495n/a /* Sometimes errno didn't get set */
496n/a message = PyUnicode_FromString("Error");
497n/a }
498n/a#else
499n/a if (i == 0)
500n/a message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
501n/a else
502n/a {
503n/a /* Note that the Win32 errors do not lineup with the
504n/a errno error. So if the error is in the MSVC error
505n/a table, we use it, otherwise we assume it really _is_
506n/a a Win32 error code
507n/a */
508n/a if (i > 0 && i < _sys_nerr) {
509n/a message = PyUnicode_FromString(_sys_errlist[i]);
510n/a }
511n/a else {
512n/a int len = FormatMessageW(
513n/a FORMAT_MESSAGE_ALLOCATE_BUFFER |
514n/a FORMAT_MESSAGE_FROM_SYSTEM |
515n/a FORMAT_MESSAGE_IGNORE_INSERTS,
516n/a NULL, /* no message source */
517n/a i,
518n/a MAKELANGID(LANG_NEUTRAL,
519n/a SUBLANG_DEFAULT),
520n/a /* Default language */
521n/a (LPWSTR) &s_buf,
522n/a 0, /* size not used */
523n/a NULL); /* no args */
524n/a if (len==0) {
525n/a /* Only ever seen this in out-of-mem
526n/a situations */
527n/a s_buf = NULL;
528n/a message = PyUnicode_FromFormat("Windows Error 0x%x", i);
529n/a } else {
530n/a /* remove trailing cr/lf and dots */
531n/a while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
532n/a s_buf[--len] = L'\0';
533n/a message = PyUnicode_FromWideChar(s_buf, len);
534n/a }
535n/a }
536n/a }
537n/a#endif /* Unix/Windows */
538n/a
539n/a if (message == NULL)
540n/a {
541n/a#ifdef MS_WINDOWS
542n/a LocalFree(s_buf);
543n/a#endif
544n/a return NULL;
545n/a }
546n/a
547n/a if (filenameObject != NULL) {
548n/a if (filenameObject2 != NULL)
549n/a args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
550n/a else
551n/a args = Py_BuildValue("(iOO)", i, message, filenameObject);
552n/a } else {
553n/a assert(filenameObject2 == NULL);
554n/a args = Py_BuildValue("(iO)", i, message);
555n/a }
556n/a Py_DECREF(message);
557n/a
558n/a if (args != NULL) {
559n/a v = PyObject_Call(exc, args, NULL);
560n/a Py_DECREF(args);
561n/a if (v != NULL) {
562n/a PyErr_SetObject((PyObject *) Py_TYPE(v), v);
563n/a Py_DECREF(v);
564n/a }
565n/a }
566n/a#ifdef MS_WINDOWS
567n/a LocalFree(s_buf);
568n/a#endif
569n/a return NULL;
570n/a}
571n/a
572n/aPyObject *
573n/aPyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
574n/a{
575n/a PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
576n/a PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
577n/a Py_XDECREF(name);
578n/a return result;
579n/a}
580n/a
581n/a#ifdef MS_WINDOWS
582n/aPyObject *
583n/aPyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
584n/a{
585n/a PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
586n/a PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
587n/a Py_XDECREF(name);
588n/a return result;
589n/a}
590n/a#endif /* MS_WINDOWS */
591n/a
592n/aPyObject *
593n/aPyErr_SetFromErrno(PyObject *exc)
594n/a{
595n/a return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
596n/a}
597n/a
598n/a#ifdef MS_WINDOWS
599n/a/* Windows specific error code handling */
600n/aPyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
601n/a PyObject *exc,
602n/a int ierr,
603n/a PyObject *filenameObject)
604n/a{
605n/a return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
606n/a filenameObject, NULL);
607n/a}
608n/a
609n/aPyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
610n/a PyObject *exc,
611n/a int ierr,
612n/a PyObject *filenameObject,
613n/a PyObject *filenameObject2)
614n/a{
615n/a int len;
616n/a WCHAR *s_buf = NULL; /* Free via LocalFree */
617n/a PyObject *message;
618n/a PyObject *args, *v;
619n/a DWORD err = (DWORD)ierr;
620n/a if (err==0) err = GetLastError();
621n/a len = FormatMessageW(
622n/a /* Error API error */
623n/a FORMAT_MESSAGE_ALLOCATE_BUFFER |
624n/a FORMAT_MESSAGE_FROM_SYSTEM |
625n/a FORMAT_MESSAGE_IGNORE_INSERTS,
626n/a NULL, /* no message source */
627n/a err,
628n/a MAKELANGID(LANG_NEUTRAL,
629n/a SUBLANG_DEFAULT), /* Default language */
630n/a (LPWSTR) &s_buf,
631n/a 0, /* size not used */
632n/a NULL); /* no args */
633n/a if (len==0) {
634n/a /* Only seen this in out of mem situations */
635n/a message = PyUnicode_FromFormat("Windows Error 0x%x", err);
636n/a s_buf = NULL;
637n/a } else {
638n/a /* remove trailing cr/lf and dots */
639n/a while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
640n/a s_buf[--len] = L'\0';
641n/a message = PyUnicode_FromWideChar(s_buf, len);
642n/a }
643n/a
644n/a if (message == NULL)
645n/a {
646n/a LocalFree(s_buf);
647n/a return NULL;
648n/a }
649n/a
650n/a if (filenameObject == NULL) {
651n/a assert(filenameObject2 == NULL);
652n/a filenameObject = filenameObject2 = Py_None;
653n/a }
654n/a else if (filenameObject2 == NULL)
655n/a filenameObject2 = Py_None;
656n/a /* This is the constructor signature for OSError.
657n/a The POSIX translation will be figured out by the constructor. */
658n/a args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
659n/a Py_DECREF(message);
660n/a
661n/a if (args != NULL) {
662n/a v = PyObject_Call(exc, args, NULL);
663n/a Py_DECREF(args);
664n/a if (v != NULL) {
665n/a PyErr_SetObject((PyObject *) Py_TYPE(v), v);
666n/a Py_DECREF(v);
667n/a }
668n/a }
669n/a LocalFree(s_buf);
670n/a return NULL;
671n/a}
672n/a
673n/aPyObject *PyErr_SetExcFromWindowsErrWithFilename(
674n/a PyObject *exc,
675n/a int ierr,
676n/a const char *filename)
677n/a{
678n/a PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
679n/a PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
680n/a ierr,
681n/a name,
682n/a NULL);
683n/a Py_XDECREF(name);
684n/a return ret;
685n/a}
686n/a
687n/aPyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
688n/a PyObject *exc,
689n/a int ierr,
690n/a const Py_UNICODE *filename)
691n/a{
692n/a PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
693n/a PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
694n/a ierr,
695n/a name,
696n/a NULL);
697n/a Py_XDECREF(name);
698n/a return ret;
699n/a}
700n/a
701n/aPyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
702n/a{
703n/a return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
704n/a}
705n/a
706n/aPyObject *PyErr_SetFromWindowsErr(int ierr)
707n/a{
708n/a return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
709n/a ierr, NULL);
710n/a}
711n/a
712n/aPyObject *PyErr_SetFromWindowsErrWithFilename(
713n/a int ierr,
714n/a const char *filename)
715n/a{
716n/a PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
717n/a PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
718n/a PyExc_OSError,
719n/a ierr, name, NULL);
720n/a Py_XDECREF(name);
721n/a return result;
722n/a}
723n/a
724n/aPyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
725n/a int ierr,
726n/a const Py_UNICODE *filename)
727n/a{
728n/a PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
729n/a PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
730n/a PyExc_OSError,
731n/a ierr, name, NULL);
732n/a Py_XDECREF(name);
733n/a return result;
734n/a}
735n/a#endif /* MS_WINDOWS */
736n/a
737n/aPyObject *
738n/aPyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
739n/a PyObject *name, PyObject *path)
740n/a{
741n/a int issubclass;
742n/a PyObject *kwargs, *error;
743n/a
744n/a issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
745n/a if (issubclass < 0) {
746n/a return NULL;
747n/a }
748n/a else if (!issubclass) {
749n/a PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
750n/a return NULL;
751n/a }
752n/a
753n/a if (msg == NULL) {
754n/a PyErr_SetString(PyExc_TypeError, "expected a message argument");
755n/a return NULL;
756n/a }
757n/a
758n/a if (name == NULL) {
759n/a name = Py_None;
760n/a }
761n/a if (path == NULL) {
762n/a path = Py_None;
763n/a }
764n/a
765n/a kwargs = PyDict_New();
766n/a if (kwargs == NULL) {
767n/a return NULL;
768n/a }
769n/a if (PyDict_SetItemString(kwargs, "name", name) < 0) {
770n/a goto done;
771n/a }
772n/a if (PyDict_SetItemString(kwargs, "path", path) < 0) {
773n/a goto done;
774n/a }
775n/a
776n/a error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
777n/a if (error != NULL) {
778n/a PyErr_SetObject((PyObject *)Py_TYPE(error), error);
779n/a Py_DECREF(error);
780n/a }
781n/a
782n/adone:
783n/a Py_DECREF(kwargs);
784n/a return NULL;
785n/a}
786n/a
787n/aPyObject *
788n/aPyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
789n/a{
790n/a return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
791n/a}
792n/a
793n/avoid
794n/a_PyErr_BadInternalCall(const char *filename, int lineno)
795n/a{
796n/a PyErr_Format(PyExc_SystemError,
797n/a "%s:%d: bad argument to internal function",
798n/a filename, lineno);
799n/a}
800n/a
801n/a/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
802n/a export the entry point for existing object code: */
803n/a#undef PyErr_BadInternalCall
804n/avoid
805n/aPyErr_BadInternalCall(void)
806n/a{
807n/a assert(0 && "bad argument to internal function");
808n/a PyErr_Format(PyExc_SystemError,
809n/a "bad argument to internal function");
810n/a}
811n/a#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
812n/a
813n/a
814n/aPyObject *
815n/aPyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
816n/a{
817n/a PyObject* string;
818n/a
819n/a /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
820n/a exception set, it calls arbitrary Python code like PyObject_Repr() */
821n/a PyErr_Clear();
822n/a
823n/a string = PyUnicode_FromFormatV(format, vargs);
824n/a
825n/a PyErr_SetObject(exception, string);
826n/a Py_XDECREF(string);
827n/a return NULL;
828n/a}
829n/a
830n/a
831n/aPyObject *
832n/aPyErr_Format(PyObject *exception, const char *format, ...)
833n/a{
834n/a va_list vargs;
835n/a#ifdef HAVE_STDARG_PROTOTYPES
836n/a va_start(vargs, format);
837n/a#else
838n/a va_start(vargs);
839n/a#endif
840n/a PyErr_FormatV(exception, format, vargs);
841n/a va_end(vargs);
842n/a return NULL;
843n/a}
844n/a
845n/a
846n/aPyObject *
847n/aPyErr_NewException(const char *name, PyObject *base, PyObject *dict)
848n/a{
849n/a const char *dot;
850n/a PyObject *modulename = NULL;
851n/a PyObject *classname = NULL;
852n/a PyObject *mydict = NULL;
853n/a PyObject *bases = NULL;
854n/a PyObject *result = NULL;
855n/a dot = strrchr(name, '.');
856n/a if (dot == NULL) {
857n/a PyErr_SetString(PyExc_SystemError,
858n/a "PyErr_NewException: name must be module.class");
859n/a return NULL;
860n/a }
861n/a if (base == NULL)
862n/a base = PyExc_Exception;
863n/a if (dict == NULL) {
864n/a dict = mydict = PyDict_New();
865n/a if (dict == NULL)
866n/a goto failure;
867n/a }
868n/a if (PyDict_GetItemString(dict, "__module__") == NULL) {
869n/a modulename = PyUnicode_FromStringAndSize(name,
870n/a (Py_ssize_t)(dot-name));
871n/a if (modulename == NULL)
872n/a goto failure;
873n/a if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
874n/a goto failure;
875n/a }
876n/a if (PyTuple_Check(base)) {
877n/a bases = base;
878n/a /* INCREF as we create a new ref in the else branch */
879n/a Py_INCREF(bases);
880n/a } else {
881n/a bases = PyTuple_Pack(1, base);
882n/a if (bases == NULL)
883n/a goto failure;
884n/a }
885n/a /* Create a real class. */
886n/a result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
887n/a dot+1, bases, dict);
888n/a failure:
889n/a Py_XDECREF(bases);
890n/a Py_XDECREF(mydict);
891n/a Py_XDECREF(classname);
892n/a Py_XDECREF(modulename);
893n/a return result;
894n/a}
895n/a
896n/a
897n/a/* Create an exception with docstring */
898n/aPyObject *
899n/aPyErr_NewExceptionWithDoc(const char *name, const char *doc,
900n/a PyObject *base, PyObject *dict)
901n/a{
902n/a int result;
903n/a PyObject *ret = NULL;
904n/a PyObject *mydict = NULL; /* points to the dict only if we create it */
905n/a PyObject *docobj;
906n/a
907n/a if (dict == NULL) {
908n/a dict = mydict = PyDict_New();
909n/a if (dict == NULL) {
910n/a return NULL;
911n/a }
912n/a }
913n/a
914n/a if (doc != NULL) {
915n/a docobj = PyUnicode_FromString(doc);
916n/a if (docobj == NULL)
917n/a goto failure;
918n/a result = PyDict_SetItemString(dict, "__doc__", docobj);
919n/a Py_DECREF(docobj);
920n/a if (result < 0)
921n/a goto failure;
922n/a }
923n/a
924n/a ret = PyErr_NewException(name, base, dict);
925n/a failure:
926n/a Py_XDECREF(mydict);
927n/a return ret;
928n/a}
929n/a
930n/a
931n/a/* Call when an exception has occurred but there is no way for Python
932n/a to handle it. Examples: exception in __del__ or during GC. */
933n/avoid
934n/aPyErr_WriteUnraisable(PyObject *obj)
935n/a{
936n/a _Py_IDENTIFIER(__module__);
937n/a PyObject *f, *t, *v, *tb;
938n/a PyObject *moduleName = NULL;
939n/a char* className;
940n/a
941n/a PyErr_Fetch(&t, &v, &tb);
942n/a
943n/a f = _PySys_GetObjectId(&PyId_stderr);
944n/a if (f == NULL || f == Py_None)
945n/a goto done;
946n/a
947n/a if (obj) {
948n/a if (PyFile_WriteString("Exception ignored in: ", f) < 0)
949n/a goto done;
950n/a if (PyFile_WriteObject(obj, f, 0) < 0) {
951n/a PyErr_Clear();
952n/a if (PyFile_WriteString("<object repr() failed>", f) < 0) {
953n/a goto done;
954n/a }
955n/a }
956n/a if (PyFile_WriteString("\n", f) < 0)
957n/a goto done;
958n/a }
959n/a
960n/a if (PyTraceBack_Print(tb, f) < 0)
961n/a goto done;
962n/a
963n/a if (!t)
964n/a goto done;
965n/a
966n/a assert(PyExceptionClass_Check(t));
967n/a className = PyExceptionClass_Name(t);
968n/a if (className != NULL) {
969n/a char *dot = strrchr(className, '.');
970n/a if (dot != NULL)
971n/a className = dot+1;
972n/a }
973n/a
974n/a moduleName = _PyObject_GetAttrId(t, &PyId___module__);
975n/a if (moduleName == NULL) {
976n/a PyErr_Clear();
977n/a if (PyFile_WriteString("<unknown>", f) < 0)
978n/a goto done;
979n/a }
980n/a else {
981n/a if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
982n/a if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
983n/a goto done;
984n/a if (PyFile_WriteString(".", f) < 0)
985n/a goto done;
986n/a }
987n/a }
988n/a if (className == NULL) {
989n/a if (PyFile_WriteString("<unknown>", f) < 0)
990n/a goto done;
991n/a }
992n/a else {
993n/a if (PyFile_WriteString(className, f) < 0)
994n/a goto done;
995n/a }
996n/a
997n/a if (v && v != Py_None) {
998n/a if (PyFile_WriteString(": ", f) < 0)
999n/a goto done;
1000n/a if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1001n/a PyErr_Clear();
1002n/a if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1003n/a goto done;
1004n/a }
1005n/a }
1006n/a }
1007n/a if (PyFile_WriteString("\n", f) < 0)
1008n/a goto done;
1009n/a
1010n/adone:
1011n/a Py_XDECREF(moduleName);
1012n/a Py_XDECREF(t);
1013n/a Py_XDECREF(v);
1014n/a Py_XDECREF(tb);
1015n/a PyErr_Clear(); /* Just in case */
1016n/a}
1017n/a
1018n/aextern PyObject *PyModule_GetWarningsModule(void);
1019n/a
1020n/a
1021n/avoid
1022n/aPyErr_SyntaxLocation(const char *filename, int lineno)
1023n/a{
1024n/a PyErr_SyntaxLocationEx(filename, lineno, -1);
1025n/a}
1026n/a
1027n/a
1028n/a/* Set file and line information for the current exception.
1029n/a If the exception is not a SyntaxError, also sets additional attributes
1030n/a to make printing of exceptions believe it is a syntax error. */
1031n/a
1032n/avoid
1033n/aPyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
1034n/a{
1035n/a PyObject *exc, *v, *tb, *tmp;
1036n/a _Py_IDENTIFIER(filename);
1037n/a _Py_IDENTIFIER(lineno);
1038n/a _Py_IDENTIFIER(msg);
1039n/a _Py_IDENTIFIER(offset);
1040n/a _Py_IDENTIFIER(print_file_and_line);
1041n/a _Py_IDENTIFIER(text);
1042n/a
1043n/a /* add attributes for the line number and filename for the error */
1044n/a PyErr_Fetch(&exc, &v, &tb);
1045n/a PyErr_NormalizeException(&exc, &v, &tb);
1046n/a /* XXX check that it is, indeed, a syntax error. It might not
1047n/a * be, though. */
1048n/a tmp = PyLong_FromLong(lineno);
1049n/a if (tmp == NULL)
1050n/a PyErr_Clear();
1051n/a else {
1052n/a if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
1053n/a PyErr_Clear();
1054n/a Py_DECREF(tmp);
1055n/a }
1056n/a tmp = NULL;
1057n/a if (col_offset >= 0) {
1058n/a tmp = PyLong_FromLong(col_offset);
1059n/a if (tmp == NULL)
1060n/a PyErr_Clear();
1061n/a }
1062n/a if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1063n/a PyErr_Clear();
1064n/a Py_XDECREF(tmp);
1065n/a if (filename != NULL) {
1066n/a if (_PyObject_SetAttrId(v, &PyId_filename, filename))
1067n/a PyErr_Clear();
1068n/a
1069n/a tmp = PyErr_ProgramTextObject(filename, lineno);
1070n/a if (tmp) {
1071n/a if (_PyObject_SetAttrId(v, &PyId_text, tmp))
1072n/a PyErr_Clear();
1073n/a Py_DECREF(tmp);
1074n/a }
1075n/a }
1076n/a if (exc != PyExc_SyntaxError) {
1077n/a if (!_PyObject_HasAttrId(v, &PyId_msg)) {
1078n/a tmp = PyObject_Str(v);
1079n/a if (tmp) {
1080n/a if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
1081n/a PyErr_Clear();
1082n/a Py_DECREF(tmp);
1083n/a } else {
1084n/a PyErr_Clear();
1085n/a }
1086n/a }
1087n/a if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1088n/a if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1089n/a Py_None))
1090n/a PyErr_Clear();
1091n/a }
1092n/a }
1093n/a PyErr_Restore(exc, v, tb);
1094n/a}
1095n/a
1096n/avoid
1097n/aPyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1098n/a{
1099n/a PyObject *fileobj;
1100n/a if (filename != NULL) {
1101n/a fileobj = PyUnicode_DecodeFSDefault(filename);
1102n/a if (fileobj == NULL)
1103n/a PyErr_Clear();
1104n/a }
1105n/a else
1106n/a fileobj = NULL;
1107n/a PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1108n/a Py_XDECREF(fileobj);
1109n/a}
1110n/a
1111n/a/* Attempt to load the line of text that the exception refers to. If it
1112n/a fails, it will return NULL but will not set an exception.
1113n/a
1114n/a XXX The functionality of this function is quite similar to the
1115n/a functionality in tb_displayline() in traceback.c. */
1116n/a
1117n/astatic PyObject *
1118n/aerr_programtext(FILE *fp, int lineno)
1119n/a{
1120n/a int i;
1121n/a char linebuf[1000];
1122n/a
1123n/a if (fp == NULL)
1124n/a return NULL;
1125n/a for (i = 0; i < lineno; i++) {
1126n/a char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1127n/a do {
1128n/a *pLastChar = '\0';
1129n/a if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1130n/a fp, NULL) == NULL)
1131n/a break;
1132n/a /* fgets read *something*; if it didn't get as
1133n/a far as pLastChar, it must have found a newline
1134n/a or hit the end of the file; if pLastChar is \n,
1135n/a it obviously found a newline; else we haven't
1136n/a yet seen a newline, so must continue */
1137n/a } while (*pLastChar != '\0' && *pLastChar != '\n');
1138n/a }
1139n/a fclose(fp);
1140n/a if (i == lineno) {
1141n/a PyObject *res;
1142n/a res = PyUnicode_FromString(linebuf);
1143n/a if (res == NULL)
1144n/a PyErr_Clear();
1145n/a return res;
1146n/a }
1147n/a return NULL;
1148n/a}
1149n/a
1150n/aPyObject *
1151n/aPyErr_ProgramText(const char *filename, int lineno)
1152n/a{
1153n/a FILE *fp;
1154n/a if (filename == NULL || *filename == '\0' || lineno <= 0)
1155n/a return NULL;
1156n/a fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
1157n/a return err_programtext(fp, lineno);
1158n/a}
1159n/a
1160n/aPyObject *
1161n/aPyErr_ProgramTextObject(PyObject *filename, int lineno)
1162n/a{
1163n/a FILE *fp;
1164n/a if (filename == NULL || lineno <= 0)
1165n/a return NULL;
1166n/a fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
1167n/a if (fp == NULL) {
1168n/a PyErr_Clear();
1169n/a return NULL;
1170n/a }
1171n/a return err_programtext(fp, lineno);
1172n/a}
1173n/a
1174n/a#ifdef __cplusplus
1175n/a}
1176n/a#endif