Debian Codegraph @

pypy/interpreter/error.py

raw symbols SCIP
1 import cStringIO
2 import itertools
3 import os
4 import sys
5 import traceback
6 from errno import EINTR
7
8 from rpython.rlib import jit
9 from rpython.rlib.objectmodel import we_are_translated, specialize
10 from rpython.rlib.objectmodel import dont_inline, not_rpython
11 from rpython.rlib import rstack, rstackovf
12 from rpython.rlib import rwin32, rutf8
13
14 from pypy.interpreter import debug
15
16
17 AUTO_DEBUG = os.getenv('PYPY_DEBUG')
18 RECORD_INTERPLEVEL_TRACEBACK = True
19
20 def strerror(errno):
21 """Translate an error code to a unicode message string."""
22 from pypy.module._codecs.locale import str_decode_locale_surrogateescape
23 utf8, lgt = str_decode_locale_surrogateescape(os.strerror(errno))
24 return utf8, lgt
25
26 class OperationError(Exception):
27 """Interpreter-level exception that signals an exception that should be
28 sent to the application level.
29
30 OperationError instances have three attributes (and no .args),
31 w_type, _w_value and _application_traceback, which contain the wrapped
32 type and value describing the exception, and a chained list of
33 PyTraceback objects making the application-level traceback.
34 """
35
36 _w_value = None
37 _application_traceback = None
38 _context_recorded = False
39
40 def __init__(self, w_type, w_value, tb=None):
41 self.setup(w_type, w_value)
42 self._application_traceback = tb
43
44 def setup(self, w_type, w_value=None):
45 assert w_type is not None
46 self.w_type = w_type
47 self._w_value = w_value
48 if not we_are_translated():
49 self.debug_excs = []
50
51 def clear(self, space):
52 # XXX remove this method. The point is that we cannot always
53 # hack at 'self' to clear w_type and _w_value, because in some
54 # corner cases the OperationError will be used again: see
55 # test_interpreter.py:test_with_statement_and_sys_clear.
56 pass
57
58 def match(self, space, w_check_class):
59 "Check if this application-level exception matches 'w_check_class'."
60 return space.exception_match(self.w_type, w_check_class)
61
62 def async(self, space):
63 "Check if this is an exception that should better not be caught."
64 return (self.match(space, space.w_SystemExit) or
65 self.match(space, space.w_KeyboardInterrupt))
66 # note: an extra case is added in OpErrFmtNoArgs
67
68 @not_rpython
69 def __str__(self):
70 "Convenience for tracebacks."
71 s = self._w_value
72 space = getattr(self.w_type, 'space', None)
73 if space is not None:
74 if self.__class__ is not OperationError and s is None:
75 s, lgt = self._compute_value(space)
76 try:
77 s = space.text_w(s)
78 except Exception:
79 pass
80 return '[%s: %s]' % (self.w_type, s)
81
82 def __repr__(self):
83 "NOT_RPYTHON"
84 return 'OperationError(%s)' % (self.w_type)
85
86 def errorstr(self, space, use_repr=False):
87 "The exception class and value, as a string."
88 if not use_repr: # see write_unraisable()
89 w_value = self.normalize_exception(space)
90 else:
91 w_value = self.get_w_value(space)
92 if space is None:
93 # this part NOT_RPYTHON
94 exc_typename = str(self.w_type)
95 exc_value = str(w_value)
96 else:
97 exc_typename = space.text_w(
98 space.getattr(self.w_type, space.newtext('__name__')))
99 if space.is_w(w_value, space.w_None):
100 exc_value = ""
101 else:
102 try:
103 if use_repr:
104 exc_value = space.text_w(space.repr(w_value))
105 else:
106 exc_value = space.text_w(space.str(w_value))
107 except OperationError:
108 # oups, cannot __str__ the exception object
109 exc_value = ("<exception %s() failed>" %
110 ("repr" if use_repr else "str"))
111 if not exc_value:
112 return exc_typename
113 else:
114 return '%s: %s' % (exc_typename, exc_value)
115
116 def record_interpreter_traceback(self):
117 """Records the current traceback inside the interpreter.
118 This traceback is only useful to debug the interpreter, not the
119 application."""
120 if not we_are_translated():
121 if RECORD_INTERPLEVEL_TRACEBACK:
122 self.debug_excs.append(sys.exc_info())
123
124 @not_rpython
125 def print_application_traceback(self, space, file=None):
126 "Dump a standard application-level traceback."
127 if file is None:
128 file = sys.stderr
129 self.print_app_tb_only(file)
130 print >> file, self.errorstr(space)
131
132 @not_rpython
133 def print_app_tb_only(self, file):
134 tb = self._application_traceback
135 if tb:
136 import linecache
137 print >> file, "Traceback (application-level):"
138 while tb is not None:
139 co = tb.frame.pycode
140 lineno = tb.get_lineno()
141 fname = co.co_filename
142 if fname.startswith('<inline>\n'):
143 lines = fname.split('\n')
144 fname = lines[0].strip()
145 try:
146 l = lines[lineno]
147 except IndexError:
148 l = ''
149 else:
150 l = linecache.getline(fname, lineno)
151 print >> file, " File \"%s\"," % fname,
152 print >> file, "line", lineno, "in", co.co_name
153 if l:
154 if l.endswith('\n'):
155 l = l[:-1]
156 l = " " + l.lstrip()
157 print >> file, l
158 tb = tb.next
159
160 @not_rpython
161 def print_detailed_traceback(self, space=None, file=None):
162 """Dump a nice detailed interpreter- and
163 application-level traceback, useful to debug the interpreter."""
164 if file is None:
165 file = sys.stderr
166 f = cStringIO.StringIO()
167 for i in range(len(self.debug_excs)-1, -1, -1):
168 print >> f, "Traceback (interpreter-level):"
169 traceback.print_tb(self.debug_excs[i][2], file=f)
170 f.seek(0)
171 debug_print(''.join(['|| ' + line for line in f.readlines()]), file)
172 if self.debug_excs:
173 from pypy.tool import tb_server
174 tb_server.publish_exc(self.debug_excs[-1])
175 self.print_app_tb_only(file)
176 print >> file, '(application-level)', self.errorstr(space)
177 if AUTO_DEBUG:
178 debug.fire(self)
179
180 @jit.unroll_safe
181 def normalize_exception(self, space):
182 """Normalize the OperationError. In other words, fix w_type and/or
183 w_value to make sure that the __class__ of w_value is exactly w_type.
184 """
185 #
186 # This method covers all ways in which the Python statement
187 # "raise X, Y" can produce a valid exception type and instance.
188 #
189 # In the following table, 'Class' means a subclass of BaseException
190 # and 'inst' is an instance of either 'Class' or a subclass of it.
191 #
192 # The flow object space only deals with non-advanced case.
193 #
194 # input (w_type, w_value)... becomes... advanced case?
195 # ---------------------------------------------------------------------
196 # (Class, None) (Class, Class()) no
197 # (Class, inst) (inst.__class__, inst) no
198 # (Class, tuple) (Class, Class(*tuple)) yes
199 # (Class, x) (Class, Class(x)) no
200 # (inst, None) (inst.__class__, inst) no
201 #
202 w_type = self.w_type
203 w_value = self.get_w_value(space)
204
205 if space.exception_is_valid_obj_as_class_w(w_type):
206 # this is for all cases of the form (Class, something)
207 if space.is_w(w_value, space.w_None):
208 # raise Type: we assume we have to instantiate Type
209 w_value = space.call_function(w_type)
210 if not space.isinstance_w(w_value, space.w_BaseException):
211 raise oefmt(space.w_TypeError,
212 "calling %T should have returned an instance of "
213 "BaseException, not %T", w_type, w_value)
214 w_type = self._exception_getclass(space, w_value)
215 else:
216 w_valuetype = space.exception_getclass(w_value)
217 if space.abstract_issubclass_w(w_valuetype, w_type, allow_override=True):
218 # raise Type, Instance: let etype be the exact type of value
219 w_type = w_valuetype
220 else:
221 if space.isinstance_w(w_value, space.w_tuple):
222 # raise Type, tuple: assume the tuple contains the
223 # constructor args
224 w_value = space.call(w_type, w_value)
225 else:
226 # raise Type, X: assume X is the constructor argument
227 w_value = space.call_function(w_type, w_value)
228 w_type = self._exception_getclass(space, w_value)
229 if self._application_traceback:
230 from pypy.interpreter.pytraceback import PyTraceback
231 from pypy.module.exceptions.interp_exceptions import W_BaseException
232 tb = self._application_traceback
233 if (isinstance(w_value, W_BaseException) and
234 isinstance(tb, PyTraceback)):
235 # traceback hasn't escaped yet
236 w_value.w_traceback = tb
237 else:
238 # traceback has escaped
239 space.setattr(w_value, space.newtext("__traceback__"),
240 self.get_w_traceback(space))
241 else:
242 # the only case left here is (inst, None), from a 'raise inst'.
243 w_inst = w_type
244 w_instclass = self._exception_getclass(space, w_inst)
245 if not space.is_w(w_value, space.w_None):
246 raise oefmt(space.w_TypeError,
247 "instance exception may not have a separate value")
248 w_value = w_inst
249 w_type = w_instclass
250
251 self.w_type = w_type
252 self._w_value = w_value
253 return w_value
254
255 def _exception_getclass(self, space, w_inst, what="exceptions"):
256 w_type = space.exception_getclass(w_inst)
257 if not space.exception_is_valid_class_w(w_type):
258 raise oefmt(space.w_TypeError,
259 "%s must derive from BaseException, not %N",
260 what, w_type)
261 return w_type
262
263 def write_unraisable(self, space, where, w_object=None,
264 with_traceback=False, extra_line=''):
265 from pypy.module.sys.vm import app_hookargs
266 try:
267 w_value = self.normalize_exception(space)
268 except OperationError:
269 w_value = self.get_w_value(space)
270 w_type = self.w_type
271 w_tb = self.get_w_traceback(space)
272 if w_object is None:
273 w_object = space.w_None
274
275 if where:
276 # Note: since Python 3.5, unraisable exceptions are always
277 # printed with a traceback. Setting 'with_traceback=True'
278 # only asks for a different format in _PyErr_WriteUnraisableMsg and
279 # _cffi_backend.ccallback's Handle_applevel_exception
280 if with_traceback:
281 first_line = 'Exception ignored %s' % (where, )
282 else:
283 first_line = 'Exception ignored in: %s' % (where, )
284 else:
285 first_line = ''
286 info_w = [
287 self.w_type,
288 w_value,
289 w_tb,
290 space.newtext(first_line),
291 w_object,
292 space.newtext(extra_line),
293 ]
294 w_hook_class = app_hookargs.wget(space, "UnraisableHookArgs")
295 try:
296 w_hook_args = space.call_function(w_hook_class, space.newtuple(info_w))
297
298 w_hook = space.sys.getdictvalue(space, "unraisablehook")
299 except OperationError as e:
300 first_line = "Exception ignored on building sys.unraisablehook arguments"
301 else:
302 if not space.is_none(w_hook):
303 try:
304 space.audit("sys.unraisablehook", [w_hook, w_hook_args])
305 space.call_function(w_hook, w_hook_args)
306 return
307 except OperationError as e:
308 first_line = "Exception ignored in sys.unraisablehook"
309 w_object = w_hook
310 w_type = e.w_type
311 w_value = e.get_w_value(space)
312 w_tb = e.get_w_traceback(space)
313
314 self.write_unraisable_default(space, w_type, w_value, w_tb, first_line, w_object,
315 extra_line)
316
317 @staticmethod
318 def write_unraisable_default(space, w_type, w_value, w_tb, first_line, w_object,
319 extra_line):
320 if not first_line:
321 first_line = "Exception ignored in:"
322 if w_object is None or w_object is space.w_None:
323 first_line = "%s" % (first_line,)
324 else:
325 try:
326 objrepr = space.text_w(space.repr(w_object))
327 except OperationError:
328 objrepr = "<object repr() failed>"
329 first_line = "%s %s" % (first_line, objrepr)
330 if not extra_line:
331 extra_line = '\n'
332 else:
333 extra_line += ':\n'
334 try:
335 space.appexec([space.newtext(first_line),
336 space.newtext(extra_line),
337 w_type, w_value, w_tb],
338 """(first_line, extra_line, t, v, tb):
339 import sys
340 sys.stderr.write(first_line)
341 if extra_line:
342 sys.stderr.write(extra_line)
343 import traceback
344 traceback.print_exception(t, v, tb)
345 """)
346 except OperationError:
347 pass # ignored
348
349 def get_w_value(self, space):
350 w_value = self._w_value
351 if w_value is None:
352 value, lgt = self._compute_value(space)
353 self._w_value = w_value = space.newtext(value, lgt)
354 return w_value
355
356 def _compute_value(self, space):
357 raise NotImplementedError
358
359 def get_traceback(self):
360 """Calling this marks the PyTraceback as escaped, i.e. it becomes
361 accessible and inspectable by app-level Python code. For the JIT.
362 Note that this has no effect if there are already several traceback
363 frames recorded, because in this case they are already marked as
364 escaping by executioncontext.leave() being called with
365 got_exception=True.
366 """
367 from pypy.interpreter.pytraceback import PyTraceback
368 tb = self._application_traceback
369 if tb is not None and isinstance(tb, PyTraceback):
370 tb.frame.mark_as_escaped()
371 return tb
372
373 def has_any_traceback(self):
374 return self._application_traceback is not None
375
376 def set_cause(self, space, w_cause):
377 if w_cause is None:
378 return
379 # ensure w_cause is of a valid type
380 if space.is_none(w_cause):
381 pass
382 else:
383 self._exception_getclass(space, w_cause, "exception causes")
384 w_value = self.get_w_value(space)
385 space.setattr(w_value, space.newtext("__cause__"), w_cause)
386
387 def get_w_traceback(self, space):
388 """Return a traceback or w_None. """
389 tb = self.get_traceback()
390 if tb is None:
391 return space.w_None
392 return tb
393
394 def got_any_traceback(self):
395 return self._application_traceback is not None
396
397 def set_traceback(self, traceback):
398 """Set the current traceback."""
399 self._application_traceback = traceback
400
401 def remove_traceback_module_frames(self, *module_names):
402 from pypy.interpreter.pytraceback import PyTraceback
403 tb = self._application_traceback
404 while tb is not None and isinstance(tb, PyTraceback):
405 if tb.frame.pycode.co_filename not in module_names:
406 break
407 tb = tb.next
408 self._application_traceback = tb
409
410 def record_context(self, space, ec):
411 """Record a __context__ for this exception if one exists.
412 """
413 if self._context_recorded:
414 return
415 last = ec.sys_exc_info()
416 try:
417 if last is not None:
418 self.chain_exceptions(space, last)
419 finally:
420 self._context_recorded = True
421
422 def chain_exceptions(self, space, context):
423 """Attach another OperationError as __context__."""
424 from pypy.module.exceptions.interp_exceptions import W_BaseException
425 w_value = self.normalize_exception(space)
426 w_context = context.normalize_exception(space)
427 if not space.is_w(w_value, w_context):
428 if not isinstance(w_value, W_BaseException):
429 raise oefmt(space.w_SystemError, "not an instance of Exception: %T", w_value)
430 # Only set __context__ if not already set, matching CPython's
431 # behavior: a pre-existing __context__ is left unchanged.
432 if w_value.w_context is None:
433 _break_context_cycle(space, w_value, w_context)
434 w_value.descr_setcontext(space, w_context)
435
436 def chain_exceptions_from_cause(self, space, exception):
437 # XXX does this code really make sense?
438 self.chain_exceptions(space, exception)
439 self.set_cause(space, exception.get_w_value(space))
440 self.record_context(space, space.getexecutioncontext())
441
442 # A simplified version of _PyErr_TrySetFromCause, which returns a
443 # new exception of the same class, but with another error message.
444 # This only works for exceptions which have just a single message,
445 # and no other attribute.
446 # Otherwise the same OperationError is returned.
447 def try_set_from_cause(self, space, message):
448 from pypy.module.exceptions.interp_exceptions import W_BaseException
449 w_value = self.normalize_exception(space)
450 if not isinstance(w_value, W_BaseException):
451 return self
452 exc = w_value
453 # "args" should be empty or contain a single string
454 if len(exc.args_w) == 0:
455 pass
456 elif len(exc.args_w) == 1:
457 if not space.isinstance_w(exc.args_w[0], space.w_unicode):
458 return self
459 else:
460 return self
461 # No instance attribute.
462 if exc.w_dict and space.is_true(exc.w_dict):
463 return self
464 # Try to create the new exception.
465 try:
466 new_error = oefmt(space.type(w_value),
467 "%s (%T: %S)", message, w_value, w_value)
468 new_error.normalize_exception(space)
469 new_error.set_cause(space, w_value)
470 # Copy the traceback, but it does not escape.
471 new_error.set_traceback(self._application_traceback)
472 except OperationError:
473 # Return the original error
474 return self
475 return new_error
476
477
478 def _break_context_cycle(space, w_value, w_context):
479 """Don't create new context chain cycles, but be prepared to not hang on
480 existing ones.
481
482 This is O(chain length) but context chains are usually very short. Uses
483 Floyd's cycle algorithm.
484 """
485 from pypy.module.exceptions.interp_exceptions import W_BaseException
486 w_rabbit = w_context
487 w_tortoise = w_context
488 update_tortoise_toggle = False
489
490 while True:
491 if not isinstance(w_rabbit, W_BaseException):
492 raise oefmt(space.w_SystemError, "not an instance of Exception: %T", w_rabbit)
493 w_next = w_rabbit.descr_getcontext(space)
494 if space.is_none(w_next):
495 break
496 if space.is_w(w_next, w_value):
497 w_rabbit.descr_setcontext(space, space.w_None)
498 break
499 w_rabbit = w_next
500 if space.is_w(w_rabbit, w_tortoise):
501 # pre-excisting cycle, don't set anything to None
502 break
503 if update_tortoise_toggle:
504 # every other iteration
505 if not isinstance(w_tortoise, W_BaseException):
506 raise oefmt(space.w_SystemError, "not an instance of Exception: %T", w_tortoise)
507 w_tortoise = w_tortoise.descr_getcontext(space)
508 update_tortoise_toggle = not update_tortoise_toggle
509
510
511 class ClearedOpErr:
512 def __init__(self, space):
513 self.operr = OperationError(space.w_None, space.w_None)
514
515
516 # ____________________________________________________________
517 # optimization only: avoid the slowest operation -- the string
518 # formatting with '%' -- in the common case were we don't
519 # actually need the message. Only supports %s and %d.
520
521 _fmtcache = {}
522 _fmtcache2 = {}
523 _FMTS = tuple('8NRSTds')
524
525 def decompose_valuefmt(valuefmt):
526 """Returns a tuple of string parts extracted from valuefmt,
527 and a tuple of format characters."""
528 formats = []
529 parts = valuefmt.split('%')
530 i = 1
531 while i < len(parts):
532 if parts[i].startswith(_FMTS):
533 formats.append(parts[i][0])
534 parts[i] = parts[i][1:]
535 i += 1
536 elif parts[i] == '': # support for '%%'
537 parts[i-1] += '%' + parts[i+1]
538 del parts[i:i+2]
539 else:
540 fmts = '%%%s or %%%s' % (', %'.join(_FMTS[:-1]), _FMTS[-1])
541 raise ValueError("invalid format string (only %s supported)" %
542 fmts)
543 assert len(formats) > 0, "unsupported: no % command found"
544 return tuple(parts), tuple(formats)
545
546 def get_operrcls2(valuefmt):
547 strings, formats = decompose_valuefmt(valuefmt)
548 assert len(strings) == len(formats) + 1
549 try:
550 OpErrFmt = _fmtcache2[formats]
551 except KeyError:
552 from rpython.rlib.unroll import unrolling_iterable
553 attrs = ['x%d' % i for i in range(len(formats))]
554 entries = unrolling_iterable(zip(itertools.count(), formats, attrs))
555
556 class OpErrFmt(OperationError):
557 def __init__(self, w_type, strings, *args):
558 assert len(args) == len(strings) - 1
559 self.xstrings = strings
560 for i, _, attr in entries:
561 setattr(self, attr, args[i])
562 self.setup(w_type)
563
564 def _compute_value(self, space):
565 lst = [None] * (len(formats) + len(formats) + 1)
566 lgt = 0
567 for i, fmt, attr in entries:
568 lst[i + i] = self.xstrings[i]
569 lgt += len(self.xstrings[i])
570 value = getattr(self, attr)
571 if fmt == 'd':
572 result = str(value)
573 lgt += len(result)
574 elif fmt == 'R':
575 try:
576 w_s = space.repr(value)
577 result = space.utf8_w(w_s)
578 lgt += space.len_w(w_s)
579 except OperationError as e:
580 e.write_unraisable(space, "exception formatting: ", value)
581 result = '<repr raised>'
582 lgt += len(result)
583 elif fmt == 'S':
584 try:
585 s = space.str(value)
586 result = space.utf8_w(s)
587 lgt += space.len_w(s)
588 except OperationError as e:
589 e.write_unraisable(space, "exception formatting: ", value)
590 result = '<str raised>'
591 lgt += len(result)
592 elif fmt == 'T':
593 result = space.type(value).name
594 lgt += rutf8.codepoints_in_utf8(result)
595 elif fmt == 'N':
596 result = value.getname(space)
597 lgt += len(result)
598 elif fmt == '8':
599 # u'str\uxxxx' -> 'str\xXX\xXX' -> u"'str\xXX\xXX'"
600 from pypy.interpreter import unicodehelper as uh
601 decode_never_raise = uh.make_decode_never_raise(space)
602 w_value = space.newbytes(value)
603 result, _lgt, pos = uh.str_decode_utf8(
604 space, value, w_value, 'replace', True,
605 decode_never_raise, True)
606 lgt += _lgt
607 elif isinstance(value, unicode):
608 # 's'
609 result = str(value.encode('utf-8'))
610 lgt += len(value)
611 else:
612 result = str(value)
613 try:
614 lgt += rutf8.check_utf8(result, True)
615 except rutf8.CheckError as e:
616 lgt -= e.pos
617 lst[i + i + 1] = result
618 lst[-1] = self.xstrings[-1]
619 lgt += len(self.xstrings[-1])
620 retval = ''.join(lst)
621 return retval, lgt
622
623 _fmtcache2[formats] = OpErrFmt
624 return OpErrFmt, strings
625
626 class OpErrFmtNoArgs(OperationError):
627 def __init__(self, w_type, value):
628 self._value = value
629 self.setup(w_type)
630
631 def _compute_value(self, space):
632 return self._value, len(self._value)
633
634 def async(self, space):
635 # also matches a RuntimeError("maximum rec.") if the stack is
636 # still almost full, because in this case it might be a better
637 # idea to propagate the exception than eat it
638 if (self.w_type is space.w_RecursionError and
639 self._value == "maximum recursion depth exceeded" and
640 rstack.stack_almost_full()):
641 return True
642 return OperationError.async(self, space)
643
644 @specialize.memo()
645 def get_operr_class(valuefmt):
646 try:
647 result = _fmtcache[valuefmt]
648 except KeyError:
649 result = _fmtcache[valuefmt] = get_operrcls2(valuefmt)
650 return result
651
652 @specialize.arg(1)
653 def oefmt(w_type, valuefmt, *args):
654 """Equivalent to OperationError(w_type, space.newtext(valuefmt % args)).
655 More efficient in the (common) case where the value is not actually
656 needed. Note that in the py3k branch the exception message will
657 always be unicode.
658
659 Supports the standard %s and %d formats, plus the following:
660
661 %8 - The result of arg.decode('utf-8')
662 %N - The result of w_arg.getname(space)
663 %R - The result of space.utf8_w(space.repr(w_arg))
664 %S - The result of space.utf8_w(space.str(w_arg))
665 %T - The result of space.type(w_arg).name
666
667 """
668 if not len(args):
669 return OpErrFmtNoArgs(w_type, valuefmt)
670 OpErrFmt, strings = get_operr_class(valuefmt)
671 return OpErrFmt(w_type, strings, *args)
672
673
674 _fmtcache_withname_error2 = {}
675
676 def get_operr_withname_error_class2(valuefmt, errorclsname):
677 strings, formats = decompose_valuefmt(valuefmt)
678 try:
679 OpErrFmtWithNameError = _fmtcache_withname_error2[formats, errorclsname]
680 except KeyError:
681 basecls, _ = get_operr_class(valuefmt)
682 class OpErrFmtWithNameError(basecls):
683 def get_w_value(self, space):
684 from pypy.module.exceptions.interp_exceptions import W_AttributeError, W_NameError
685 w_value = self._w_value
686 if w_value is None:
687 value, lgt = self._compute_value(space)
688 # do the instantiation here, poking at the internals somewhat
689 w_msg = space.newtext(value, lgt)
690 if errorclsname == "AttributeError":
691 w_value = W_AttributeError(space)
692 w_value.descr_init(space, [w_msg], None, self.x0, self.x1)
693 else:
694 assert errorclsname == "NameError"
695 w_value = W_NameError(space)
696 w_value.descr_init(space, [w_msg], None, self.x0)
697 self._w_value = w_value
698 return w_value
699 _fmtcache_withname_error2[formats, errorclsname] = OpErrFmtWithNameError
700 return OpErrFmtWithNameError, strings
701
702
703 _fmtcache_withname_error = {}
704
705 @specialize.memo()
706 def get_operr_withname_error_class(valuefmt, errorclsname):
707 try:
708 return _fmtcache_withname_error[valuefmt, errorclsname]
709 except KeyError:
710 OpErrFmtWithNameError, strings = get_operr_withname_error_class2(valuefmt, errorclsname)
711 result = _fmtcache_withname_error[valuefmt, errorclsname] = OpErrFmtWithNameError, strings
712 return result
713
714
715 @specialize.arg(3)
716 def oefmt_attribute_error(space, w_obj, w_name, valuefmt, *args):
717 """ Like oefmt, but always raises w_AttributeError, passing w_obj and
718 w_name to its constructor. the valuefmt needs at least two fmt characters
719 for these two arguments. """
720
721 cls, strings = get_operr_withname_error_class(valuefmt, "AttributeError")
722 return cls(space.w_AttributeError, strings, *(w_obj, w_name) + args)
723
724
725 def enrich_attribute_error(space, operr, w_obj, w_name):
726 if not operr.match(space, space.w_AttributeError):
727 return
728 if type(operr) is not OperationError:
729 # operr is likely created with oefmt_attribute_error, and therefore an
730 # instance of one of the OpErrFmtWithNameError. We can ignore them,
731 # they already have the necessary attributes.
732 return
733 from pypy.module.exceptions.interp_exceptions import W_AttributeError
734 w_exc = operr.get_w_value(space)
735 if (isinstance(w_exc, W_AttributeError) and space.is_w(space.w_None, w_exc.w_name) and
736 space.is_w(space.w_None, w_exc.w_obj)):
737 w_exc.w_name = w_name
738 w_exc.w_obj = w_obj
739
740
741 @specialize.arg(3)
742 def oefmt_name_error(space, w_name, valuefmt, *args):
743 """ Like oefmt, but always raises w_NameError, passing w_name to its
744 constructor. the valuefmt needs at least one fmt characters for this
745 argument. """
746
747 cls, strings = get_operr_withname_error_class(valuefmt, "NameError")
748 return cls(space.w_NameError, strings, *(w_name, ) + args)
749 # ____________________________________________________________
750
751 # Utilities
752 from rpython.tool.ansi_print import ansi_print
753
754 def debug_print(text, file=None, newline=True):
755 # 31: ANSI color code "red"
756 ansi_print(text, esc="31", file=file, newline=newline)
757
758 @specialize.arg(3, 5)
759 def wrap_oserror2(space, e, w_filename=None, w_exception_class=None,
760 w_filename2=None, eintr_retry=False):
761 """A double API here:
762
763 * if eintr_retry is False, always return the OperationError to
764 be raised by the caller. It can possibly be about EINTR
765 (checksignals() is still called here).
766
767 * if eintr_retry is True (PEP 475 compliant API for retrying
768 system calls failing with EINTR), then this function raises
769 the OperationError directly, or for EINTR it calls
770 checksignals() and returns None in case the original
771 operation should be retried.
772 """
773 assert isinstance(e, OSError)
774
775 if w_exception_class is None:
776 w_exc = space.w_OSError
777 else:
778 w_exc = w_exception_class
779 operror = _wrap_oserror2_impl(space, e, w_filename, w_filename2, w_exc,
780 eintr_retry)
781 if eintr_retry:
782 assert operror is None # otherwise, _wrap_oserror2_impl() has raised
783 else:
784 assert operror is not None # tell the annotator we don't return None
785 return operror
786
787 @dont_inline
788 def _wrap_oserror2_impl(space, e, w_filename, w_filename2, w_exc, eintr_retry):
789 # move the common logic in its own function, instead of having it
790 # duplicated 4 times in all 4 specialized versions of wrap_oserror2()
791
792 if rwin32.WIN32 and isinstance(e, WindowsError):
793 winerror = e.winerror
794 try:
795 msg, lgt = rwin32.FormatErrorW(winerror)
796 except ValueError:
797 msg = 'Windows Error %d' % winerror
798 lgt = len(msg)
799 w_errno = space.w_None
800 w_winerror = space.newint(winerror)
801 w_msg = space.newtext(msg, lgt)
802 w_exc = space.w_WindowsError
803 else:
804 errno = e.errno
805 if errno == EINTR:
806 space.getexecutioncontext().checksignals()
807 if eintr_retry:
808 return None
809
810 try:
811 msg, lgt = strerror(errno)
812 except ValueError:
813 msg = 'error %d' % errno
814 lgt = len(msg)
815 w_errno = space.newint(errno)
816 w_winerror = space.w_None
817 w_msg = space.newtext(msg, lgt)
818
819 if w_filename is None:
820 w_filename = space.w_None
821 if w_filename2 is None:
822 w_filename2 = space.w_None
823 w_error = space.call_function(w_exc, w_errno, w_msg, w_filename,
824 w_winerror, w_filename2)
825 # w_exc may be normalized into a subclass of W_OSError
826 operror = OperationError(space.type(w_error), w_error)
827 if eintr_retry:
828 raise operror
829 return operror
830
831 @specialize.arg(3, 5)
832 @dont_inline
833 def wrap_oserror(space, e, filename=None, w_exception_class=None,
834 filename2=None, eintr_retry=False):
835 w_filename = None
836 w_filename2 = None
837 if filename is not None:
838 w_filename = space.newfilename(filename)
839 if filename2 is not None:
840 w_filename2 = space.newfilename(filename2)
841 return wrap_oserror2(space, e, w_filename,
842 w_exception_class=w_exception_class,
843 w_filename2=w_filename2,
844 eintr_retry=eintr_retry)
845
846 def exception_from_errno(space, w_type, errno):
847 msg, lgt = strerror(errno)
848 w_error = space.call_function(w_type, space.newint(errno),
849 space.newtext(msg, lgt))
850 return OperationError(w_type, w_error)
851
852 def exception_from_saved_errno(space, w_type):
853 from rpython.rlib.rposix import get_saved_errno
854 errno = get_saved_errno()
855 return exception_from_errno(space, w_type, errno)
856
857 def new_exception_class(space, name, w_bases=None, w_dict=None):
858 """Create a new exception type.
859 @param name: the name of the type.
860 @param w_bases: Either an exception type, or a wrapped tuple of
861 exception types. default is space.w_Exception.
862 @param w_dict: an optional dictionary to populate the class __dict__.
863 """
864 if '.' in name:
865 module, name = name.rsplit('.', 1)
866 else:
867 module = None
868 if w_bases is None:
869 w_bases = space.newtuple([space.w_Exception])
870 elif not space.isinstance_w(w_bases, space.w_tuple):
871 w_bases = space.newtuple([w_bases])
872 if w_dict is None:
873 w_dict = space.newdict()
874 w_exc = space.call_function(
875 space.w_type, space.newtext(name), w_bases, w_dict)
876 if module:
877 space.setattr(w_exc, space.newtext("__module__"), space.newtext(module))
878 return w_exc
879
880 def new_import_error(space, w_msg, w_name, w_path):
881 """Create a new instance of ImportError.
882
883 The result corresponds to ImportError(msg, name=name, path=path)
884 """
885 return space.appexec(
886 [w_msg, w_name, w_path], """(msg, name, path):
887 return ImportError(msg, name=name, path=path)""")
888
889 def raise_import_error(space, w_msg, w_name, w_path):
890 w_exc = new_import_error(space, w_msg, w_name, w_path)
891 raise OperationError(space.w_ImportError, w_exc)
892
893 @jit.dont_look_inside
894 def get_converted_unexpected_exception(space, e):
895 """This is used in two places when we get an non-OperationError
896 RPython exception: from gateway.py when calling an interp-level
897 function raises; and from pyopcode.py when we're exiting the
898 interpretation of the frame with an exception. Note that it
899 *cannot* be used in pyopcode.py: that place gets a
900 ContinueRunningNormally exception from the JIT, which must not end
901 up here!
902 """
903 try:
904 if not we_are_translated():
905 raise
906 raise e
907 except KeyboardInterrupt:
908 return OperationError(space.w_KeyboardInterrupt, space.w_None)
909 except MemoryError:
910 return OperationError(space.w_MemoryError, space.w_None)
911 except rstackovf.StackOverflow as e:
912 # xxx twisted logic which happens to give the result that we
913 # want: when untranslated, a RuntimeError or its subclass
914 # NotImplementedError is caught here. Then
915 # check_stack_overflow() will re-raise it directly. We see
916 # the result as this exception propagates directly. But when
917 # translated, an RPython-level RuntimeError is turned into
918 # an app-level RuntimeError by the next case.
919 rstackovf.check_stack_overflow()
920 # print "maximum recurson depth exceeded"
921 # assert False
922 return oefmt(space.w_RecursionError,
923 "maximum recursion depth exceeded")
924 except RuntimeError: # not on top of py.py
925 return OperationError(space.w_RuntimeError, space.w_None)
926 except:
927 if we_are_translated():
928 from rpython.rlib.debug import debug_print_traceback
929 debug_print_traceback()
930 extra = '; internal traceback was dumped to stderr'
931 else:
932 # when untranslated, we don't wrap into an app-level
933 # SystemError (this makes debugging tests harder)
934 raise
935 return OperationError(space.w_SystemError, space.newtext(
936 "unexpected internal exception (please report a bug): %r%s" %
937 (e, extra)))