-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathllinterp.py
More file actions
1462 lines (1241 loc) · 52.2 KB
/
llinterp.py
File metadata and controls
1462 lines (1241 loc) · 52.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import cStringIO
import os
import sys
import traceback
import py
from rpython.flowspace.model import (FunctionGraph, Constant, Variable)
from rpython.rlib import rstackovf
from rpython.rlib.objectmodel import (ComputedIntSymbolic, CDefinedIntSymbolic,
Symbolic)
# intmask is used in an exec'd code block
from rpython.rlib.rarithmetic import (ovfcheck, is_valid_int, intmask,
r_uint, r_longlong, r_ulonglong, r_longlonglong)
from rpython.rtyper.lltypesystem import lltype, llmemory, lloperation, llheap
from rpython.rtyper import rclass
from rpython.tool.ansi_print import AnsiLogger
# by default this logger's output is disabled.
# e.g. tests can then switch on logging to get more help
# for failing tests
log = AnsiLogger('llinterp')
log.output_disabled = True
class LLException(Exception):
def __init__(self, *args):
"NOT_RPYTHON"
Exception.__init__(self, *args)
def __str__(self):
etype = self.args[0]
#evalue = self.args[1]
if len(self.args) > 2:
f = cStringIO.StringIO()
original_type, original_value, original_tb = self.args[2]
traceback.print_exception(original_type, original_value, original_tb,
file=f)
extra = '\n' + f.getvalue().rstrip('\n')
extra = extra.replace('\n', '\n | ') + '\n `------'
else:
extra = ''
return '<LLException %r%s>' % (type_name(etype), extra)
class LLFatalError(Exception):
def __str__(self):
return ': '.join([str(x) for x in self.args])
class LLAssertFailure(Exception):
pass
def type_name(etype):
return ''.join(etype.name.chars)
class LLInterpreter(object):
""" low level interpreter working with concrete values. """
current_interpreter = None
def __init__(self, typer, tracing=True, exc_data_ptr=None):
self.bindings = {}
self.typer = typer
# 'heap' is module or object that provides malloc, etc for lltype ops
self.heap = llheap
self.exc_data_ptr = exc_data_ptr
self.frame_stack = []
self.tracer = None
self.frame_class = LLFrame
if tracing:
self.tracer = Tracer()
def eval_graph(self, graph, args=(), recursive=False):
llframe = self.frame_class(graph, args, self)
if self.tracer and not recursive:
global tracer1
tracer1 = self.tracer
self.tracer.start()
retval = None
self.traceback_frames = []
old_frame_stack = self.frame_stack[:]
prev_interpreter = LLInterpreter.current_interpreter
LLInterpreter.current_interpreter = self
try:
try:
retval = llframe.eval()
except LLException as e:
log.error("LLEXCEPTION: %s" % (e, ))
self.print_traceback()
if self.tracer:
self.tracer.dump('LLException: %s\n' % (e,))
raise
except Exception as e:
if getattr(e, '_go_through_llinterp_uncaught_', False):
raise
log.error("AN ERROR OCCURED: %s" % (e, ))
self.print_traceback()
if self.tracer:
line = str(e)
if line:
line = ': ' + line
line = '* %s' % (e.__class__.__name__,) + line
self.tracer.dump(line + '\n')
raise
finally:
LLInterpreter.current_interpreter = prev_interpreter
assert old_frame_stack == self.frame_stack
if self.tracer:
if retval is not None:
self.tracer.dump(' ---> %r\n' % (retval,))
if not recursive:
self.tracer.stop()
return retval
def print_traceback(self):
frames = self.traceback_frames
frames.reverse()
self.traceback_frames = []
lines = []
for frame in frames:
logline = frame.graph.name + "()"
if frame.curr_block is None:
logline += " <not running yet>"
lines.append(logline)
continue
try:
logline += " " + self.typer.annotator.annotated[frame.curr_block].func.__module__
except (KeyError, AttributeError, TypeError):
logline += " <unknown module>"
lines.append(logline)
for i, operation in enumerate(frame.curr_block.operations):
if i == frame.curr_operation_index:
logline = "E %s"
else:
logline = " %s"
lines.append(logline % (operation, ))
if self.tracer:
self.tracer.dump('Traceback\n', bold=True)
for line in lines:
self.tracer.dump(line + '\n')
for line in lines:
log.traceback(line)
def get_tlobj(self):
try:
return self._tlobj
except AttributeError:
from rpython.rtyper.lltypesystem import rffi
PERRNO = rffi.CArrayPtr(rffi.INT)
fake_p_errno = lltype.malloc(PERRNO.TO, 1, flavor='raw', zero=True,
track_allocation=False)
self._tlobj = {'RPY_TLOFS_p_errno': fake_p_errno,
#'thread_ident': ...,
}
return self._tlobj
def find_roots(self, is_minor=False):
"""Return a list of the addresses of the roots."""
#log.findroots("starting")
roots = []
for frame in reversed(self.frame_stack):
#log.findroots("graph", frame.graph.name)
frame.find_roots(roots)
# If a call is done with 'is_minor=True', we can stop after the
# first frame in the stack that was already seen by the previous
# call with 'is_minor=True'. (We still need to trace that frame,
# but not its callers.)
if is_minor:
if getattr(frame, '_find_roots_already_seen', False):
break
frame._find_roots_already_seen = True
return roots
def find_exception(self, exc):
assert isinstance(exc, LLException)
klass, inst = exc.args[0], exc.args[1]
for cls in enumerate_exceptions_top_down():
if "".join(klass.name.chars) == cls.__name__:
return cls
raise ValueError("couldn't match exception, maybe it"
" has RPython attributes like OSError?")
def get_transformed_exc_data(self, graph):
if hasattr(graph, 'exceptiontransformed'):
return graph.exceptiontransformed
if getattr(graph, 'rgenop', False):
return self.exc_data_ptr
return None
def _store_exception(self, exc):
raise PleaseOverwriteStoreException("You just invoked ll2ctypes callback without overwriting _store_exception on llinterpreter")
class PleaseOverwriteStoreException(Exception):
pass
def checkptr(ptr):
assert isinstance(lltype.typeOf(ptr), lltype.Ptr)
def checkadr(addr):
assert lltype.typeOf(addr) is llmemory.Address
class LLFrame(object):
def __init__(self, graph, args, llinterpreter):
assert not graph or isinstance(graph, FunctionGraph)
self.graph = graph
self.args = args
self.llinterpreter = llinterpreter
self.heap = llinterpreter.heap
self.bindings = {}
self.curr_block = None
self.curr_operation_index = 0
self.alloca_objects = []
def newsubframe(self, graph, args):
return self.__class__(graph, args, self.llinterpreter)
# _______________________________________________________
# variable setters/getters helpers
def clear(self):
self.bindings.clear()
def fillvars(self, block, values):
vars = block.inputargs
assert len(vars) == len(values), (
"block %s received %d args, expected %d" % (
block, len(values), len(vars)))
for var, val in zip(vars, values):
self.setvar(var, val)
def setvar(self, var, val):
if var.concretetype is not lltype.Void:
try:
val = lltype.enforce(var.concretetype, val)
except TypeError:
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)
assert isinstance(var, Variable)
self.bindings[var] = val
def setifvar(self, var, val):
if isinstance(var, Variable):
self.setvar(var, val)
def getval(self, varorconst):
try:
val = varorconst.value
except AttributeError:
val = self.bindings[varorconst]
if isinstance(val, ComputedIntSymbolic):
val = val.compute_fn()
if varorconst.concretetype is not lltype.Void:
try:
val = lltype.enforce(varorconst.concretetype, val)
except TypeError:
assert False, "type error: %r val from %r var/const" % (lltype.typeOf(val), varorconst.concretetype)
return val
# _______________________________________________________
# other helpers
def getoperationhandler(self, opname):
ophandler = getattr(self, 'op_' + opname, None)
if ophandler is None:
# try to import the operation from opimpl.py
ophandler = lloperation.LL_OPERATIONS[opname].fold
setattr(self.__class__, 'op_' + opname, staticmethod(ophandler))
return ophandler
# _______________________________________________________
# evaling functions
def eval(self):
graph = self.graph
tracer = self.llinterpreter.tracer
if tracer:
tracer.enter(graph)
self.llinterpreter.frame_stack.append(self)
try:
try:
nextblock = graph.startblock
args = self.args
while 1:
self.clear()
self.fillvars(nextblock, args)
nextblock, args = self.eval_block(nextblock)
if nextblock is None:
for obj in self.alloca_objects:
obj._obj._free()
return args
except Exception:
self.llinterpreter.traceback_frames.append(self)
raise
finally:
leavingframe = self.llinterpreter.frame_stack.pop()
assert leavingframe is self
if tracer:
tracer.leave()
def eval_block(self, block):
""" return (nextblock, values) tuple. If nextblock
is None, values is the concrete return value.
"""
self.curr_block = block
e = None
try:
for i, op in enumerate(block.operations):
self.curr_operation_index = i
self.eval_operation(op)
except LLException as e:
if op is not block.raising_op:
raise
except RuntimeError as e:
rstackovf.check_stack_overflow()
# xxx fish fish fish for proper etype and evalue to use
rtyper = self.llinterpreter.typer
bk = rtyper.annotator.bookkeeper
classdef = bk.getuniqueclassdef(rstackovf._StackOverflow)
exdata = rtyper.exceptiondata
evalue = exdata.get_standard_ll_exc_instance(rtyper, classdef)
etype = exdata.fn_type_of_exc_inst(evalue)
e = LLException(etype, evalue)
if op is not block.raising_op:
raise e
# determine nextblock and/or return value
if len(block.exits) == 0:
# return block
tracer = self.llinterpreter.tracer
if len(block.inputargs) == 2:
# exception
if tracer:
tracer.dump('raise')
etypevar, evaluevar = block.getvariables()
etype = self.getval(etypevar)
evalue = self.getval(evaluevar)
# watch out, these are _ptr's
raise LLException(etype, evalue)
resultvar, = block.getvariables()
result = self.getval(resultvar)
exc_data = self.llinterpreter.get_transformed_exc_data(self.graph)
if exc_data:
# re-raise the exception set by this graph, if any
etype = exc_data.exc_type
if etype:
evalue = exc_data.exc_value
if tracer:
tracer.dump('raise')
exc_data.exc_type = lltype.typeOf(etype)._defl()
exc_data.exc_value = lltype.typeOf(evalue)._defl()
from rpython.translator import exceptiontransform
T = resultvar.concretetype
errvalue = exceptiontransform.error_value(T)
# check that the exc-transformed graph returns the error
# value when it returns with an exception set
assert result == errvalue
raise LLException(etype, evalue)
if tracer:
tracer.dump('return')
return None, result
elif block.exitswitch is None:
# single-exit block
assert len(block.exits) == 1
link = block.exits[0]
elif block.canraise:
link = block.exits[0]
if e:
exdata = self.llinterpreter.typer.exceptiondata
cls = e.args[0]
inst = e.args[1]
for link in block.exits[1:]:
assert issubclass(link.exitcase, py.builtin.BaseException)
if self.op_direct_call(exdata.fn_exception_match,
cls, link.llexitcase):
self.setifvar(link.last_exception, cls)
self.setifvar(link.last_exc_value, inst)
break
else:
# no handler found, pass on
raise e
else:
llexitvalue = self.getval(block.exitswitch)
if block.exits[-1].exitcase == "default":
defaultexit = block.exits[-1]
nondefaultexits = block.exits[:-1]
assert defaultexit.llexitcase is None
else:
defaultexit = None
nondefaultexits = block.exits
for link in nondefaultexits:
if link.llexitcase == llexitvalue:
break # found -- the result is in 'link'
else:
if defaultexit is None:
raise ValueError("exit case %r not found in the exit links "
"of %r" % (llexitvalue, block))
else:
link = defaultexit
return link.target, [self.getval(x) for x in link.args]
def eval_operation(self, operation):
tracer = self.llinterpreter.tracer
if tracer:
tracer.dump(str(operation))
ophandler = self.getoperationhandler(operation.opname)
# XXX slighly unnice but an important safety check
if operation.opname == 'direct_call':
assert isinstance(operation.args[0], Constant)
elif operation.opname == 'indirect_call':
assert isinstance(operation.args[0], Variable)
if getattr(ophandler, 'specialform', False):
retval = ophandler(*operation.args)
else:
vals = [self.getval(x) for x in operation.args]
if getattr(ophandler, 'need_result_type', False):
vals.insert(0, operation.result.concretetype)
try:
retval = ophandler(*vals)
except LLException as e:
# safety check check that the operation is allowed to raise that
# exception
if operation.opname in lloperation.LL_OPERATIONS:
canraise = lloperation.LL_OPERATIONS[operation.opname].canraise
if Exception not in canraise:
exc = self.llinterpreter.find_exception(e)
for canraiseexc in canraise:
if issubclass(exc, canraiseexc):
break
else:
raise TypeError("the operation %s is not expected to raise %s" % (operation, exc))
# for exception-transformed graphs, store the LLException
# into the exc_data used by this graph
exc_data = self.llinterpreter.get_transformed_exc_data(
self.graph)
if exc_data:
etype = e.args[0]
evalue = e.args[1]
exc_data.exc_type = etype
exc_data.exc_value = evalue
from rpython.translator import exceptiontransform
retval = exceptiontransform.error_value(
operation.result.concretetype)
else:
raise
self.setvar(operation.result, retval)
if tracer:
if retval is None:
tracer.dump('\n')
else:
tracer.dump(' ---> %r\n' % (retval,))
def make_llexception(self, exc=None):
if exc is None:
original = sys.exc_info()
exc = original[1]
# it makes no sense to convert some exception classes that
# just mean something buggy crashed
if isinstance(exc, (AssertionError, AttributeError,
TypeError, NameError,
KeyboardInterrupt, SystemExit,
ImportError, SyntaxError)):
raise original[0], original[1], original[2] # re-raise it
# for testing the JIT (see ContinueRunningNormally) we need
# to let some exceptions introduced by the JIT go through
# the llinterpreter uncaught
if getattr(exc, '_go_through_llinterp_uncaught_', False):
raise original[0], original[1], original[2] # re-raise it
extraargs = (original,)
else:
extraargs = ()
typer = self.llinterpreter.typer
exdata = typer.exceptiondata
evalue = exdata.get_standard_ll_exc_instance_by_class(exc.__class__)
etype = self.op_direct_call(exdata.fn_type_of_exc_inst, evalue)
raise LLException(etype, evalue, *extraargs)
def invoke_callable_with_pyexceptions(self, fptr, *args):
obj = fptr._obj
try:
return obj._callable(*args)
except LLException as e:
raise
except Exception as e:
if getattr(e, '_go_through_llinterp_uncaught_', False):
raise
if getattr(obj, '_debugexc', False):
log.ERROR('The llinterpreter got an '
'unexpected exception when calling')
log.ERROR('the external function %r:' % (fptr,))
log.ERROR('%s: %s' % (e.__class__.__name__, e))
if self.llinterpreter.tracer:
self.llinterpreter.tracer.flush()
import sys
from rpython.translator.tool.pdbplus import PdbPlusShow
PdbPlusShow(None).post_mortem(sys.exc_info()[2])
self.make_llexception()
def find_roots(self, roots):
#log.findroots(self.curr_block.inputargs)
vars = []
for v in self.curr_block.inputargs:
if isinstance(v, Variable):
vars.append(v)
for op in self.curr_block.operations[:self.curr_operation_index]:
vars.append(op.result)
for v in vars:
TYPE = v.concretetype
if isinstance(TYPE, lltype.Ptr) and TYPE.TO._gckind == 'gc':
roots.append(_address_of_local_var(self, v))
# __________________________________________________________
# misc LL operation implementations
def op_debug_view(self, *ll_objects):
from rpython.translator.tool.lltracker import track
track(*ll_objects)
def op_debug_assert(self, x, msg):
if not x:
raise LLAssertFailure(msg)
def op_debug_assert_not_none(self, x):
if not x:
raise LLAssertFailure("ll_assert_not_none() failed")
def op_debug_fatalerror(self, ll_msg, ll_exc=None):
msg = ''.join(ll_msg.chars)
if ll_exc is None:
raise LLFatalError(msg)
else:
ll_exc_type = lltype.cast_pointer(rclass.OBJECTPTR, ll_exc).typeptr
raise LLFatalError(msg, LLException(ll_exc_type, ll_exc))
def op_debug_llinterpcall(self, pythonfunction, *args_ll):
try:
return pythonfunction(*args_ll)
except:
self.make_llexception()
def op_debug_forked(self, *args):
raise NotImplementedError
def op_debug_start_traceback(self, *args):
pass # xxx write debugging code here?
def op_debug_reraise_traceback(self, *args):
pass # xxx write debugging code here?
def op_debug_record_traceback(self, *args):
pass # xxx write debugging code here?
def op_debug_print_traceback(self, *args):
pass # xxx write debugging code here?
def op_debug_catch_exception(self, *args):
pass # xxx write debugging code here?
def op_jit_marker(self, *args):
pass
def op_jit_record_exact_class(self, *args):
pass
def op_jit_conditional_call(self, *args):
raise NotImplementedError("should not be called while not jitted")
def op_jit_conditional_call_value(self, *args):
raise NotImplementedError("should not be called while not jitted")
def op_get_exception_addr(self, *args):
raise NotImplementedError
def op_get_exc_value_addr(self, *args):
raise NotImplementedError
def op_instrument_count(self, ll_tag, ll_label):
pass # xxx for now
def op_keepalive(self, value):
pass
def op_hint(self, x, hints):
return x
def op_decode_arg(self, fname, i, name, vargs, vkwds):
raise NotImplementedError("decode_arg")
def op_decode_arg_def(self, fname, i, name, vargs, vkwds, default):
raise NotImplementedError("decode_arg_def")
def op_check_no_more_arg(self, fname, n, vargs):
raise NotImplementedError("check_no_more_arg")
def op_getslice(self, vargs, start, stop_should_be_None):
raise NotImplementedError("getslice") # only for argument parsing
def op_check_self_nonzero(self, fname, vself):
raise NotImplementedError("check_self_nonzero")
def op_setfield(self, obj, fieldname, fieldvalue):
# obj should be pointer
FIELDTYPE = getattr(lltype.typeOf(obj).TO, fieldname)
if FIELDTYPE is not lltype.Void:
self.heap.setfield(obj, fieldname, fieldvalue)
def op_bare_setfield(self, obj, fieldname, fieldvalue):
# obj should be pointer
FIELDTYPE = getattr(lltype.typeOf(obj).TO, fieldname)
if FIELDTYPE is not lltype.Void:
setattr(obj, fieldname, fieldvalue)
def op_getinteriorfield(self, obj, *offsets):
checkptr(obj)
ob = obj
for o in offsets:
if isinstance(o, str):
ob = getattr(ob, o)
else:
ob = ob[o]
assert not isinstance(ob, lltype._interior_ptr)
return ob
def getinneraddr(self, obj, *offsets):
TYPE = lltype.typeOf(obj).TO
addr = llmemory.cast_ptr_to_adr(obj)
for o in offsets:
if isinstance(o, str):
addr += llmemory.offsetof(TYPE, o)
TYPE = getattr(TYPE, o)
else:
addr += llmemory.itemoffsetof(TYPE, o)
TYPE = TYPE.OF
return addr, TYPE
def op_setinteriorfield(self, obj, *fieldnamesval):
offsets, fieldvalue = fieldnamesval[:-1], fieldnamesval[-1]
inneraddr, FIELD = self.getinneraddr(obj, *offsets)
if FIELD is not lltype.Void:
self.heap.setinterior(obj, inneraddr, FIELD, fieldvalue, offsets)
def op_bare_setinteriorfield(self, obj, *fieldnamesval):
offsets, fieldvalue = fieldnamesval[:-1], fieldnamesval[-1]
inneraddr, FIELD = self.getinneraddr(obj, *offsets)
if FIELD is not lltype.Void:
llheap.setinterior(obj, inneraddr, FIELD, fieldvalue)
def op_getarrayitem(self, array, index):
return array[index]
def op_setarrayitem(self, array, index, item):
# array should be a pointer
ITEMTYPE = lltype.typeOf(array).TO.OF
if ITEMTYPE is not lltype.Void:
self.heap.setarrayitem(array, index, item)
def op_bare_setarrayitem(self, array, index, item):
# array should be a pointer
ITEMTYPE = lltype.typeOf(array).TO.OF
if ITEMTYPE is not lltype.Void:
array[index] = item
def perform_call(self, f, ARGS, args):
fobj = f._obj
has_callable = getattr(fobj, '_callable', None) is not None
if hasattr(fobj, 'graph'):
graph = fobj.graph
else:
assert has_callable, "don't know how to execute %r" % f
return self.invoke_callable_with_pyexceptions(f, *args)
args_v = graph.getargs()
if len(ARGS) != len(args_v):
raise TypeError("graph with %d args called with wrong func ptr type: %r" %(len(args_v), ARGS))
for T, v in zip(ARGS, args_v):
if not lltype.isCompatibleType(T, v.concretetype):
raise TypeError("graph with %r args called with wrong func ptr type: %r" %
(tuple([v.concretetype for v in args_v]), ARGS))
frame = self.newsubframe(graph, args)
return frame.eval()
def op_direct_call(self, f, *args):
FTYPE = lltype.typeOf(f).TO
return self.perform_call(f, FTYPE.ARGS, args)
def op_indirect_call(self, f, *args):
graphs = args[-1]
args = args[:-1]
if graphs is not None:
obj = f._obj
if hasattr(obj, 'graph'):
assert obj.graph in graphs
else:
pass
#log.warn("op_indirect_call with graphs=None:", f)
return self.op_direct_call(f, *args)
def op_malloc(self, obj, flags):
flavor = flags['flavor']
zero = flags.get('zero', False)
track_allocation = flags.get('track_allocation', True)
if flavor == "stack":
result = self.heap.malloc(obj, zero=zero, flavor='raw')
self.alloca_objects.append(result)
return result
ptr = self.heap.malloc(obj, zero=zero, flavor=flavor,
track_allocation=track_allocation)
return ptr
def op_malloc_varsize(self, obj, flags, size):
flavor = flags['flavor']
zero = flags.get('zero', False)
track_allocation = flags.get('track_allocation', True)
assert flavor in ('gc', 'raw')
try:
ptr = self.heap.malloc(obj, size, zero=zero, flavor=flavor,
track_allocation=track_allocation)
return ptr
except MemoryError:
self.make_llexception()
def op_free(self, obj, flags):
assert flags['flavor'] == 'raw'
track_allocation = flags.get('track_allocation', True)
self.heap.free(obj, flavor='raw', track_allocation=track_allocation)
def op_gc_add_memory_pressure(self, size):
self.heap.add_memory_pressure(size)
def op_gc_fq_next_dead(self, fq_tag):
return self.heap.gc_fq_next_dead(fq_tag)
def op_gc_fq_register(self, fq_tag, obj):
self.heap.gc_fq_register(fq_tag, obj)
def op_gc_gettypeid(self, obj):
return lloperation.llop.combine_ushort(lltype.Signed, self.heap.gettypeid(obj), 0)
def op_shrink_array(self, obj, smallersize):
return self.heap.shrink_array(obj, smallersize)
def op_zero_gc_pointers_inside(self, obj):
raise NotImplementedError("zero_gc_pointers_inside")
def op_gc_get_stats(self, obj):
raise NotImplementedError("gc_get_stats")
def op_gc_writebarrier_before_copy(self, source, dest,
source_start, dest_start, length):
if hasattr(self.heap, 'writebarrier_before_copy'):
return self.heap.writebarrier_before_copy(source, dest,
source_start, dest_start,
length)
else:
return True
def op_getfield(self, obj, field):
checkptr(obj)
# check the difference between op_getfield and op_getsubstruct:
assert not isinstance(getattr(lltype.typeOf(obj).TO, field),
lltype.ContainerType)
return getattr(obj, field)
def op_force_cast(self, RESTYPE, obj):
from rpython.rtyper.lltypesystem import ll2ctypes
return ll2ctypes.force_cast(RESTYPE, obj)
op_force_cast.need_result_type = True
def op_cast_int_to_ptr(self, RESTYPE, int1):
return lltype.cast_int_to_ptr(RESTYPE, int1)
op_cast_int_to_ptr.need_result_type = True
def op_cast_ptr_to_int(self, ptr1):
checkptr(ptr1)
return lltype.cast_ptr_to_int(ptr1)
def op_cast_opaque_ptr(self, RESTYPE, obj):
checkptr(obj)
return lltype.cast_opaque_ptr(RESTYPE, obj)
op_cast_opaque_ptr.need_result_type = True
def op_length_of_simple_gcarray_from_opaque(self, obj):
checkptr(obj)
return lltype.length_of_simple_gcarray_from_opaque(obj)
def op_cast_ptr_to_adr(self, ptr):
checkptr(ptr)
return llmemory.cast_ptr_to_adr(ptr)
def op_cast_adr_to_int(self, adr, mode):
checkadr(adr)
return llmemory.cast_adr_to_int(adr, mode)
def op_convert_float_bytes_to_longlong(self, f):
from rpython.rlib import longlong2float
return longlong2float.float2longlong(f)
def op_weakref_create(self, v_obj):
def objgetter(): # special support for gcwrapper.py
return self.getval(v_obj)
assert self.llinterpreter.typer.getconfig().translation.rweakref
return self.heap.weakref_create_getlazy(objgetter)
op_weakref_create.specialform = True
def op_weakref_deref(self, PTRTYPE, obj):
assert self.llinterpreter.typer.getconfig().translation.rweakref
return self.heap.weakref_deref(PTRTYPE, obj)
op_weakref_deref.need_result_type = True
def op_cast_ptr_to_weakrefptr(self, obj):
assert self.llinterpreter.typer.getconfig().translation.rweakref
return llmemory.cast_ptr_to_weakrefptr(obj)
def op_cast_weakrefptr_to_ptr(self, PTRTYPE, obj):
assert self.llinterpreter.typer.getconfig().translation.rweakref
return llmemory.cast_weakrefptr_to_ptr(PTRTYPE, obj)
op_cast_weakrefptr_to_ptr.need_result_type = True
def op_gc__collect(self, *gen):
self.heap.collect(*gen)
def op_gc__collect_step(self):
return self.heap.collect_step()
def op_gc__enable(self):
self.heap.enable()
def op_gc__disable(self):
self.heap.disable()
def op_gc__isenabled(self):
return self.heap.isenabled()
def op_gc_heap_stats(self):
raise NotImplementedError
def op_gc_obtain_free_space(self, size):
raise NotImplementedError
def op_gc_can_move(self, ptr):
addr = llmemory.cast_ptr_to_adr(ptr)
return self.heap.can_move(addr)
def op_gc_thread_run(self):
self.heap.thread_run()
def op_gc_thread_start(self):
self.heap.thread_start()
def op_gc_thread_die(self):
self.heap.thread_die()
def op_gc_thread_before_fork(self):
raise NotImplementedError
def op_gc_thread_after_fork(self):
raise NotImplementedError
def op_gc_free(self, addr):
# what can you do?
pass
#raise NotImplementedError("gc_free")
def op_gc_fetch_exception(self):
raise NotImplementedError("gc_fetch_exception")
def op_gc_restore_exception(self, exc):
raise NotImplementedError("gc_restore_exception")
def op_gc_adr_of_nursery_top(self):
raise NotImplementedError
def op_gc_adr_of_nursery_free(self):
raise NotImplementedError
def op_gc_adr_of_root_stack_base(self):
raise NotImplementedError
def op_gc_adr_of_root_stack_top(self):
raise NotImplementedError
def op_gc_modified_shadowstack(self):
raise NotImplementedError
def op_gc_call_rtti_destructor(self, rtti, addr):
if hasattr(rtti._obj, 'destructor_funcptr'):
d = rtti._obj.destructor_funcptr
obptr = addr.ref()
return self.op_direct_call(d, obptr)
def op_gc_deallocate(self, TYPE, addr):
raise NotImplementedError("gc_deallocate")
def op_gc_reload_possibly_moved(self, v_newaddr, v_ptr):
assert v_newaddr.concretetype is llmemory.Address
assert isinstance(v_ptr.concretetype, lltype.Ptr)
assert v_ptr.concretetype.TO._gckind == 'gc'
newaddr = self.getval(v_newaddr)
p = llmemory.cast_adr_to_ptr(newaddr, v_ptr.concretetype)
if isinstance(v_ptr, Constant):
assert v_ptr.value == p
else:
self.setvar(v_ptr, p)
op_gc_reload_possibly_moved.specialform = True
def op_gc_identityhash(self, obj):
return lltype.identityhash(obj)
def op_gc_id(self, ptr):
PTR = lltype.typeOf(ptr)
if isinstance(PTR, lltype.Ptr):
return self.heap.gc_id(ptr)
raise NotImplementedError("gc_id on %r" % (PTR,))
def op_gc_set_max_heap_size(self, maxsize):
raise NotImplementedError("gc_set_max_heap_size")
def op_gc_asmgcroot_static(self, index):
raise NotImplementedError("gc_asmgcroot_static")
def op_gc_stack_bottom(self):
pass # marker for trackgcroot.py
def op_gc_pin(self, obj):
addr = llmemory.cast_ptr_to_adr(obj)
return self.heap.pin(addr)
def op_gc_unpin(self, obj):
addr = llmemory.cast_ptr_to_adr(obj)
self.heap.unpin(addr)
def op_gc__is_pinned(self, obj):
addr = llmemory.cast_ptr_to_adr(obj)
return self.heap._is_pinned(addr)
def op_gc_detach_callback_pieces(self):
raise NotImplementedError("gc_detach_callback_pieces")
def op_gc_reattach_callback_pieces(self):
raise NotImplementedError("gc_reattach_callback_pieces")
def op_gc_get_type_info_group(self):
raise NotImplementedError("gc_get_type_info_group")
def op_gc_get_rpy_memory_usage(self):
raise NotImplementedError("gc_get_rpy_memory_usage")
def op_gc_get_rpy_roots(self):
raise NotImplementedError("gc_get_rpy_roots")
def op_gc_get_rpy_referents(self):
raise NotImplementedError("gc_get_rpy_referents")
def op_gc_is_rpy_instance(self):
raise NotImplementedError("gc_is_rpy_instance")
def op_gc_get_rpy_type_index(self):
raise NotImplementedError("gc_get_rpy_type_index")
def op_gc_dump_rpy_heap(self):
raise NotImplementedError("gc_dump_rpy_heap")
def op_gc_typeids_z(self):
raise NotImplementedError("gc_typeids_z")
def op_gc_typeids_list(self):
raise NotImplementedError("gc_typeids_list")
def op_gc_gcflag_extra(self, subopnum, *args):
return self.heap.gcflag_extra(subopnum, *args)
def op_gc_rawrefcount_init(self, *args):
raise NotImplementedError("gc_rawrefcount_init")
def op_gc_rawrefcount_to_obj(self, *args):
raise NotImplementedError("gc_rawrefcount_to_obj")
def op_gc_rawrefcount_from_obj(self, *args):
raise NotImplementedError("gc_rawrefcount_from_obj")
def op_gc_rawrefcount_create_link_pyobj(self, *args):
raise NotImplementedError("gc_rawrefcount_create_link_pyobj")
def op_gc_rawrefcount_create_link_pypy(self, *args):
raise NotImplementedError("gc_rawrefcount_create_link_pypy")
def op_gc_rawrefcount_mark_deallocating(self, *args):
raise NotImplementedError("gc_rawrefcount_mark_deallocating")
def op_gc_rawrefcount_next_dead(self, *args):
raise NotImplementedError("gc_rawrefcount_next_dead")
def op_do_malloc_fixedsize(self):
raise NotImplementedError("do_malloc_fixedsize")
def op_do_malloc_fixedsize_clear(self):
raise NotImplementedError("do_malloc_fixedsize_clear")
def op_do_malloc_varsize(self):
raise NotImplementedError("do_malloc_varsize")
def op_do_malloc_varsize_clear(self):
raise NotImplementedError("do_malloc_varsize_clear")
def op_get_write_barrier_failing_case(self):
raise NotImplementedError("get_write_barrier_failing_case")