Debian Codegraph @

pypy/module/cpyext/pyerrors.py

raw symbols SCIP
1 import os
2 import signal as cpy_signal
3
4 from rpython.rtyper.lltypesystem import rffi, lltype
5 from rpython.rlib.objectmodel import we_are_translated
6 from pypy.interpreter.error import OperationError, oefmt, strerror as _strerror
7 from pypy.module.cpyext.api import cpython_api, CANNOT_FAIL, CONST_STRING
8 from pypy.module.cpyext.api import PyObjectFields, cpython_struct
9 from pypy.module.cpyext.api import bootstrap_function, slot_function
10 from pypy.module.cpyext.pyobject import make_typedescr
11 from pypy.module.exceptions.interp_exceptions import W_RuntimeWarning
12 from pypy.module.exceptions.interp_exceptions import W_StopIteration
13 from pypy.module.cpyext.pyobject import (
14 PyObject, PyObjectP, make_ref, from_ref, decref, get_w_obj_and_decref)
15 from pypy.module.cpyext.state import State
16 from pypy.module.cpyext.import_ import PyImport_Import
17 from rpython.rlib import rposix, jit
18 from rpython.rlib import rwin32
19 from rpython.rlib.rarithmetic import widen
20
21 PyStopIterationObjectStruct = lltype.ForwardReference()
22 PyStopIterationObject = lltype.Ptr(PyStopIterationObjectStruct)
23 PyStopIterationObjectFields = PyObjectFields + \
24 (("value", PyObject), )
25 cpython_struct("PyStopIterationObject", PyStopIterationObjectFields,
26 PyStopIterationObjectStruct)
27
28 @bootstrap_function
29 def init_stopiterationobject(space):
30 "Type description of PyStopIterationObject"
31 make_typedescr(W_StopIteration.typedef,
32 basestruct=PyStopIterationObject.TO,
33 attach=stopiteration_attach,
34 dealloc=stopiteration_dealloc)
35
36 def stopiteration_attach(space, py_obj, w_obj, w_userdata=None):
37 py_stopiteration = rffi.cast(PyStopIterationObject, py_obj)
38 assert isinstance(w_obj, W_StopIteration)
39 # note: assumes that w_value is read-only; changes on one side won't
40 # be reflected on the other side
41 py_stopiteration.c_value = make_ref(space, w_obj.w_value)
42
43 @slot_function([PyObject], lltype.Void)
44 def stopiteration_dealloc(space, py_obj):
45 py_stopiteration = rffi.cast(PyStopIterationObject, py_obj)
46 decref(space, py_stopiteration.c_value)
47 from pypy.module.cpyext.object import _dealloc
48 _dealloc(space, py_obj)
49
50
51 @cpython_api([PyObject, PyObject], lltype.Void)
52 def PyErr_SetObject(space, w_type, w_value):
53 """This function is similar to PyErr_SetString() but lets you specify an
54 arbitrary Python object for the "value" of the exception."""
55 pyerr_setobject(space, w_type, w_value)
56
57 def pyerr_setobject(space, w_type, w_value):
58 state = space.fromcache(State)
59 operr = OperationError(w_type, w_value)
60 operr.record_context(space, space.getexecutioncontext())
61 state.set_exception(operr)
62
63 @cpython_api([PyObject, CONST_STRING], lltype.Void)
64 def PyErr_SetString(space, w_type, message_ptr):
65 message = rffi.charp2str(message_ptr)
66 pyerr_setobject(space, w_type, space.newtext(message))
67
68 @cpython_api([PyObject], lltype.Void, error=CANNOT_FAIL)
69 def PyErr_SetNone(space, w_type):
70 """This is a shorthand for PyErr_SetObject(type, Py_None)."""
71 pyerr_setobject(space, w_type, space.w_None)
72
73 if os.name == 'nt':
74 # For some reason CPython returns a (PyObject*)NULL
75 # This confuses the annotator, so set result_is_ll
76 @cpython_api([rffi.INT_real], PyObject, error=CANNOT_FAIL, result_is_ll=True)
77 def PyErr_SetFromWindowsErr(space, err):
78 pyerr_setobject(space, space.w_OSError, space.newint(err))
79 return rffi.cast(PyObject, 0)
80
81 @cpython_api([rffi.INT_real, CONST_STRING], PyObject, error=CANNOT_FAIL, result_is_ll=True)
82 def PyErr_SetFromWindowsErrWithFilename(space, err, filename):
83 state = space.fromcache(State)
84 if filename:
85 filename = rffi.charp2str(filename)
86 try:
87 w_filename = space.fsdecode(space.newbytes(filename))
88 except:
89 w_filename = space.w_None
90 else:
91 w_filename = space.w_None
92 return pyerr_setexcfromwindows(space, space.w_WindowsError, err,
93 w_filename)
94
95 @cpython_api([PyObject, rffi.INT_real, PyObject], PyObject, error=CANNOT_FAIL, result_is_ll=True)
96 def PyErr_SetExcFromWindowsErrWithFilenameObject(space, w_exc, err, w_filename):
97 return pyerr_setexcfromwindows(space, w_exc, err, w_filename)
98
99 @cpython_api([PyObject, rffi.INT_real, PyObject, PyObject], PyObject, error=CANNOT_FAIL, result_is_ll=True)
100 def PyErr_SetExcFromWindowsErrWithFilenameObjects(space, w_exc, err, w_filename, w_filename2):
101 return pyerr_setexcfromwindows(space, w_exc, err, w_filename, w_filename2)
102
103 def pyerr_setexcfromwindows(space, w_exc, err, w_filename=None, w_filename2=None):
104 # Take from error._wrap_oserror2_impl
105 err = widen(err)
106 try:
107 msg, lgt = rwin32.FormatErrorW(err)
108 except ValueError:
109 msg = 'Windows Error %d' % err
110 lgt = len(msg)
111 w_msg = space.newtext(msg, lgt)
112 w_winerror = space.newint(err)
113 if not w_filename:
114 w_filename = space.w_None
115 if not w_filename2:
116 w_filename2 = space.w_None
117 w_error = space.call_function(w_exc, space.w_None, w_msg, w_filename,
118 w_winerror, w_filename2)
119 state = space.fromcache(State)
120 operr = OperationError(space.type(w_error), w_error)
121 operr.record_context(space, space.getexecutioncontext())
122 state.set_exception(operr)
123 return rffi.cast(PyObject, 0)
124
125 @cpython_api([], PyObject, result_borrowed=True)
126 def PyErr_Occurred(space):
127 state = space.fromcache(State)
128 operror = state.get_exception()
129 if operror is None:
130 return None
131 return operror.w_type # borrowed ref
132
133 @cpython_api([], lltype.Void)
134 def PyErr_Clear(space):
135 state = space.fromcache(State)
136 state.clear_exception()
137
138 @cpython_api([PyObjectP, PyObjectP, PyObjectP], lltype.Void)
139 def PyErr_Fetch(space, ptype, pvalue, ptraceback):
140 """Retrieve the error indicator into three variables whose addresses are passed.
141 If the error indicator is not set, set all three variables to NULL. If it is
142 set, it will be cleared and you own a reference to each object retrieved. The
143 value and traceback object may be NULL even when the type object is not.
144
145 This function is normally only used by code that needs to handle exceptions or
146 by code that needs to save and restore the error indicator temporarily."""
147 state = space.fromcache(State)
148 operror = state.clear_exception()
149 if operror:
150 ptype[0] = make_ref(space, operror.w_type)
151 pvalue[0] = make_ref(space, operror.get_w_value(space))
152 ptraceback[0] = make_ref(space, operror.get_w_traceback(space))
153 else:
154 ptype[0] = lltype.nullptr(PyObject.TO)
155 pvalue[0] = lltype.nullptr(PyObject.TO)
156 ptraceback[0] = lltype.nullptr(PyObject.TO)
157
158 @cpython_api([PyObject, PyObject, PyObject], lltype.Void)
159 def PyErr_Restore(space, py_type, py_value, py_traceback):
160 """Set the error indicator from the three objects. If the error indicator is
161 already set, it is cleared first. If the objects are NULL, the error
162 indicator is cleared. Do not pass a NULL type and non-NULL value or
163 traceback. The exception type should be a class. Do not pass an invalid
164 exception type or value. (Violating these rules will cause subtle problems
165 later.) This call takes away a reference to each object: you must own a
166 reference to each object before the call and after the call you no longer own
167 these references. (If you don't understand this, don't use this function. I
168 warned you.)
169
170 This function is normally only used by code that needs to save and restore the
171 error indicator temporarily; use PyErr_Fetch() to save the current
172 exception state."""
173 state = space.fromcache(State)
174 w_type = get_w_obj_and_decref(space, py_type)
175 w_value = get_w_obj_and_decref(space, py_value)
176 w_traceback = get_w_obj_and_decref(space, py_traceback)
177
178 if w_type is None:
179 state.clear_exception()
180 return
181 state.set_exception(OperationError(w_type, w_value, w_traceback))
182
183 @cpython_api([PyObjectP, PyObjectP, PyObjectP], lltype.Void)
184 def PyErr_NormalizeException(space, exc_p, val_p, tb_p):
185 """Under certain circumstances, the values returned by PyErr_Fetch() below
186 can be "unnormalized", meaning that *exc is a class object but *val is
187 not an instance of the same class. This function can be used to instantiate
188 the class in that case. If the values are already normalized, nothing happens.
189 The delayed normalization is implemented to improve performance."""
190 if exc_p[0]:
191 w_etype = from_ref(space, exc_p[0])
192 else:
193 # There is no exception, so nothing to do
194 return
195 if val_p[0]:
196 w_evalue = from_ref(space, val_p[0])
197 else:
198 # On CPython, PyErr_SetNone actually sets val to NULL.
199 # Sensible code should probably never trigger this path on PyPy, but...
200 w_evalue = space.w_None
201 operr = OperationError(w_etype, w_evalue)
202 w_value = operr.normalize_exception(space)
203 decref(space, exc_p[0])
204 decref(space, val_p[0])
205 exc_p[0] = make_ref(space, operr.w_type)
206 val_p[0] = make_ref(space, w_value)
207
208 @cpython_api([], rffi.INT_real, error=0)
209 def PyErr_BadArgument(space):
210 """This is a shorthand for PyErr_SetString(PyExc_TypeError, message), where
211 message indicates that a built-in operation was invoked with an illegal
212 argument. It is mostly for internal use. In CPython this function always
213 raises an exception and returns 0 in all cases, hence the (ab)use of the
214 error indicator."""
215 raise oefmt(space.w_TypeError, "bad argument type for built-in operation")
216
217 @cpython_api([], lltype.Void, error=None)
218 def PyErr_BadInternalCall(space):
219 raise oefmt(space.w_SystemError, "Bad internal call!")
220
221 @cpython_api([], PyObject, error=CANNOT_FAIL)
222 def PyErr_NoMemory(space):
223 """This is a shorthand for PyErr_SetNone(PyExc_MemoryError); it returns NULL
224 so an object allocation function can write return PyErr_NoMemory(); when it
225 runs out of memory.
226 Return value: always NULL."""
227 return PyErr_SetNone(space, space.w_MemoryError)
228 # use pre-allocated exception since there is no memory
229 state = space.fromcache(State)
230 static_operr = state.static_memory_error
231 static_operr.record_context(space, space.getexecutioncontext())
232 state.set_exception(static_operr)
233 return rffi.cast(PyObject, 0)
234
235 @cpython_api([PyObject], PyObject)
236 def PyErr_SetFromErrno(space, w_type):
237 """
238 This is a convenience function to raise an exception when a C library function
239 has returned an error and set the C variable errno. It constructs a
240 tuple object whose first item is the integer errno value and whose
241 second item is the corresponding error message (gotten from strerror()),
242 and then calls PyErr_SetObject(type, object). On Unix, when the
243 errno value is EINTR, indicating an interrupted system call,
244 this calls PyErr_CheckSignals(), and if that set the error indicator,
245 leaves it set to that. The function always returns NULL, so a wrapper
246 function around a system call can write return PyErr_SetFromErrno(type);
247 when the system call returns an error.
248 Return value: always NULL."""
249 PyErr_SetFromErrnoWithFilename(space, w_type,
250 lltype.nullptr(rffi.CCHARP.TO))
251
252 @cpython_api([PyObject, CONST_STRING], PyObject)
253 def PyErr_SetFromErrnoWithFilename(space, w_type, llfilename):
254 """Similar to PyErr_SetFromErrno(), with the additional behavior that if
255 filename is not NULL, it is passed to the constructor of type as a third
256 parameter. In the case of exceptions such as IOError and OSError,
257 this is used to define the filename attribute of the exception instance.
258 Return value: always NULL."""
259 # XXX Doesn't actually do anything with PyErr_CheckSignals.
260 if llfilename:
261 filename = rffi.charp2str(llfilename)
262 w_filename = space.newfilename(filename)
263 else:
264 w_filename = space.w_None
265
266 PyErr_SetFromErrnoWithFilenameObject(space, w_type, w_filename)
267
268 @cpython_api([PyObject, PyObject], PyObject)
269 @jit.dont_look_inside # direct use of _get_errno()
270 def PyErr_SetFromErrnoWithFilenameObject(space, w_type, w_value):
271 """Similar to PyErr_SetFromErrno(), with the additional behavior that if
272 w_value is not NULL, it is passed to the constructor of type as a
273 third parameter. In the case of exceptions such as IOError and OSError,
274 this is used to define the filename attribute of the exception instance.
275 Return value: always NULL."""
276 # XXX Doesn't actually do anything with PyErr_CheckSignals.
277 errno = rffi.cast(lltype.Signed, rposix._get_errno())
278 msg, lgt = _strerror(errno)
279 if w_value:
280 if we_are_translated():
281 w_error = space.call_function(w_type,
282 space.newint(errno),
283 space.newtext(msg, lgt),
284 w_value)
285 else:
286 # Untranslated: errno may be reset by bridge overhead before
287 # _get_errno() runs, mapping OSError to BlockingIOError. An
288 # integer w_value would then be stored as characters_written
289 # instead of filename. Avoid that by setting filename directly.
290 w_error = space.call_function(w_type,
291 space.newint(errno),
292 space.newtext(msg, lgt))
293 space.setattr(w_error, space.newtext('filename'), w_value)
294 else:
295 w_error = space.call_function(w_type,
296 space.newint(errno),
297 space.newtext(msg, lgt))
298 raise OperationError(w_type, w_error)
299
300 @cpython_api([PyObject, PyObject, PyObject], PyObject)
301 @jit.dont_look_inside # direct use of _get_errno()
302 def PyErr_SetFromErrnoWithFilenameObjects(space, w_type, w_value, w_value2):
303 """Similar to PyErr_SetFromErrnoWithFilenameObject(), with the additional
304 behavior that it can take 2 filenames, for failures in rename(), symlink()
305 or copy().
306 Return value: always NULL."""
307 # XXX Doesn't actually do anything with PyErr_CheckSignals.
308 errno = rffi.cast(lltype.Signed, rposix._get_errno())
309 msg, lgt = _strerror(errno)
310 if w_value:
311 if w_value2:
312 w_error = space.call_function(w_type,
313 space.newint(errno),
314 space.newtext(msg, lgt),
315 w_value, None, w_value2)
316 else:
317 w_error = space.call_function(w_type,
318 space.newint(errno),
319 space.newtext(msg, lgt),
320 w_value)
321 else:
322 w_error = space.call_function(w_type,
323 space.newint(errno),
324 space.newtext(msg, lgt))
325 raise OperationError(w_type, w_error)
326
327 @cpython_api([], rffi.INT_real, error=-1)
328 def PyErr_CheckSignals(space):
329 """
330 This function interacts with Python's signal handling. It checks whether a
331 signal has been sent to the processes and if so, invokes the corresponding
332 signal handler. If the signal module is supported, this can invoke a
333 signal handler written in Python. In all cases, the default effect for
334 SIGINT is to raise the KeyboardInterrupt exception. If an
335 exception is raised the error indicator is set and the function returns -1;
336 otherwise the function returns 0. The error indicator may or may not be
337 cleared if it was previously set."""
338 # XXX implement me
339 return 0
340
341 @cpython_api([PyObject, PyObject], rffi.INT_real, error=CANNOT_FAIL)
342 def PyErr_GivenExceptionMatches(space, w_given, w_exc):
343 """Return true if the given exception matches the exception in exc. If
344 exc is a class object, this also returns true when given is an instance
345 of a subclass. If exc is a tuple, all exceptions in the tuple (and
346 recursively in subtuples) are searched for a match."""
347 if space.isinstance_w(w_given, space.w_BaseException):
348 w_given_type = space.type(w_given)
349 else:
350 w_given_type = w_given
351 try:
352 return space.exception_match(w_given_type, w_exc)
353 except:
354 return 0
355
356 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
357 def PyErr_ExceptionMatches(space, w_exc):
358 """Equivalent to PyErr_GivenExceptionMatches(PyErr_Occurred(), exc). This
359 should only be called when an exception is actually set; a memory access
360 violation will occur if no exception has been raised."""
361 w_type = PyErr_Occurred(space)
362 return PyErr_GivenExceptionMatches(space, w_type, w_exc)
363
364
365 @cpython_api([PyObject, CONST_STRING, rffi.INT_real], rffi.INT_real, error=-1)
366 def PyErr_WarnEx(space, w_category, message_ptr, stacklevel):
367 """Issue a warning message. The category argument is a warning category (see
368 below) or NULL; the message argument is a message string. stacklevel is a
369 positive number giving a number of stack frames; the warning will be issued from
370 the currently executing line of code in that stack frame. A stacklevel of 1
371 is the function calling PyErr_WarnEx(), 2 is the function above that,
372 and so forth.
373
374 This function normally prints a warning message to sys.stderr; however, it is
375 also possible that the user has specified that warnings are to be turned into
376 errors, and in that case this will raise an exception. It is also possible that
377 the function raises an exception because of a problem with the warning machinery
378 (the implementation imports the warnings module to do the heavy lifting).
379 The return value is 0 if no exception is raised, or -1 if an exception
380 is raised. (It is not possible to determine whether a warning message is
381 actually printed, nor what the reason is for the exception; this is
382 intentional.) If an exception is raised, the caller should do its normal
383 exception handling (for example, Py_DECREF() owned references and return
384 an error value).
385
386 Warning categories must be subclasses of Warning; the default warning
387 category is RuntimeWarning. The standard Python warning categories are
388 available as global variables whose names are PyExc_ followed by the Python
389 exception name. These have the type PyObject*; they are all class
390 objects. Their names are PyExc_Warning, PyExc_UserWarning,
391 PyExc_UnicodeWarning, PyExc_DeprecationWarning,
392 PyExc_SyntaxWarning, PyExc_RuntimeWarning, and
393 PyExc_FutureWarning. PyExc_Warning is a subclass of
394 PyExc_Exception; the other warning categories are subclasses of
395 PyExc_Warning.
396
397 For information about warning control, see the documentation for the
398 warnings module and the -W option in the command line
399 documentation. There is no C API for warning control."""
400 if w_category is None:
401 w_category = space.w_None
402 w_message = space.newtext(rffi.charp2str(message_ptr))
403 w_stacklevel = space.newint(rffi.cast(lltype.Signed, stacklevel))
404
405 w_module = PyImport_Import(space, space.newtext("warnings"))
406 w_warn = space.getattr(w_module, space.newtext("warn"))
407 space.call_function(w_warn, w_message, w_category, w_stacklevel)
408 return 0
409
410 @cpython_api([PyObject, CONST_STRING], rffi.INT_real, error=-1)
411 def PyErr_Warn(space, w_category, message):
412 """Issue a warning message. The category argument is a warning category (see
413 below) or NULL; the message argument is a message string. The warning will
414 appear to be issued from the function calling PyErr_Warn(), equivalent to
415 calling PyErr_WarnEx() with a stacklevel of 1.
416
417 Deprecated; use PyErr_WarnEx() instead."""
418 return PyErr_WarnEx(space, w_category, message, 1)
419
420 @cpython_api(
421 [PyObject, CONST_STRING, CONST_STRING, rffi.INT_real, CONST_STRING, PyObject],
422 rffi.INT_real, error=-1)
423 def PyErr_WarnExplicit(space, w_category, message, filename, lineno, module, w_registry):
424 """Issue a warning message with explicit control over all warning attributes. This
425 is a straightforward wrapper around the Python function
426 warnings.warn_explicit(), see there for more information. The module
427 and registry arguments may be set to NULL to get the default effect
428 described there. message and module are UTF-8 encoded strings,
429 filename is decoded from the filesystem encoding
430 (sys.getfilesystemencoding())."""
431 if w_category is None:
432 w_category = space.w_UserWarning
433 w_message = space.newtext(rffi.charp2str(message))
434 # XXX use fsencode
435 w_filename = space.newtext(rffi.charp2str(filename))
436 w_lineno = space.newint(rffi.cast(lltype.Signed, lineno))
437 if module:
438 w_module = space.newtext(rffi.charp2str(module))
439 else:
440 w_module = space.w_None
441 if w_registry is None:
442 w_registry = space.w_None
443 w_warnings = PyImport_Import(space, space.newtext("warnings"))
444 w_warn = space.getattr(w_warnings, space.newtext("warn_explicit"))
445 space.call_function(w_warn, w_message, w_category, w_filename, w_lineno,
446 w_module, w_registry)
447 return 0
448
449
450 @cpython_api([rffi.INT_real], lltype.Void)
451 def PyErr_PrintEx(space, set_sys_last_vars):
452 """Print a standard traceback to sys.stderr and clear the error indicator.
453 Call this function only when the error indicator is set. (Otherwise it will
454 cause a fatal error!)
455
456 If set_sys_last_vars is nonzero, the variables sys.last_type,
457 sys.last_value and sys.last_traceback will be set to the
458 type, value and traceback of the printed exception, respectively."""
459 if not PyErr_Occurred(space):
460 PyErr_BadInternalCall(space)
461
462 operror = space.fromcache(State).clear_exception()
463 w_value = operror.normalize_exception(space)
464 w_type = operror.w_type
465 w_tb = operror.get_w_traceback(space)
466
467 if rffi.cast(lltype.Signed, set_sys_last_vars):
468 space.sys.setdictvalue(space, "last_type", w_type)
469 space.sys.setdictvalue(space, "last_value", w_value)
470 space.sys.setdictvalue(space, "last_traceback", w_tb)
471
472 space.call_function(space.sys.get("excepthook"),
473 w_type, w_value, w_tb)
474
475 @cpython_api([], lltype.Void)
476 def PyErr_Print(space):
477 """Alias for PyErr_PrintEx(1)."""
478 PyErr_PrintEx(space, 1)
479
480 @cpython_api([PyObject, PyObject, PyObject], lltype.Void)
481 def PyErr_Display(space, w_type, w_value, tb):
482 if tb:
483 w_tb = from_ref(space, tb)
484 else:
485 w_tb = space.w_None
486 try:
487 space.call_function(space.sys.get("excepthook"),
488 w_type, w_value, w_tb)
489 except OperationError:
490 # Like CPython: This is wrong, but too many callers rely on
491 # this behavior.
492 pass
493
494 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
495 def PyTraceBack_Print(space, w_tb, w_file):
496 space.call_method(w_file, "write", space.newtext(
497 'Traceback (most recent call last):\n'))
498 w_traceback = space.call_method(space.builtin, '__import__',
499 space.newtext("traceback"))
500 space.call_method(w_traceback, "print_tb", w_tb, space.w_None, w_file)
501 return 0
502
503 @cpython_api([PyObject], lltype.Void)
504 def PyErr_WriteUnraisable(space, where):
505 """This utility function prints a warning message to sys.stderr when an
506 exception has been set but it is impossible for the interpreter to actually
507 raise the exception. It is used, for example, when an exception occurs in
508 an __del__() method.
509
510 The function is called with a single argument obj that identifies the
511 context in which the unraisable exception occurred. The repr of obj will be
512 printed in the warning message."""
513
514 if not where:
515 where = ''
516 else:
517 where = space.text_w(space.repr(from_ref(space, where)))
518 state = space.fromcache(State)
519 operror = state.clear_exception()
520 if operror:
521 operror.write_unraisable(space, where)
522
523 @cpython_api([CONST_STRING, PyObject], lltype.Void)
524 def _PyErr_WriteUnraisableMsg(space, where, w_obj):
525 """This utility function prints a warning message to sys.stderr when an
526 exception has been set but it is impossible for the interpreter to actually
527 raise the exception. It is used, for example, when an exception occurs in
528 an __del__() method.
529
530 The function is called with a single argument obj that identifies the
531 context in which the unraisable exception occurred. The repr of obj will be
532 printed in the warning message."""
533
534 if not where:
535 where = ''
536 else:
537 where = rffi.charp2str(where)
538 state = space.fromcache(State)
539 operror = state.clear_exception()
540 if operror:
541 operror.write_unraisable(space, where, w_object=w_obj, with_traceback=True)
542
543 @cpython_api([PyObjectP, PyObjectP, PyObjectP], lltype.Void)
544 def PyErr_GetExcInfo(space, ptype, pvalue, ptraceback):
545 """
546 Retrieve the exception info, as known from ``sys.exc_info()``. This
547 refers to an exception that was already caught, not to an exception
548 that was freshly raised. Returns new references for the three
549 objects, any of which may be *NULL*. Does not modify the exception
550 info state.
551
552 .. note::
553
554 This function is not normally used by code that wants to handle
555 exceptions. Rather, it can be used when code needs to save and
556 restore the exception state temporarily. Use
557 :c:func:`PyErr_SetExcInfo` to restore or clear the exception
558 state.
559 """
560 ec = space.getexecutioncontext()
561 operror = ec.sys_exc_info()
562 if operror:
563 ptype[0] = make_ref(space, operror.w_type)
564 pvalue[0] = make_ref(space, operror.get_w_value(space))
565 ptraceback[0] = make_ref(space, operror.get_w_traceback(space))
566 else:
567 ptype[0] = lltype.nullptr(PyObject.TO)
568 pvalue[0] = lltype.nullptr(PyObject.TO)
569 ptraceback[0] = lltype.nullptr(PyObject.TO)
570
571 @cpython_api([PyObject, PyObject, PyObject], lltype.Void)
572 def PyErr_SetExcInfo(space, py_type, py_value, py_traceback):
573 """
574 Set the exception info, as known from ``sys.exc_info()``. This refers
575 to an exception that was already caught, not to an exception that was
576 freshly raised. This function steals the references of the arguments.
577 To clear the exception state, pass *NULL* for all three arguments.
578 For general rules about the three arguments, see :c:func:`PyErr_Restore`.
579
580 .. note::
581
582 This function is not normally used by code that wants to handle
583 exceptions. Rather, it can be used when code needs to save and
584 restore the exception state temporarily. Use
585 :c:func:`PyErr_GetExcInfo` to read the exception state.
586 """
587 w_type = get_w_obj_and_decref(space, py_type)
588 w_value = get_w_obj_and_decref(space, py_value)
589 w_traceback = get_w_obj_and_decref(space, py_traceback)
590 #
591 ec = space.getexecutioncontext()
592 ec.set_sys_exc_info3(w_value)
593
594 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
595 def PyOS_InterruptOccurred(space):
596 return 0;
597
598 @cpython_api([PyObject], lltype.Void)
599 def PyErr_SetHandledException(space, exc):
600 if exc:
601 w_exc = from_ref(space, exc)
602 else:
603 w_exc = space.w_None
604 ec = space.getexecutioncontext()
605 ec.set_sys_exc_info3(w_exc)
606
607
608 @cpython_api([], PyObject)
609 def PyErr_GetHandledException(space):
610 ec = space.getexecutioncontext()
611 operror = ec.sys_exc_info()
612 if not operror:
613 return space.w_None
614 return operror.normalize_exception(space)