Debian Codegraph @

rpython/rtyper/llinterp.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import cStringIO
4 import os
5 import sys
6 import traceback
7
8 import py
9
10 from rpython.flowspace.model import (FunctionGraph, Constant, Variable)
11 from rpython.rlib import rstackovf
12 from rpython.rlib.objectmodel import (ComputedIntSymbolic, CDefinedIntSymbolic,
13 Symbolic)
14 # intmask is used in an exec'd code block
15 from rpython.rlib.rarithmetic import (ovfcheck, is_valid_int, intmask,
16 r_uint, r_longlong, r_ulonglong, r_longlonglong)
17 from rpython.rtyper.lltypesystem import lltype, llmemory, lloperation, llheap
18 from rpython.rtyper import rclass
19 from rpython.tool.ansi_print import AnsiLogger
20
21 # by default this logger's output is disabled.
22 # e.g. tests can then switch on logging to get more help
23 # for failing tests
24 log = AnsiLogger('llinterp')
25 log.output_disabled = True
26
27
28 class LLException(Exception):
29
30 # .error_value is used only by tests: in particular,
31 # test_exceptiontransform uses it to check what is the return value of the
32 # function in case of exception
33 UNDEFINED_ERROR_VALUE = object() # sentinel for self.error_value
34
35 def __init__(self, *args, **kwargs):
36 "NOT_RPYTHON"
37 Exception.__init__(self, *args)
38 self.error_value = kwargs.pop('error_value', self.UNDEFINED_ERROR_VALUE)
39 if kwargs:
40 raise TypeError('unexpected keyword arguments: %s' % kwargs.keys())
41
42 def __str__(self):
43 etype = self.args[0]
44 #evalue = self.args[1]
45 if len(self.args) > 2:
46 f = cStringIO.StringIO()
47 original_type, original_value, original_tb = self.args[2]
48 traceback.print_exception(original_type, original_value, original_tb,
49 file=f)
50 extra = '\n' + f.getvalue().rstrip('\n')
51 extra = extra.replace('\n', '\n | ') + '\n `------'
52 else:
53 extra = ''
54 return '<LLException %r%s>' % (type_name(etype), extra)
55
56 class LLFatalError(Exception):
57 def __str__(self):
58 return ': '.join([str(x) for x in self.args])
59
60 class LLAssertFailure(Exception):
61 pass
62
63
64 def type_name(etype):
65 return ''.join(etype.name.chars)
66
67 class LLInterpreter(object):
68 """ low level interpreter working with concrete values. """
69
70 current_interpreter = None
71
72 def __init__(self, typer, tracing=True, exc_data_ptr=None):
73 self.bindings = {}
74 self.typer = typer
75 # 'heap' is module or object that provides malloc, etc for lltype ops
76 self.heap = llheap
77 self.exc_data_ptr = exc_data_ptr
78 self.frame_stack = []
79 self.tracer = None
80 self.frame_class = LLFrame
81 if tracing:
82 self.tracer = Tracer()
83
84 def eval_graph(self, graph, args=(), recursive=False):
85 llframe = self.frame_class(graph, args, self)
86 if self.tracer and not recursive:
87 global tracer1
88 tracer1 = self.tracer
89 self.tracer.start()
90 retval = None
91 self.traceback_frames = []
92 old_frame_stack = self.frame_stack[:]
93 prev_interpreter = LLInterpreter.current_interpreter
94 LLInterpreter.current_interpreter = self
95 try:
96 try:
97 retval = llframe.eval()
98 except LLException as e:
99 log.error("LLEXCEPTION: %s" % (e, ))
100 self.print_traceback()
101 if self.tracer:
102 self.tracer.dump('LLException: %s\n' % (e,))
103 raise
104 except Exception as e:
105 if getattr(e, '_go_through_llinterp_uncaught_', False):
106 raise
107 log.error("AN ERROR OCCURED: %s" % (e, ))
108 self.print_traceback()
109 if self.tracer:
110 line = str(e)
111 if line:
112 line = ': ' + line
113 line = '* %s' % (e.__class__.__name__,) + line
114 self.tracer.dump(line + '\n')
115 raise
116 finally:
117 LLInterpreter.current_interpreter = prev_interpreter
118 assert old_frame_stack == self.frame_stack
119 if self.tracer:
120 if retval is not None:
121 self.tracer.dump(' ---> %r\n' % (retval,))
122 if not recursive:
123 self.tracer.stop()
124 return retval
125
126 def print_traceback(self):
127 frames = self.traceback_frames
128 frames.reverse()
129 self.traceback_frames = []
130 lines = []
131 for frame in frames:
132 logline = frame.graph.name + "()"
133 if frame.curr_block is None:
134 logline += " <not running yet>"
135 lines.append(logline)
136 continue
137 try:
138 logline += " " + self.typer.annotator.annotated[frame.curr_block].func.__module__
139 except (KeyError, AttributeError, TypeError):
140 logline += " <unknown module>"
141 lines.append(logline)
142 for i, operation in enumerate(frame.curr_block.operations):
143 if i == frame.curr_operation_index:
144 logline = "E %s"
145 else:
146 logline = " %s"
147 lines.append(logline % (operation, ))
148 if self.tracer:
149 self.tracer.dump('Traceback\n', bold=True)
150 for line in lines:
151 self.tracer.dump(line + '\n')
152 for line in lines:
153 log.traceback(line)
154
155 def get_tlobj(self):
156 try:
157 return self._tlobj
158 except AttributeError:
159 from rpython.rtyper.lltypesystem import rffi
160 PERRNO = rffi.CArrayPtr(rffi.INT)
161 fake_p_errno = lltype.malloc(PERRNO.TO, 1, flavor='raw', zero=True,
162 track_allocation=False)
163 self._tlobj = {'RPY_TLOFS_p_errno': fake_p_errno,
164 #'thread_ident': ...,
165 }
166 return self._tlobj
167
168 def find_roots(self, is_minor=False):
169 """Return a list of the addresses of the roots."""
170 #log.findroots("starting")
171 roots = []
172 for frame in reversed(self.frame_stack):
173 #log.findroots("graph", frame.graph.name)
174 frame.find_roots(roots)
175 # If a call is done with 'is_minor=True', we can stop after the
176 # first frame in the stack that was already seen by the previous
177 # call with 'is_minor=True'. (We still need to trace that frame,
178 # but not its callers.)
179 if is_minor:
180 if getattr(frame, '_find_roots_already_seen', False):
181 break
182 frame._find_roots_already_seen = True
183 return roots
184
185 def find_exception(self, exc):
186 assert isinstance(exc, LLException)
187 klass, inst = exc.args[0], exc.args[1]
188 for cls in enumerate_exceptions_top_down():
189 if "".join(klass.name.chars) == cls.__name__:
190 return cls
191 raise ValueError("couldn't match exception, maybe it"
192 " has RPython attributes like OSError?")
193
194 def get_transformed_exc_data(self, graph):
195 if hasattr(graph, 'exceptiontransformed'):
196 return graph.exceptiontransformed
197 if getattr(graph, 'rgenop', False):
198 return self.exc_data_ptr
199 return None
200
201 def _store_exception(self, exc):
202 raise PleaseOverwriteStoreException("You just invoked ll2ctypes callback without overwriting _store_exception on llinterpreter")
203
204 class PleaseOverwriteStoreException(Exception):
205 pass
206
207 def checkptr(ptr):
208 assert isinstance(lltype.typeOf(ptr), lltype.Ptr)
209
210 def checkadr(addr):
211 assert lltype.typeOf(addr) is llmemory.Address
212
213
214 class LLFrame(object):
215 def __init__(self, graph, args, llinterpreter):
216 assert not graph or isinstance(graph, FunctionGraph)
217 self.graph = graph
218 self.args = args
219 self.llinterpreter = llinterpreter
220 self.heap = llinterpreter.heap
221 self.bindings = {}
222 self.curr_block = None
223 self.curr_operation_index = 0
224 self.alloca_objects = []
225
226 def newsubframe(self, graph, args):
227 return self.__class__(graph, args, self.llinterpreter)
228
229 # _______________________________________________________
230 # variable setters/getters helpers
231
232 def clear(self):
233 self.bindings.clear()
234
235 def fillvars(self, block, values):
236 vars = block.inputargs
237 assert len(vars) == len(values), (
238 "block %s received %d args, expected %d" % (
239 block, len(values), len(vars)))
240 for var, val in zip(vars, values):
241 self.setvar(var, val)
242
243 def setvar(self, var, val):
244 if var.concretetype is not lltype.Void:
245 try:
246 val = lltype.enforce(var.concretetype, val)
247 except TypeError:
248 assert False, "type error: input value of type:\n\n\t%r\n\n===> variable of type:\n\n\t%r\n" % (lltype.typeOf(val), var.concretetype)
249 assert isinstance(var, Variable)
250 self.bindings[var] = val
251
252 def setifvar(self, var, val):
253 if isinstance(var, Variable):
254 self.setvar(var, val)
255
256 def getval(self, varorconst):
257 try:
258 val = varorconst.value
259 except AttributeError:
260 val = self.bindings[varorconst]
261 if isinstance(val, ComputedIntSymbolic):
262 val = val.compute_fn()
263 if varorconst.concretetype is not lltype.Void:
264 try:
265 val = lltype.enforce(varorconst.concretetype, val)
266 except TypeError:
267 assert False, "type error: %r val from %r var/const" % (lltype.typeOf(val), varorconst.concretetype)
268 return val
269
270 # _______________________________________________________
271 # other helpers
272 def getoperationhandler(self, opname):
273 ophandler = getattr(self, 'op_' + opname, None)
274 if ophandler is None:
275 # try to import the operation from opimpl.py
276 ophandler = lloperation.LL_OPERATIONS[opname].fold
277 setattr(self.__class__, 'op_' + opname, staticmethod(ophandler))
278 return ophandler
279 # _______________________________________________________
280 # evaling functions
281
282 def eval(self):
283 graph = self.graph
284 tracer = self.llinterpreter.tracer
285 if tracer:
286 tracer.enter(graph)
287 self.llinterpreter.frame_stack.append(self)
288 try:
289 try:
290 nextblock = graph.startblock
291 args = self.args
292 while 1:
293 self.clear()
294 self.fillvars(nextblock, args)
295 nextblock, args = self.eval_block(nextblock)
296 if nextblock is None:
297 for obj in self.alloca_objects:
298 obj._obj._free()
299 return args
300 except Exception:
301 self.llinterpreter.traceback_frames.append(self)
302 raise
303 finally:
304 leavingframe = self.llinterpreter.frame_stack.pop()
305 assert leavingframe is self
306 if tracer:
307 tracer.leave()
308
309 def eval_block(self, block):
310 """ return (nextblock, values) tuple. If nextblock
311 is None, values is the concrete return value.
312 """
313 self.curr_block = block
314 e = None
315
316 try:
317 for i, op in enumerate(block.operations):
318 self.curr_operation_index = i
319 self.eval_operation(op)
320 except LLException as e:
321 if op is not block.raising_op:
322 raise
323 except RuntimeError as e:
324 rstackovf.check_stack_overflow()
325 # xxx fish fish fish for proper etype and evalue to use
326 rtyper = self.llinterpreter.typer
327 bk = rtyper.annotator.bookkeeper
328 classdef = bk.getuniqueclassdef(rstackovf._StackOverflow)
329 exdata = rtyper.exceptiondata
330 evalue = exdata.get_standard_ll_exc_instance(rtyper, classdef)
331 etype = exdata.fn_type_of_exc_inst(evalue)
332 e = LLException(etype, evalue)
333 if op is not block.raising_op:
334 raise e
335
336 # determine nextblock and/or return value
337 if len(block.exits) == 0:
338 # return block
339 tracer = self.llinterpreter.tracer
340 if len(block.inputargs) == 2:
341 # exception
342 if tracer:
343 tracer.dump('raise')
344 etypevar, evaluevar = block.getvariables()
345 etype = self.getval(etypevar)
346 evalue = self.getval(evaluevar)
347 # watch out, these are _ptr's
348 raise LLException(etype, evalue)
349 resultvar, = block.getvariables()
350 result = self.getval(resultvar)
351 exc_data = self.llinterpreter.get_transformed_exc_data(self.graph)
352 if exc_data:
353 # re-raise the exception set by this graph, if any
354 etype = exc_data.exc_type
355 if etype:
356 evalue = exc_data.exc_value
357 if tracer:
358 tracer.dump('raise')
359 exc_data.exc_type = lltype.typeOf(etype)._defl()
360 exc_data.exc_value = lltype.typeOf(evalue)._defl()
361 raise LLException(etype, evalue, error_value=result)
362 if tracer:
363 tracer.dump('return')
364 return None, result
365 elif block.exitswitch is None:
366 # single-exit block
367 assert len(block.exits) == 1
368 link = block.exits[0]
369 elif block.canraise:
370 link = block.exits[0]
371 if e:
372 exdata = self.llinterpreter.typer.exceptiondata
373 cls = e.args[0]
374 inst = e.args[1]
375 for link in block.exits[1:]:
376 assert issubclass(link.exitcase, py.builtin.BaseException)
377 if self.op_direct_call(exdata.fn_exception_match,
378 cls, link.llexitcase):
379 self.setifvar(link.last_exception, cls)
380 self.setifvar(link.last_exc_value, inst)
381 break
382 else:
383 # no handler found, pass on
384 raise e
385 else:
386 llexitvalue = self.getval(block.exitswitch)
387 if block.exits[-1].exitcase == "default":
388 defaultexit = block.exits[-1]
389 nondefaultexits = block.exits[:-1]
390 assert defaultexit.llexitcase is None
391 else:
392 defaultexit = None
393 nondefaultexits = block.exits
394 for link in nondefaultexits:
395 if link.llexitcase == llexitvalue:
396 break # found -- the result is in 'link'
397 else:
398 if defaultexit is None:
399 raise ValueError("exit case %r not found in the exit links "
400 "of %r" % (llexitvalue, block))
401 else:
402 link = defaultexit
403 return link.target, [self.getval(x) for x in link.args]
404
405 def eval_operation(self, operation):
406 tracer = self.llinterpreter.tracer
407 if tracer:
408 tracer.dump(str(operation))
409 ophandler = self.getoperationhandler(operation.opname)
410 # XXX slighly unnice but an important safety check
411 if operation.opname == 'direct_call':
412 assert isinstance(operation.args[0], Constant)
413 elif operation.opname == 'indirect_call':
414 assert isinstance(operation.args[0], Variable)
415 if getattr(ophandler, 'specialform', False):
416 retval = ophandler(*operation.args)
417 else:
418 vals = [self.getval(x) for x in operation.args]
419 if getattr(ophandler, 'need_result_type', False):
420 vals.insert(0, operation.result.concretetype)
421 try:
422 retval = ophandler(*vals)
423 except LLException as e:
424 # safety check check that the operation is allowed to raise that
425 # exception
426 if operation.opname in lloperation.LL_OPERATIONS:
427 canraise = lloperation.LL_OPERATIONS[operation.opname].canraise
428 if Exception not in canraise:
429 exc = self.llinterpreter.find_exception(e)
430 for canraiseexc in canraise:
431 if issubclass(exc, canraiseexc):
432 break
433 else:
434 raise TypeError("the operation %s is not expected to raise %s" % (operation, exc))
435
436 # for exception-transformed graphs, store the LLException
437 # into the exc_data used by this graph
438 exc_data = self.llinterpreter.get_transformed_exc_data(
439 self.graph)
440 if exc_data:
441 etype = e.args[0]
442 evalue = e.args[1]
443 exc_data.exc_type = etype
444 exc_data.exc_value = evalue
445 retval = e.error_value
446 if retval is LLException.UNDEFINED_ERROR_VALUE:
447 from rpython.translator import exceptiontransform
448 # if we are here it means that the exception was
449 # caused by a builtin op such as int_add_ovf (i.e.,
450 # NOT a call): in this case, we just use the default
451 # error_value
452 T = operation.result.concretetype
453 retval = exceptiontransform.default_error_value(T)
454 else:
455 raise
456 self.setvar(operation.result, retval)
457 if tracer:
458 if retval is None:
459 tracer.dump('\n')
460 else:
461 tracer.dump(' ---> %r\n' % (retval,))
462
463 def make_llexception(self, exc=None):
464 if exc is None:
465 original = sys.exc_info()
466 exc = original[1]
467 # it makes no sense to convert some exception classes that
468 # just mean something buggy crashed
469 if isinstance(exc, (AssertionError, AttributeError,
470 TypeError, NameError,
471 KeyboardInterrupt, SystemExit,
472 ImportError, SyntaxError)):
473 raise original[0], original[1], original[2] # re-raise it
474 # for testing the JIT (see ContinueRunningNormally) we need
475 # to let some exceptions introduced by the JIT go through
476 # the llinterpreter uncaught
477 if getattr(exc, '_go_through_llinterp_uncaught_', False):
478 raise original[0], original[1], original[2] # re-raise it
479 extraargs = (original,)
480 else:
481 extraargs = ()
482 typer = self.llinterpreter.typer
483 exdata = typer.exceptiondata
484 evalue = exdata.get_standard_ll_exc_instance_by_class(exc.__class__)
485 etype = self.op_direct_call(exdata.fn_type_of_exc_inst, evalue)
486 raise LLException(etype, evalue, *extraargs)
487
488 def invoke_callable_with_pyexceptions(self, fptr, *args):
489 obj = fptr._obj
490 try:
491 return obj._callable(*args)
492 except LLException as e:
493 raise
494 except Exception as e:
495 if getattr(e, '_go_through_llinterp_uncaught_', False):
496 raise
497 if getattr(obj, '_debugexc', False):
498 log.ERROR('The llinterpreter got an '
499 'unexpected exception when calling')
500 log.ERROR('the external function %r:' % (fptr,))
501 log.ERROR('%s: %s' % (e.__class__.__name__, e))
502 if self.llinterpreter.tracer:
503 self.llinterpreter.tracer.flush()
504 import sys
505 from rpython.translator.tool.pdbplus import PdbPlusShow
506 PdbPlusShow(None).post_mortem(sys.exc_info()[2])
507 self.make_llexception()
508
509 def find_roots(self, roots):
510 #log.findroots(self.curr_block.inputargs)
511 vars = []
512 for v in self.curr_block.inputargs:
513 if isinstance(v, Variable):
514 vars.append(v)
515 for op in self.curr_block.operations[:self.curr_operation_index]:
516 vars.append(op.result)
517
518 for v in vars:
519 TYPE = v.concretetype
520 if isinstance(TYPE, lltype.Ptr) and TYPE.TO._gckind == 'gc':
521 roots.append(_address_of_local_var(self, v))
522
523 # __________________________________________________________
524 # misc LL operation implementations
525
526 def op_debug_view(self, *ll_objects):
527 from rpython.translator.tool.lltracker import track
528 track(*ll_objects)
529
530 def op_debug_assert(self, x, msg):
531 if not x:
532 raise LLAssertFailure(msg)
533
534 def op_debug_assert_not_none(self, x):
535 if not x:
536 raise LLAssertFailure("ll_assert_not_none() failed")
537
538 def op_debug_fatalerror(self, ll_msg, ll_exc=None):
539 msg = ''.join(ll_msg.chars)
540 if ll_exc is None:
541 raise LLFatalError(msg)
542 else:
543 ll_exc_type = lltype.cast_pointer(rclass.OBJECTPTR, ll_exc).typeptr
544 raise LLFatalError(msg, LLException(ll_exc_type, ll_exc))
545
546 def op_debug_llinterpcall(self, pythonfunction, *args_ll):
547 try:
548 return pythonfunction(*args_ll)
549 except:
550 self.make_llexception()
551
552 def op_debug_forked(self, *args):
553 raise NotImplementedError
554
555 def op_debug_start_traceback(self, *args):
556 pass # xxx write debugging code here?
557
558 def op_debug_reraise_traceback(self, *args):
559 pass # xxx write debugging code here?
560
561 def op_debug_record_traceback(self, *args):
562 pass # xxx write debugging code here?
563
564 def op_debug_print_traceback(self, *args):
565 pass # xxx write debugging code here?
566
567 def op_debug_catch_exception(self, *args):
568 pass # xxx write debugging code here?
569
570 def op_jit_marker(self, *args):
571 pass
572
573 def op_jit_record_exact_class(self, *args):
574 pass
575
576 def op_jit_record_exact_value(self, *args):
577 pass
578
579 def op_jit_conditional_call(self, *args):
580 raise NotImplementedError("should not be called while not jitted")
581
582 def op_jit_conditional_call_value(self, *args):
583 raise NotImplementedError("should not be called while not jitted")
584
585 def op_get_exception_addr(self, *args):
586 raise NotImplementedError
587
588 def op_get_exc_value_addr(self, *args):
589 raise NotImplementedError
590
591 def op_instrument_count(self, ll_tag, ll_label):
592 pass # xxx for now
593
594 def op_keepalive(self, value):
595 pass
596
597 def op_hint(self, x, hints):
598 return x
599
600 def op_decode_arg(self, fname, i, name, vargs, vkwds):
601 raise NotImplementedError("decode_arg")
602
603 def op_decode_arg_def(self, fname, i, name, vargs, vkwds, default):
604 raise NotImplementedError("decode_arg_def")
605
606 def op_check_no_more_arg(self, fname, n, vargs):
607 raise NotImplementedError("check_no_more_arg")
608
609 def op_getslice(self, vargs, start, stop_should_be_None):
610 raise NotImplementedError("getslice") # only for argument parsing
611
612 def op_check_self_nonzero(self, fname, vself):
613 raise NotImplementedError("check_self_nonzero")
614
615 def op_setfield(self, obj, fieldname, fieldvalue):
616 # obj should be pointer
617 FIELDTYPE = getattr(lltype.typeOf(obj).TO, fieldname)
618 if FIELDTYPE is not lltype.Void:
619 self.heap.setfield(obj, fieldname, fieldvalue)
620
621 def op_bare_setfield(self, obj, fieldname, fieldvalue):
622 # obj should be pointer
623 FIELDTYPE = getattr(lltype.typeOf(obj).TO, fieldname)
624 if FIELDTYPE is not lltype.Void:
625 setattr(obj, fieldname, fieldvalue)
626
627 def op_getinteriorfield(self, obj, *offsets):
628 checkptr(obj)
629 ob = obj
630 for o in offsets:
631 if isinstance(o, str):
632 ob = getattr(ob, o)
633 else:
634 ob = ob[o]
635 assert not isinstance(ob, lltype._interior_ptr)
636 return ob
637
638 def getinneraddr(self, obj, *offsets):
639 TYPE = lltype.typeOf(obj).TO
640 addr = llmemory.cast_ptr_to_adr(obj)
641 for o in offsets:
642 if isinstance(o, str):
643 addr += llmemory.offsetof(TYPE, o)
644 TYPE = getattr(TYPE, o)
645 else:
646 addr += llmemory.itemoffsetof(TYPE, o)
647 TYPE = TYPE.OF
648 return addr, TYPE
649
650 def op_setinteriorfield(self, obj, *fieldnamesval):
651 offsets, fieldvalue = fieldnamesval[:-1], fieldnamesval[-1]
652 inneraddr, FIELD = self.getinneraddr(obj, *offsets)
653 if FIELD is not lltype.Void:
654 self.heap.setinterior(obj, inneraddr, FIELD, fieldvalue, offsets)
655
656 def op_bare_setinteriorfield(self, obj, *fieldnamesval):
657 offsets, fieldvalue = fieldnamesval[:-1], fieldnamesval[-1]
658 inneraddr, FIELD = self.getinneraddr(obj, *offsets)
659 if FIELD is not lltype.Void:
660 llheap.setinterior(obj, inneraddr, FIELD, fieldvalue)
661
662 def op_getarrayitem(self, array, index):
663 return array[index]
664
665 def op_setarrayitem(self, array, index, item):
666 # array should be a pointer
667 ITEMTYPE = lltype.typeOf(array).TO.OF
668 if ITEMTYPE is not lltype.Void:
669 self.heap.setarrayitem(array, index, item)
670
671 def op_bare_setarrayitem(self, array, index, item):
672 # array should be a pointer
673 ITEMTYPE = lltype.typeOf(array).TO.OF
674 if ITEMTYPE is not lltype.Void:
675 array[index] = item
676
677 def perform_call(self, f, ARGS, args):
678 fobj = f._obj
679 has_callable = getattr(fobj, '_callable', None) is not None
680 if hasattr(fobj, 'graph'):
681 graph = fobj.graph
682 else:
683 assert has_callable, "don't know how to execute %r" % f
684 return self.invoke_callable_with_pyexceptions(f, *args)
685 args_v = graph.getargs()
686 if len(ARGS) != len(args_v):
687 raise TypeError("graph with %d args called with wrong func ptr type: %r" %(len(args_v), ARGS))
688 for T, v in zip(ARGS, args_v):
689 if not lltype.isCompatibleType(T, v.concretetype):
690 raise TypeError("graph with %r args called with wrong func ptr type: %r" %
691 (tuple([v.concretetype for v in args_v]), ARGS))
692 frame = self.newsubframe(graph, args)
693 return frame.eval()
694
695 def op_direct_call(self, f, *args):
696 FTYPE = lltype.typeOf(f).TO
697 return self.perform_call(f, FTYPE.ARGS, args)
698
699 def op_indirect_call(self, f, *args):
700 graphs = args[-1]
701 args = args[:-1]
702 if graphs is not None:
703 obj = f._obj
704 if hasattr(obj, 'graph'):
705 assert obj.graph in graphs
706 else:
707 pass
708 #log.warn("op_indirect_call with graphs=None:", f)
709 return self.op_direct_call(f, *args)
710
711 def op_malloc(self, obj, flags):
712 flavor = flags['flavor']
713 zero = flags.get('zero', False)
714 track_allocation = flags.get('track_allocation', True)
715 if flavor == "stack":
716 result = self.heap.malloc(obj, zero=zero, flavor='raw')
717 self.alloca_objects.append(result)
718 return result
719 ptr = self.heap.malloc(obj, zero=zero, flavor=flavor,
720 track_allocation=track_allocation)
721 return ptr
722
723 def op_malloc_varsize(self, obj, flags, size):
724 flavor = flags['flavor']
725 zero = flags.get('zero', False)
726 track_allocation = flags.get('track_allocation', True)
727 assert flavor in ('gc', 'raw')
728 try:
729 ptr = self.heap.malloc(obj, size, zero=zero, flavor=flavor,
730 track_allocation=track_allocation)
731 return ptr
732 except MemoryError:
733 self.make_llexception()
734
735 def op_free(self, obj, flags):
736 assert flags['flavor'] == 'raw'
737 track_allocation = flags.get('track_allocation', True)
738 self.heap.free(obj, flavor='raw', track_allocation=track_allocation)
739
740 def op_gc_add_memory_pressure(self, size):
741 self.heap.add_memory_pressure(size)
742
743 def op_gc_fq_next_dead(self, fq_tag):
744 return self.heap.gc_fq_next_dead(fq_tag)
745
746 def op_gc_fq_register(self, fq_tag, obj):
747 self.heap.gc_fq_register(fq_tag, obj)
748
749 def op_gc_gettypeid(self, obj):
750 return lloperation.llop.combine_ushort(lltype.Signed, self.heap.gettypeid(obj), 0)
751
752 def op_shrink_array(self, obj, smallersize):
753 return self.heap.shrink_array(obj, smallersize)
754
755 def op_zero_gc_pointers_inside(self, obj):
756 raise NotImplementedError("zero_gc_pointers_inside")
757
758 def op_gc_get_stats(self, obj):
759 raise NotImplementedError("gc_get_stats")
760
761 def op_gc_writebarrier_before_copy(self, source, dest,
762 source_start, dest_start, length):
763 if hasattr(self.heap, 'writebarrier_before_copy'):
764 return self.heap.writebarrier_before_copy(source, dest,
765 source_start, dest_start,
766 length)
767 else:
768 return True
769
770 def op_gc_writebarrier_before_move(self, array):
771 if hasattr(self.heap, 'writebarrier_before_move'):
772 self.heap.writebarrier_before_move(array)
773
774 def op_getfield(self, obj, field):
775 checkptr(obj)
776 # check the difference between op_getfield and op_getsubstruct:
777 assert not isinstance(getattr(lltype.typeOf(obj).TO, field),
778 lltype.ContainerType)
779 return getattr(obj, field)
780
781 def op_force_cast(self, RESTYPE, obj):
782 from rpython.rtyper.lltypesystem import ll2ctypes
783 return ll2ctypes.force_cast(RESTYPE, obj)
784 op_force_cast.need_result_type = True
785
786 def op_cast_int_to_ptr(self, RESTYPE, int1):
787 return lltype.cast_int_to_ptr(RESTYPE, int1)
788 op_cast_int_to_ptr.need_result_type = True
789
790 def op_cast_ptr_to_int(self, ptr1):
791 checkptr(ptr1)
792 return lltype.cast_ptr_to_int(ptr1)
793
794 def op_cast_opaque_ptr(self, RESTYPE, obj):
795 checkptr(obj)
796 return lltype.cast_opaque_ptr(RESTYPE, obj)
797 op_cast_opaque_ptr.need_result_type = True
798
799 def op_length_of_simple_gcarray_from_opaque(self, obj):
800 checkptr(obj)
801 return lltype.length_of_simple_gcarray_from_opaque(obj)
802
803 def op_cast_ptr_to_adr(self, ptr):
804 checkptr(ptr)
805 return llmemory.cast_ptr_to_adr(ptr)
806
807 def op_cast_adr_to_int(self, adr, mode):
808 checkadr(adr)
809 return llmemory.cast_adr_to_int(adr, mode)
810
811 def op_convert_float_bytes_to_longlong(self, f):
812 from rpython.rlib import longlong2float
813 return longlong2float.float2longlong(f)
814
815 def op_weakref_create(self, v_obj):
816 def objgetter(): # special support for gcwrapper.py
817 return self.getval(v_obj)
818 assert self.llinterpreter.typer.getconfig().translation.rweakref
819 return self.heap.weakref_create_getlazy(objgetter)
820 op_weakref_create.specialform = True
821
822 def op_weakref_deref(self, PTRTYPE, obj):
823 assert self.llinterpreter.typer.getconfig().translation.rweakref
824 return self.heap.weakref_deref(PTRTYPE, obj)
825 op_weakref_deref.need_result_type = True
826
827 def op_cast_ptr_to_weakrefptr(self, obj):
828 assert self.llinterpreter.typer.getconfig().translation.rweakref
829 return llmemory.cast_ptr_to_weakrefptr(obj)
830
831 def op_cast_weakrefptr_to_ptr(self, PTRTYPE, obj):
832 assert self.llinterpreter.typer.getconfig().translation.rweakref
833 return llmemory.cast_weakrefptr_to_ptr(PTRTYPE, obj)
834 op_cast_weakrefptr_to_ptr.need_result_type = True
835
836 def op_gc__collect(self, *gen):
837 self.heap.collect(*gen)
838
839 def op_gc__collect_step(self):
840 return self.heap.collect_step()
841
842 def op_gc__enable(self):
843 self.heap.enable()
844
845 def op_gc__disable(self):
846 self.heap.disable()
847
848 def op_gc__isenabled(self):
849 return self.heap.isenabled()
850
851 def op_gc_heap_stats(self):
852 raise NotImplementedError
853
854 def op_gc_obtain_free_space(self, size):
855 raise NotImplementedError
856
857 def op_gc_can_move(self, ptr):
858 addr = llmemory.cast_ptr_to_adr(ptr)
859 return self.heap.can_move(addr)
860
861 def op_gc_thread_run(self):
862 self.heap.thread_run()
863
864 def op_gc_thread_start(self):
865 self.heap.thread_start()
866
867 def op_gc_thread_die(self):
868 self.heap.thread_die()
869
870 def op_gc_thread_before_fork(self):
871 raise NotImplementedError
872
873 def op_gc_thread_after_fork(self):
874 raise NotImplementedError
875
876 def op_gc_free(self, addr):
877 # what can you do?
878 pass
879 #raise NotImplementedError("gc_free")
880
881 def op_gc_fetch_exception(self):
882 raise NotImplementedError("gc_fetch_exception")
883
884 def op_gc_restore_exception(self, exc):
885 raise NotImplementedError("gc_restore_exception")
886
887 def op_gc_adr_of_nursery_top(self):
888 raise NotImplementedError
889 def op_gc_adr_of_nursery_free(self):
890 raise NotImplementedError
891
892 def op_gc_adr_of_root_stack_base(self):
893 raise NotImplementedError
894 def op_gc_adr_of_root_stack_top(self):
895 raise NotImplementedError
896
897 def op_gc_modified_shadowstack(self):
898 raise NotImplementedError
899
900 def op_gc_call_rtti_destructor(self, rtti, addr):
901 if hasattr(rtti._obj, 'destructor_funcptr'):
902 d = rtti._obj.destructor_funcptr
903 obptr = addr.ref()
904 return self.op_direct_call(d, obptr)
905
906 def op_gc_deallocate(self, TYPE, addr):
907 raise NotImplementedError("gc_deallocate")
908
909 def op_gc_reload_possibly_moved(self, v_newaddr, v_ptr):
910 assert v_newaddr.concretetype is llmemory.Address
911 assert isinstance(v_ptr.concretetype, lltype.Ptr)
912 assert v_ptr.concretetype.TO._gckind == 'gc'
913 newaddr = self.getval(v_newaddr)
914 p = llmemory.cast_adr_to_ptr(newaddr, v_ptr.concretetype)
915 if isinstance(v_ptr, Constant):
916 assert v_ptr.value == p
917 else:
918 self.setvar(v_ptr, p)
919 op_gc_reload_possibly_moved.specialform = True
920
921 def op_gc_identityhash(self, obj):
922 return lltype.identityhash(obj)
923
924 def op_gc_id(self, ptr):
925 PTR = lltype.typeOf(ptr)
926 if isinstance(PTR, lltype.Ptr):
927 return self.heap.gc_id(ptr)
928 raise NotImplementedError("gc_id on %r" % (PTR,))
929
930 def op_gc_set_max_heap_size(self, maxsize):
931 raise NotImplementedError("gc_set_max_heap_size")
932
933 def op_gc_stack_bottom(self):
934 # Marker when we enter RPython code from C code. It used to be
935 # essential for trackgcroot.py. Nowaways it is mostly unused,
936 # except by revdb.
937 pass
938
939 def op_gc_pin(self, obj):
940 addr = llmemory.cast_ptr_to_adr(obj)
941 return self.heap.pin(addr)
942
943 def op_gc_unpin(self, obj):
944 addr = llmemory.cast_ptr_to_adr(obj)
945 self.heap.unpin(addr)
946
947 def op_gc__is_pinned(self, obj):
948 addr = llmemory.cast_ptr_to_adr(obj)
949 return self.heap._is_pinned(addr)
950
951 def op_gc_get_type_info_group(self):
952 raise NotImplementedError("gc_get_type_info_group")
953
954 def op_gc_get_rpy_memory_usage(self):
955 raise NotImplementedError("gc_get_rpy_memory_usage")
956
957 def op_gc_get_rpy_roots(self):
958 raise NotImplementedError("gc_get_rpy_roots")
959
960 def op_gc_get_rpy_referents(self):
961 raise NotImplementedError("gc_get_rpy_referents")
962
963 def op_gc_is_rpy_instance(self):
964 raise NotImplementedError("gc_is_rpy_instance")
965
966 def op_gc_get_rpy_type_index(self):
967 raise NotImplementedError("gc_get_rpy_type_index")
968
969 def op_gc_dump_rpy_heap(self):
970 raise NotImplementedError("gc_dump_rpy_heap")
971
972 def op_gc_typeids_z(self):
973 raise NotImplementedError("gc_typeids_z")
974
975 def op_gc_typeids_list(self):
976 raise NotImplementedError("gc_typeids_list")
977
978 def op_gc_gcflag_extra(self, subopnum, *args):
979 return self.heap.gcflag_extra(subopnum, *args)
980
981 def op_gc_rawrefcount_init(self, *args):
982 raise NotImplementedError("gc_rawrefcount_init")
983
984 def op_gc_rawrefcount_to_obj(self, *args):
985 raise NotImplementedError("gc_rawrefcount_to_obj")
986
987 def op_gc_rawrefcount_from_obj(self, *args):
988 raise NotImplementedError("gc_rawrefcount_from_obj")
989
990 def op_gc_rawrefcount_create_link_pyobj(self, *args):
991 raise NotImplementedError("gc_rawrefcount_create_link_pyobj")
992
993 def op_gc_rawrefcount_create_link_pypy(self, *args):
994 raise NotImplementedError("gc_rawrefcount_create_link_pypy")
995
996 def op_gc_rawrefcount_mark_deallocating(self, *args):
997 raise NotImplementedError("gc_rawrefcount_mark_deallocating")
998
999 def op_gc_rawrefcount_next_dead(self, *args):
1000 raise NotImplementedError("gc_rawrefcount_next_dead")
1001
1002 def op_do_malloc_fixedsize(self):
1003 raise NotImplementedError("do_malloc_fixedsize")
1004 def op_do_malloc_fixedsize_clear(self):
1005 raise NotImplementedError("do_malloc_fixedsize_clear")
1006 def op_do_malloc_varsize(self):
1007 raise NotImplementedError("do_malloc_varsize")
1008 def op_do_malloc_varsize_clear(self):
1009 raise NotImplementedError("do_malloc_varsize_clear")
1010
1011 def op_get_write_barrier_failing_case(self):
1012 raise NotImplementedError("get_write_barrier_failing_case")
1013
1014 def op_get_write_barrier_from_array_failing_case(self):
1015 raise NotImplementedError("get_write_barrier_from_array_failing_case")
1016
1017 def op_stack_current(self):
1018 return 0
1019
1020 def op_threadlocalref_addr(self):
1021 return _address_of_thread_local()
1022
1023 def op_threadlocalref_get(self, RESTYPE, offset):
1024 return self.op_raw_load(RESTYPE, _address_of_thread_local(), offset)
1025 op_threadlocalref_get.need_result_type = True
1026
1027 op_threadlocalref_load = op_threadlocalref_get
1028
1029 def op_threadlocalref_store(self, offset, value):
1030 self.op_raw_store(_address_of_thread_local(), offset, value)
1031
1032 def op_threadlocalref_acquire(self, prev):
1033 raise NotImplementedError
1034 def op_threadlocalref_release(self, prev):
1035 raise NotImplementedError
1036 def op_threadlocalref_enum(self, prev):
1037 raise NotImplementedError
1038
1039 # __________________________________________________________
1040 # operations on addresses
1041
1042 def op_raw_malloc(self, size, zero):
1043 assert lltype.typeOf(size) == lltype.Signed
1044 return llmemory.raw_malloc(size, zero=zero)
1045
1046 def op_boehm_malloc(self, size):
1047 assert lltype.typeOf(size) == lltype.Signed
1048 raw = llmemory.raw_malloc(size)
1049 return llmemory.cast_adr_to_ptr(raw, llmemory.GCREF)
1050 op_boehm_malloc_atomic = op_boehm_malloc
1051
1052 def op_boehm_register_finalizer(self, p, finalizer):
1053 pass
1054
1055 def op_boehm_disappearing_link(self, link, obj):
1056 pass
1057
1058 def op_raw_malloc_usage(self, size):
1059 assert lltype.typeOf(size) == lltype.Signed
1060 return llmemory.raw_malloc_usage(size)
1061
1062 def op_raw_free(self, addr):
1063 checkadr(addr)
1064 llmemory.raw_free(addr)
1065
1066 def op_raw_memclear(self, addr, size):
1067 checkadr(addr)
1068 llmemory.raw_memclear(addr, size)
1069
1070 def op_raw_memcopy(self, fromaddr, toaddr, size):
1071 checkadr(fromaddr)
1072 checkadr(toaddr)
1073 llmemory.raw_memcopy(fromaddr, toaddr, size)
1074
1075 def op_raw_memset(self, addr, byte, size):
1076 raise NotImplementedError
1077
1078 op_raw_memmove = op_raw_memcopy # this is essentially the same here
1079
1080 def op_raw_load(self, RESTYPE, addr, offset):
1081 checkadr(addr)
1082 if isinstance(offset, int):
1083 from rpython.rtyper.lltypesystem import rffi
1084 ll_p = rffi.cast(rffi.CCHARP, addr)
1085 ll_p = rffi.cast(rffi.CArrayPtr(RESTYPE),
1086 rffi.ptradd(ll_p, offset))
1087 value = ll_p[0]
1088 elif getattr(addr, 'is_fake_thread_local_addr', False):
1089 assert type(offset) is CDefinedIntSymbolic
1090 value = self.llinterpreter.get_tlobj()[offset.expr]
1091 else:
1092 assert offset.TYPE == RESTYPE
1093 value = getattr(addr, str(RESTYPE).lower())[offset.repeat]
1094 assert lltype.typeOf(value) == RESTYPE
1095 return value
1096 op_raw_load.need_result_type = True
1097
1098 def op_raw_store(self, addr, offset, value):
1099 # XXX handle the write barrier by delegating to self.heap instead
1100 self.op_bare_raw_store(addr, offset, value)
1101
1102 def op_bare_raw_store(self, addr, offset, value):
1103 checkadr(addr)
1104 ARGTYPE = lltype.typeOf(value)
1105 if isinstance(offset, int):
1106 from rpython.rtyper.lltypesystem import rffi
1107 ll_p = rffi.cast(rffi.CCHARP, addr)
1108 ll_p = rffi.cast(rffi.CArrayPtr(ARGTYPE),
1109 rffi.ptradd(ll_p, offset))
1110 ll_p[0] = value
1111 elif getattr(addr, 'is_fake_thread_local_addr', False):
1112 assert type(offset) is CDefinedIntSymbolic
1113 self.llinterpreter.get_tlobj()[offset.expr] = value
1114 elif isinstance(offset, llmemory.ArrayLengthOffset):
1115 assert len(addr.ptr) == value # invalid ArrayLengthOffset
1116 else:
1117 assert offset.TYPE == ARGTYPE
1118 getattr(addr, str(ARGTYPE).lower())[offset.repeat] = value
1119
1120 def op_track_alloc_start(self, addr):
1121 # we don't do tracking at this level
1122 checkadr(addr)
1123
1124 def op_track_alloc_stop(self, addr):
1125 checkadr(addr)
1126
1127 def op_gc_enter_roots_frame(self, gcdata, numcolors):
1128 """Fetch from the gcdata the current root_stack_top; bump it
1129 by 'numcolors'; and assert that the new area is fully
1130 uninitialized so far.
1131 """
1132 assert not hasattr(self, '_inside_roots_frame')
1133 p = gcdata.inst_root_stack_top.ptr
1134 q = lltype.direct_ptradd(p, numcolors)
1135 self._inside_roots_frame = (p, q, numcolors, gcdata)
1136 gcdata.inst_root_stack_top = llmemory.cast_ptr_to_adr(q)
1137 #
1138 array = p._obj._parentstructure()
1139 index = p._obj._parent_index
1140 for i in range(index, index + numcolors):
1141 assert isinstance(array.getitem(i), lltype._uninitialized)
1142
1143 def op_gc_leave_roots_frame(self):
1144 """Cancel gc_enter_roots_frame() by removing the frame from
1145 the root_stack_top. Writes uninitialized entries in its old place.
1146 """
1147 (p, q, numcolors, gcdata) = self._inside_roots_frame
1148 assert gcdata.inst_root_stack_top.ptr == q
1149 gcdata.inst_root_stack_top = llmemory.cast_ptr_to_adr(p)
1150 del self._inside_roots_frame
1151 #
1152 array = p._obj._parentstructure()
1153 index = p._obj._parent_index
1154 for i in range(index, index + numcolors):
1155 array.setitem(i, lltype._uninitialized(llmemory.Address))
1156
1157 def op_gc_save_root(self, num, value):
1158 """Save one value (int or ptr) into the frame."""
1159 (p, q, numcolors, gcdata) = self._inside_roots_frame
1160 assert 0 <= num < numcolors
1161 if isinstance(value, int):
1162 assert value & 1 # must be odd
1163 v = llmemory.cast_int_to_adr(value)
1164 else:
1165 v = llmemory.cast_ptr_to_adr(value)
1166 llmemory.cast_ptr_to_adr(p).address[num] = v
1167
1168 def op_gc_restore_root(self, c_num, v_value):
1169 """Restore one value from the frame."""
1170 num = c_num.value
1171 (p, q, numcolors, gcdata) = self._inside_roots_frame
1172 assert 0 <= num < numcolors
1173 assert isinstance(v_value.concretetype, lltype.Ptr)
1174 assert v_value.concretetype.TO._gckind == 'gc'
1175 newvalue = llmemory.cast_ptr_to_adr(p).address[num]
1176 newvalue = llmemory.cast_adr_to_ptr(newvalue, v_value.concretetype)
1177 self.setvar(v_value, newvalue)
1178 op_gc_restore_root.specialform = True
1179
1180 def op_gc_push_roots(self, *args):
1181 raise NotImplementedError
1182
1183 def op_gc_pop_roots(self, *args):
1184 raise NotImplementedError
1185
1186 # ____________________________________________________________
1187 # Overflow-detecting variants
1188
1189 def op_int_add_ovf(self, x, y):
1190 assert isinstance(x, (int, long, llmemory.AddressOffset))
1191 assert isinstance(y, (int, long, llmemory.AddressOffset))
1192 try:
1193 return ovfcheck(x + y)
1194 except OverflowError:
1195 self.make_llexception()
1196
1197 def op_int_add_nonneg_ovf(self, x, y):
1198 if isinstance(y, int):
1199 assert y >= 0
1200 return self.op_int_add_ovf(x, y)
1201
1202 def op_int_sub_ovf(self, x, y):
1203 assert isinstance(x, (int, long))
1204 assert isinstance(y, (int, long))
1205 try:
1206 return ovfcheck(x - y)
1207 except OverflowError:
1208 self.make_llexception()
1209
1210 def op_int_mul_ovf(self, x, y):
1211 assert isinstance(x, (int, long, llmemory.AddressOffset))
1212 assert isinstance(y, (int, long, llmemory.AddressOffset))
1213 try:
1214 return ovfcheck(x * y)
1215 except OverflowError:
1216 self.make_llexception()
1217
1218 def op_int_is_true(self, x):
1219 # special case
1220 if type(x) is CDefinedIntSymbolic:
1221 x = x.default
1222 # if type(x) is a subclass of Symbolic, bool(x) will usually raise
1223 # a TypeError -- unless __nonzero__ has been explicitly overridden.
1224 assert is_valid_int(x) or isinstance(x, Symbolic)
1225 return bool(x)
1226
1227 # hack for jit.codegen.llgraph
1228
1229 def op_check_and_clear_exc(self):
1230 exc_data = self.llinterpreter.get_transformed_exc_data(self.graph)
1231 assert exc_data
1232 etype = exc_data.exc_type
1233 evalue = exc_data.exc_value
1234 exc_data.exc_type = lltype.typeOf(etype)._defl()
1235 exc_data.exc_value = lltype.typeOf(evalue)._defl()
1236 return bool(etype)
1237
1238 def op_gc_move_out_of_nursery(self, obj):
1239 raise NotImplementedError("gc_move_out_of_nursery")
1240
1241 def op_gc_increase_root_stack_depth(self, new_depth):
1242 raise NotImplementedError("gc_increase_root_stack_depth")
1243
1244 def op_revdb_stop_point(self, *args):
1245 pass
1246 def op_revdb_send_answer(self, *args):
1247 raise NotImplementedError
1248 def op_revdb_breakpoint(self, *args):
1249 raise NotImplementedError
1250 def op_revdb_get_value(self, *args):
1251 raise NotImplementedError
1252 def op_revdb_get_unique_id(self, *args):
1253 raise NotImplementedError
1254 def op_revdb_watch_save_state(self, *args):
1255 return False
1256 def op_revdb_watch_restore_state(self, *args):
1257 raise NotImplementedError
1258 def op_revdb_weakref_create(self, *args):
1259 raise NotImplementedError
1260 def op_revdb_weakref_deref(self, *args):
1261 raise NotImplementedError
1262 def op_revdb_call_destructor(self, *args):
1263 raise NotImplementedError
1264 def op_revdb_strtod(self, *args):
1265 raise NotImplementedError
1266 def op_revdb_frexp(self, *args):
1267 raise NotImplementedError
1268 def op_revdb_modf(self, *args):
1269 raise NotImplementedError
1270 def op_revdb_dtoa(self, *args):
1271 raise NotImplementedError
1272 def op_revdb_do_next_call(self):
1273 pass
1274 def op_revdb_set_thread_breakpoint(self, *args):
1275 raise NotImplementedError
1276
1277
1278 class Tracer(object):
1279 Counter = 0
1280 file = None
1281 TRACE = int(os.getenv('PYPY_TRACE') or '0')
1282
1283 HEADER = """<html><head>
1284 <script language=javascript type='text/javascript'>
1285 function togglestate(n) {
1286 var item = document.getElementById('div'+n)
1287 if (item.style.display == 'none')
1288 item.style.display = 'block';
1289 else
1290 item.style.display = 'none';
1291 }
1292
1293 function toggleall(lst) {
1294 for (var i = 0; i<lst.length; i++) {
1295 togglestate(lst[i]);
1296 }
1297 }
1298 </script>
1299 </head>
1300
1301 <body><pre>
1302 """
1303
1304 FOOTER = """</pre>
1305 <script language=javascript type='text/javascript'>
1306 toggleall(%r);
1307 </script>
1308
1309 </body></html>"""
1310
1311 ENTER = ('''\n\t<a href="javascript:togglestate(%d)">%s</a>'''
1312 '''\n<div id="div%d" style="display: %s">\t''')
1313 LEAVE = '''\n</div>\t'''
1314
1315 def htmlquote(self, s, text_to_html={}):
1316 # HTML quoting, lazily initialized
1317 if not text_to_html:
1318 import htmlentitydefs
1319 for key, value in htmlentitydefs.entitydefs.items():
1320 text_to_html[value] = '&' + key + ';'
1321 return ''.join([text_to_html.get(c, c) for c in s])
1322
1323 def start(self):
1324 # start of a dump file
1325 if not self.TRACE:
1326 return
1327 from rpython.tool.udir import udir
1328 n = Tracer.Counter
1329 Tracer.Counter += 1
1330 filename = 'llinterp_trace_%d.html' % n
1331 self.file = udir.join(filename).open('w')
1332 print(self.HEADER, file=self.file)
1333
1334 linkname = str(udir.join('llinterp_trace.html'))
1335 try:
1336 os.unlink(linkname)
1337 except OSError:
1338 pass
1339 try:
1340 os.symlink(filename, linkname)
1341 except (AttributeError, OSError):
1342 pass
1343
1344 self.count = 0
1345 self.indentation = ''
1346 self.depth = 0
1347 self.latest_call_chain = []
1348
1349 def stop(self):
1350 # end of a dump file
1351 if self.file:
1352 print(self.FOOTER % (self.latest_call_chain[1:]), file=self.file)
1353 self.file.close()
1354 self.file = None
1355
1356 def enter(self, graph):
1357 # enter evaluation of a graph
1358 if self.file:
1359 del self.latest_call_chain[self.depth:]
1360 self.depth += 1
1361 self.latest_call_chain.append(self.count)
1362 s = self.htmlquote(str(graph))
1363 i = s.rfind(')')
1364 s = s[:i+1] + '<b>' + s[i+1:] + '</b>'
1365 if self.count == 0:
1366 display = 'block'
1367 else:
1368 display = 'none'
1369 text = self.ENTER % (self.count, s, self.count, display)
1370 self.indentation += ' '
1371 self.file.write(text.replace('\t', self.indentation))
1372 self.count += 1
1373
1374 def leave(self):
1375 # leave evaluation of a graph
1376 if self.file:
1377 self.indentation = self.indentation[:-4]
1378 self.file.write(self.LEAVE.replace('\t', self.indentation))
1379 self.depth -= 1
1380
1381 def dump(self, text, bold=False):
1382 if self.file:
1383 text = self.htmlquote(text)
1384 if bold:
1385 text = '<b>%s</b>' % (text,)
1386 self.file.write(text.replace('\n', '\n'+self.indentation))
1387
1388 def flush(self):
1389 if self.file:
1390 self.file.flush()
1391
1392 def wrap_callable(llinterpreter, fn, obj, method_name):
1393 if method_name is None:
1394 # fn is a StaticMethod
1395 if obj is not None:
1396 self_arg = [obj]
1397 else:
1398 self_arg = []
1399 func_graph = fn.graph
1400 else:
1401 # obj is an instance, we want to call 'method_name' on it
1402 assert fn is None
1403 self_arg = [obj]
1404 func_graph = obj._TYPE._methods[method_name._str].graph
1405
1406 return wrap_graph(llinterpreter, func_graph, self_arg)
1407
1408 def wrap_graph(llinterpreter, graph, self_arg):
1409 """
1410 Returns a callable that inteprets the given func or method_name when called.
1411 """
1412
1413 def interp_func(*args):
1414 graph_args = self_arg + list(args)
1415 return llinterpreter.eval_graph(graph, args=graph_args)
1416 interp_func.graph = graph
1417 interp_func.self_arg = self_arg
1418 return graph.name, interp_func
1419
1420
1421 def enumerate_exceptions_top_down():
1422 import exceptions
1423 result = []
1424 seen = {}
1425 def addcls(cls):
1426 if (type(cls) is type(Exception) and
1427 issubclass(cls, py.builtin.BaseException)):
1428 if cls in seen:
1429 return
1430 for base in cls.__bases__: # bases first
1431 addcls(base)
1432 result.append(cls)
1433 seen[cls] = True
1434 for cls in exceptions.__dict__.values():
1435 addcls(cls)
1436 return result
1437
1438 class _address_of_local_var(object):
1439 _TYPE = llmemory.Address
1440 def __init__(self, frame, v):
1441 self._frame = frame
1442 self._v = v
1443 def _getaddress(self):
1444 return _address_of_local_var_accessor(self._frame, self._v)
1445 address = property(_getaddress)
1446
1447 class _address_of_local_var_accessor(object):
1448 def __init__(self, frame, v):
1449 self.frame = frame
1450 self.v = v
1451 def __getitem__(self, index):
1452 if index != 0:
1453 raise IndexError("address of local vars only support [0] indexing")
1454 p = self.frame.getval(self.v)
1455 result = llmemory.cast_ptr_to_adr(p)
1456 # the GC should never see instances of _gctransformed_wref
1457 result = self.unwrap_possible_weakref(result)
1458 return result
1459 def __setitem__(self, index, newvalue):
1460 if index != 0:
1461 raise IndexError("address of local vars only support [0] indexing")
1462 if self.v.concretetype == llmemory.WeakRefPtr:
1463 # fish some more
1464 assert isinstance(newvalue, llmemory.fakeaddress)
1465 p = llmemory.cast_ptr_to_weakrefptr(newvalue.ptr)
1466 else:
1467 p = llmemory.cast_adr_to_ptr(newvalue, self.v.concretetype)
1468 self.frame.setvar(self.v, p)
1469 def unwrap_possible_weakref(self, addr):
1470 # fish fish fish
1471 if addr and isinstance(addr.ptr._obj, llmemory._gctransformed_wref):
1472 return llmemory.fakeaddress(addr.ptr._obj._ptr)
1473 return addr
1474
1475 class _address_of_thread_local(object):
1476 _TYPE = llmemory.Address
1477 is_fake_thread_local_addr = True