forked from static-analysis-engineering/CodeHawk-Binary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractSyntaxTree.py
More file actions
1681 lines (1428 loc) · 61.6 KB
/
AbstractSyntaxTree.py
File metadata and controls
1681 lines (1428 loc) · 61.6 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
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2021-2024 Aarno Labs LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ------------------------------------------------------------------------------
"""Construction of abstract syntax tree."""
import json
from typing import (
Any,
Callable,
cast,
Dict,
List,
Mapping,
NewType,
Optional,
Sequence,
Set,
Tuple,
TYPE_CHECKING,
Union)
import chb.ast.ASTNode as AST
from chb.ast.ASTProvenance import ASTProvenance
from chb.ast.ASTSerializer import ASTSerializer
from chb.ast.ASTBasicCTyper import ASTBasicCTyper
from chb.ast.ASTReturnSequences import ASTReturnSequences
from chb.ast.ASTStorage import (
ASTStorage,
ASTRegisterStorage,
ASTFlagStorage,
ASTStackStorage,
ASTBaseStorage,
ASTGlobalStorage,
ASTStorageConstructor)
from chb.ast.ASTSymbolTable import (
ASTGlobalSymbolTable, ASTSymbolTable, ASTLocalSymbolTable)
ASTSpanRecord = NewType(
"ASTSpanRecord", Dict[str, Union[int, List[Dict[str, Union[str, int]]]]])
nooffset = AST.ASTNoOffset()
voidtype = AST.ASTTypVoid()
class AbstractSyntaxTree:
def __init__(
self,
faddr: str,
fname: str,
localsymboltable: ASTLocalSymbolTable,
returnsequences: Optional[ASTReturnSequences] = None,
registersizes: Dict[str, int] = {},
flagnames: List[str] = [],
defaultsize: Optional[int] = None) -> None:
self._faddr = faddr
self._fname = fname # same as faddr if no name provided
self._stmtid_counter = 1
self._instrid_counter = 1
self._locationid_counter = 1
self._lval_counter = 1
self._expr_counter = 1
self._tmpcounter = 0
self._spans: List[ASTSpanRecord] = []
self._storage: Dict[int, ASTStorage] = {}
self._available_expressions: Dict[str, Dict[str, Tuple[int, int, str]]] = {}
self._symboltable = localsymboltable
self._returnsequences = returnsequences
self._storageconstructor = ASTStorageConstructor(
registersizes, defaultsize, flagnames)
self._provenance = ASTProvenance()
self._serializer = ASTSerializer()
# integer types
self._char_type = self.mk_integer_ikind_type("ichar")
self._signed_char_type = self.mk_integer_ikind_type("ischar")
self._unsigned_char_type = self.mk_integer_ikind_type("iuchar")
self._bool_type = self.mk_integer_ikind_type("ibool")
self._int_type = self.mk_integer_ikind_type("iint")
self._unsigned_int_type = self.mk_integer_ikind_type("iuint")
self._short_type = self.mk_integer_ikind_type("ishort")
self._unsigned_short_type = self.mk_integer_ikind_type("iushort")
self._long_type = self.mk_integer_ikind_type("ilong")
self._unsigned_long_type = self.mk_integer_ikind_type("iulong")
self._long_long_type = self.mk_integer_ikind_type("ilonglong")
self._unsigned_long_long_type = self.mk_integer_ikind_type("iulonglong")
# float types
self._float_type = self.mk_float_fkind_type("float")
self._double_type = self.mk_float_fkind_type("fdouble")
self._long_double_type = self.mk_float_fkind_type("flongdouble")
@property
def fname(self) -> str:
return self._fname
@property
def faddr(self) -> str:
return self._faddr
@property
def symboltable(self) -> ASTLocalSymbolTable:
return self._symboltable
@property
def globalsymboltable(self) -> ASTGlobalSymbolTable:
return self.symboltable.globaltable
@property
def returnsequences(self) -> Optional[ASTReturnSequences]:
return self._returnsequences
@property
def compinfos(self) -> Mapping[int, AST.ASTCompInfo]:
return self.symboltable.compinfos
@property
def enuminfos(self) -> Mapping[str, AST.ASTEnumInfo]:
return self.symboltable.enuminfos
@property
def provenance(self) -> ASTProvenance:
return self._provenance
@property
def serializer(self) -> ASTSerializer:
return self._serializer
@property
def spans(self) -> List[ASTSpanRecord]:
return self._spans
@property
def storage(self) -> Dict[int, ASTStorage]:
return self._storage
@property
def available_expressions(
self) -> Dict[str, Dict[str, Tuple[int, int, str]]]:
return self._available_expressions
def set_available_expressions(
self,
aexprs: Dict[str, Dict[str, Tuple[int, int, str]]]) -> None:
self._available_expressions = aexprs
def storage_records(self) -> Dict[int, Dict[str, Union[str, int]]]:
results: Dict[int, Dict[str, Union[str, int]]] = {}
for (lvalid, record) in self.storage.items():
results[lvalid] = record.serialize()
return results
@property
def storageconstructor(self) -> ASTStorageConstructor:
return self._storageconstructor
def set_function_prototype(self, p: AST.ASTVarInfo) -> None:
self.symboltable.set_function_prototype(p)
def has_function_prototype(self) -> bool:
return self.symboltable.has_function_prototype()
@property
def function_prototype(self) -> Optional[AST.ASTVarInfo]:
return self.symboltable.function_prototype
def has_symbol(self, name: str) -> bool:
return self.symboltable.has_symbol(name)
def get_symbol(self, name: str) -> AST.ASTVarInfo:
return self.symboltable.get_symbol(name)
def add_symbol(
self,
name: str,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
globaladdress: Optional[int] = None,
ssa: bool = False,
vdescr: Optional[str] = None) -> AST.ASTVarInfo:
return self.symboltable.add_symbol(
name,
vtype=vtype,
parameter=parameter,
globaladdress=globaladdress,
ssa=ssa,
vdescr=vdescr)
def add_compinfo(self, cinfo: AST.ASTCompInfo) -> None:
self.symboltable.add_compinfo(cinfo)
def add_enuminfo(self, einfo: AST.ASTEnumInfo) -> None:
self.symboltable.add_enuminfo(einfo)
def add_return_sequence(
self,
hexstring: str,
assembly: List[str],
address: str) -> None:
if self.returnsequences is None:
print("Return sequences not initialized; return sequence ignored")
else:
self.returnsequences.add_return_sequence(hexstring, assembly, address)
def serialize_return_sequences(self) -> Dict[str, str]:
if self.returnsequences is None:
return {}
else:
return self.returnsequences.serialize()
def new_stmtid(self) -> int:
"""Return a new id for statements."""
stmtid = self._stmtid_counter
self._stmtid_counter += 1
return stmtid
def get_stmtid(self, stmtid: Optional[int]) -> int:
return self.new_stmtid() if stmtid is None else stmtid
def new_instrid(self) -> int:
"""Return a new id for instructions."""
instrid = self._instrid_counter
self._instrid_counter += 1
return instrid
def get_instrid(self, instrid: Optional[int]) -> int:
return self.new_instrid() if instrid is None else instrid
def new_locationid(self) -> int:
"""Return a new location id for statements/labels/instructions."""
locationid = self._locationid_counter
self._locationid_counter += 1
return locationid
def get_locationid(self, locationid: Optional[int]) -> int:
return self.new_locationid() if locationid is None else locationid
def new_lvalid(self) -> int:
"""Return a new lval id for lvalues."""
lvalid = self._lval_counter
self._lval_counter += 1
return lvalid
def get_lvalid(self, lvalid: Optional[int]) -> int:
return self.new_lvalid() if lvalid is None else lvalid
def new_exprid(self) -> int:
"""Return a new expression id."""
exprid = self._expr_counter
self._expr_counter += 1
return exprid
def get_exprid(self, exprid: Optional[int]) -> int:
return self.new_exprid() if exprid is None else exprid
def add_span(self, span: ASTSpanRecord) -> None:
self._spans.append(span)
def add_stmt_span(
self, locationid: int, spans: List[Tuple[str, str]]) -> None:
"""Add a span for the ast instructions contained in a stmt.
Note: this is currently done only for if statements originating from
predicated instructions.
"""
spaninstances: List[Dict[str, Union[str, int]]] = []
for (iaddr, bytestring) in spans:
span: Dict[str, Union[str, int]] = {}
span["base_va"] = iaddr
span["size"] = len(bytestring) // 2
spaninstances.append(span)
spanrec: Dict[str, Any] = {}
spanrec["locationid"] = locationid
spanrec["spans"] = spaninstances
self.add_span(cast(ASTSpanRecord, spanrec))
def add_instruction_span(
self, locationid: int, base: str, bytestring: str) -> None:
"""Add a span for an ast instruction."""
span: Dict[str, Union[str, int]] = {}
span["base_va"] = base
span["size"] = len(bytestring) // 2
spanrec: Dict[str, Any] = {}
spanrec["locationid"] = locationid
spanrec["spans"] = [span]
self.add_span(cast(ASTSpanRecord, spanrec))
def add_expr_span(
self, exprid: int, base: str, bytestring: str) -> None:
"""Add a span for an assembly instruction without ast instruction.
The expression span provides a link between assembly instructions
that do not (or may not) have an associated instruction in the ast
such as return statements and conditional jumps.
If these assembly instructions involve an expression (such as the
return value or the branch condition) then the expression id of the
associated ast expression can be used to establish the link to the
relevant assembly instruction.
"""
if exprid in self.expr_spanmap():
return
span: Dict[str, Union[str, int]] = {}
span["base_va"] = base
span["size"] = len(bytestring) // 2
spanrec: Dict[str, Any] = {}
spanrec["exprid"] = exprid
spanrec["spans"] = [span]
self.add_span(cast(ASTSpanRecord, spanrec))
def spanmap(self) -> Dict[int, str]:
"""Return mapping from locationid to instruction base address."""
result: Dict[int, str] = {}
for spanrec in self.spans:
if "locationid" in spanrec:
spanlocationid = cast(int, spanrec["locationid"])
spans_at_xref = cast(List[Dict[str, Any]], spanrec["spans"])
result[spanlocationid] = spans_at_xref[0]["base_va"]
return result
def expr_spanmap(self) -> Dict[int, str]:
"""Return mapping from exprid to related instruction base address."""
result: Dict[int, str] = {}
for spanrec in self.spans:
if "exprid" in spanrec:
spanexprid = cast(int, spanrec["exprid"])
spans_at_xref = cast(List[Dict[str, Any]], spanrec["spans"])
result[spanexprid] = spans_at_xref[0]["base_va"]
return result
# ------------------------------------------------------ make statements ---
def mk_block(
self,
stmts: List[AST.ASTStmt],
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = []) -> AST.ASTBlock:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTBlock(stmtid, locationid, stmts, labels=labels)
def mk_return_stmt(
self,
expr: Optional[AST.ASTExpr],
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = []) -> AST.ASTReturn:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTReturn(stmtid, locationid, expr, labels=labels)
def mk_loop(
self,
body: AST.ASTStmt,
mergeaddr: Optional[str] = None,
continueaddr: Optional[str] = None,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None) -> AST.ASTLoop:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTLoop(stmtid, locationid, mergeaddr, continueaddr, body)
def mk_break_stmt(
self,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None) -> AST.ASTBreak:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTBreak(stmtid, locationid)
def mk_continue_stmt(
self,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None) -> AST.ASTContinue:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTContinue(stmtid, locationid)
def mk_branch(
self,
condition: Optional[AST.ASTExpr],
ifbranch: AST.ASTStmt,
elsebranch: AST.ASTStmt,
targetaddr: str,
mergeaddr: Optional[str] = None,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = [],
predicated: Optional[int] = None) -> AST.ASTBranch:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
if condition is None:
# create a new unknown (uninitialized) variable
condition = self.mk_tmp_lval_expression()
return AST.ASTBranch(
stmtid, locationid, condition, ifbranch, elsebranch,
targetaddr, mergeaddr, predicated=predicated)
def mk_goto_stmt(
self,
destinationlabel: str,
destinationaddr: str,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = []) -> AST.ASTGoto:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTGoto(
stmtid, locationid, destinationlabel, destinationaddr, labels)
def mk_computed_goto_stmt(
self,
targetexpr: AST.ASTExpr,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = []) -> AST.ASTComputedGoto:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTComputedGoto(stmtid, locationid, targetexpr, labels)
def mk_switch_stmt(
self,
switchexpr: Optional[AST.ASTExpr],
cases: AST.ASTStmt,
mergeaddr: Optional[str] = None,
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = []) -> AST.ASTSwitchStmt:
if switchexpr is None:
# create a new unknown (uninitialized) variable
switchexpr = self.mk_tmp_lval_expression()
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTSwitchStmt(
stmtid, locationid, switchexpr, cases,
mergeaddr=mergeaddr, labels=labels)
def mk_instr_sequence(
self,
instrs: List[AST.ASTInstruction],
optstmtid: Optional[int] = None,
optlocationid: Optional[int] = None,
labels: List[AST.ASTStmtLabel] = []) -> AST.ASTInstrSequence:
stmtid = self.get_stmtid(optstmtid)
locationid = self.get_locationid(optlocationid)
return AST.ASTInstrSequence(stmtid, locationid, instrs, labels=labels)
"""Labels
Labels can be associated with statements. They represent both to mark
a location in the control-flow, for example serving as the destination
of a goto statement, and to specify case label in a switch statement.
Labels have a locationid associated with them.
Construction methods provided:
------------------------------
- mk_label: creates a marker label with a name that can be used as the
destination of a goto statement
- mk_case_label: creates a case label for a switch statement with a
case expression
- mk_case_range_label: creates a case label for a switch statement with
a range of expressions, expressed as lowexpr and a highexpr
(this is a gcc extension, not part of the C standard)
- mk_default_label: creates a default label for a switch statement.
"""
def mk_label(
self, name: str,
optlocationid: Optional[int] = None) -> AST.ASTLabel:
locationid = self.get_locationid(optlocationid)
return AST.ASTLabel(locationid, name)
def mk_case_label(
self,
expr: Optional[AST.ASTExpr],
optlocationid: Optional[int] = None) -> AST.ASTCaseLabel:
locationid = self.get_locationid(optlocationid)
if expr is None:
# create an (uninitialized) temporary variable
expr = self.mk_tmp_lval_expression()
return AST.ASTCaseLabel(locationid, expr)
def mk_case_range_label(
self,
lowexpr: AST.ASTExpr,
highexpr: AST.ASTExpr,
optlocationid: Optional[int] = None) -> AST.ASTCaseRangeLabel:
locationid = self.get_locationid(optlocationid)
return AST.ASTCaseRangeLabel(locationid, lowexpr, highexpr)
def mk_default_label(
self, optlocationid: Optional[int] = None) -> AST.ASTDefaultLabel:
locationid = self.get_locationid(optlocationid)
return AST.ASTDefaultLabel(locationid)
"""Instructions
There are two types of instructions: an assignment and a call. An
assignment consists of a lhs (lval) and a rhs (expression). A call consists
of an optional lhs (lval) to which the return value from the call is
assigned, an expression that is the target of the call (an lval expression
of a variable of type function in case of a direct call, or any other
expression in case of an indirect call), and a list of expressions that
represent the arguments to the call (preferably in conformance with the
arity of the function type, but this is not checked).
Instructions are assigned a unique assembly cross reference, assembly_xref.
This cross reference can then be used to create a link with the instruction
address (via the span) if desired. If an assembly_xref was assigned earlier
(e.g., when constructing an ast from an existing ast json file) it can be
given as an optional argument.
Construction methods provided:
------------------------------
- mk_assign: creates an assignment from a lhs (lval) and rhs (expression)
- mk_call: creates a call from an optional lhs (lval), a target (expression),
and a list of arguments (expressions)
- mk_var_assign: creates an assignment from a variable name and rhs
(expression); an lval with the given name is created (as described
below under Variables)
- mk_var_var_assign: creates an assignment from one variable name to another
variable name; an lval and lval-expression for the two variables is
created (as described below under Variables)
- mk_var_call: creates a call instruction with a variable name as lhs argument
- mk_tgt_call: creates a call instruction with a function name as tgt expression
- mk_default_call: creates a call instruction with only a function name and
arguments, and optionally a type for the function name; this method tries
to determine if the function has a return value (i.e., does not return
void). If so it will create a tmp variable with a description that
indicates this variable holds a return value from the named function,
if the function has void return type, the lval is set to None.
Note: if function prototypes are available before creating call instructions
it is preferable that they be entered in the symbol table up front.
"""
def mk_assign(
self,
lval: AST.ASTLval,
rhs: AST.ASTExpr,
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTAssign:
instrid = self.get_instrid(optinstrid)
locationid = self.get_locationid(optlocationid)
for ll_instrid in low_level_instrids:
self.provenance.add_instruction_mapping(instrid, ll_instrid)
return AST.ASTAssign(instrid, locationid, lval, rhs)
def mk_var_assign(
self,
vname: str,
rhs: AST.ASTExpr,
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTAssign:
lval = self.mk_named_lval(vname)
return self.mk_assign(
lval,
rhs,
optinstrid=optinstrid,
optlocationid=optlocationid,
low_level_instrids=low_level_instrids)
def mk_var_var_assign(
self,
vname: str,
rhsname: str,
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTAssign:
rhs = self.mk_named_lval_expression(vname)
return self.mk_var_assign(
vname,
rhs,
optinstrid,
optlocationid,
low_level_instrids=low_level_instrids)
def mk_call(
self,
lval: Optional[AST.ASTLval],
tgt: AST.ASTExpr,
args: List[AST.ASTExpr],
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTCall:
instrid = self.get_instrid(optinstrid)
locationid = self.get_locationid(optlocationid)
for ll_instrid in low_level_instrids:
self.provenance.add_instruction_mapping(instrid, ll_instrid)
return AST.ASTCall(instrid, locationid, lval, tgt, args)
def mk_asm(
self,
vola: bool,
templates: List[str],
clobbers: List[str],
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTAsm:
instrid = self.get_instrid(optinstrid)
locationid = self.get_locationid(optlocationid)
for ll_instrid in low_level_instrids:
self.provenance.add_instruction_mapping(instrid, ll_instrid)
return AST.ASTAsm(instrid, locationid, vola, templates, clobbers)
def mk_var_call(
self,
vname: str,
tgt: AST.ASTExpr,
args: List[AST.ASTExpr],
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTCall:
lval = self.mk_named_lval(vname)
return self.mk_call(
lval,
tgt,
args,
optinstrid=optinstrid,
optlocationid=optlocationid,
low_level_instrids=low_level_instrids)
def mk_tgt_call(
self,
lval: Optional[AST.ASTLval],
tgtname: str,
args: List[AST.ASTExpr],
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTCall:
tgtexpr = self.mk_named_lval_expression(tgtname)
return self.mk_call(
lval,
tgtexpr,
args,
optinstrid=optinstrid,
optlocationid=optlocationid,
low_level_instrids=low_level_instrids)
def mk_default_call(
self,
tgtvname: str,
args: List[AST.ASTExpr],
tgtvtype: Optional[AST.ASTTyp] = None,
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTCall:
tgtvinfo = self.mk_vinfo(tgtvname, vtype=tgtvtype)
lval: Optional[AST.ASTLval] = None
if (
tgtvinfo.vtype is not None
and tgtvinfo.vtype.is_function):
tgttyp = cast(AST.ASTTypFun, tgtvinfo.vtype)
if tgttyp.is_void:
lval = None
else:
lval = self.mk_tmp_lval(vdescr="return value from " + tgtvname)
tgtexpr = self.mk_vinfo_lval_expression(tgtvinfo)
return self.mk_call(
lval,
tgtexpr,
args,
optinstrid=optinstrid,
optlocationid=optlocationid,
low_level_instrids=low_level_instrids)
def mk_nop_instruction(
self,
descr: str,
optinstrid: Optional[int] = None,
optlocationid: Optional[int] = None,
low_level_instrids: List[int] = []) -> AST.ASTNOPInstruction:
instrid = self.get_instrid(optinstrid)
locationid = self.get_locationid(optlocationid)
for ll_instrid in low_level_instrids:
self.provenance.add_instruction_mapping(instrid, ll_instrid)
return AST.ASTNOPInstruction(instrid, locationid, descr)
"""Variables
Variables have a name. For named variables it is the user's responsibility
to ensure that distinct variables (i.e. distinct storage locations) have
distinct names (within a function) and that distinct global variables have
distinct names (across all functions). Local variables in different\
functions may have the same name (functions have different name spaces).
The basic data structure for a variable is the ASTVarInfo, which holds the
name, type (optional), the parameter index (zero-based) if the variable is
a formal parameter to a function, the global address (optional) if the
address is known, and an optional description of what the variable holds.
The varinfo is stored in the local or global symbol table on first creation.
The first creation of the varinfo determines the associate data. Once a
variable exists (either in the global symbol or local symbol table)
subsequent calls to create a variable with the same name (in the same name
space result in retrieval of the existing varinfo rather than creating a
new one, thereby ignoring the associate data provided.
Only one instance exists of the ASTVarInfo data structure, held in the
symboltable for each name. Multiple instances of related ASTVariable,
ASTLval, and ASTLvalExpr may exist within the abstract syntax tree structure
(these will all be collapsed into one by the serializer).
Temporary variables are automatically given unique names.
Construction methods provided:
------------------------------
- mk_vinfo : creates/returns a varinfo data structure from the symboltable
a vinfo is considered global if (1) it has a global address, or (2) its
type is a function type.
A vinfo can be forced global by giving it a global address of 0, if the
actual address is not known.
- mk_vinfo_variable: creates/returns a variable from a vinfo
- mk_lval: creates/returns an lval from an lhost and an offset
- mk_vinfo_lval: creates/returns an lval (lhs) (with optional offset) from
a vinfo
- mk_vinfo_lval_expression: creates/returns an lval-expression (rhs) (with
optional offset) from a vinfo
- mk_named_variable: creates a variable with the given a name (and will
implicitly create a varinfo, if necessary)
- mk_named_lval: creates an lval (lhs) (with optional offset) with the given
name
- mk_named_lval_expression: creates an lval expression (rhs) (with optional
offset) with the given name
- mk_tmp_variable: creates a new varinfo/variable with a unique name
- mk_tmp_lval: creates a new varinfo/lval (lhs) with a unique name
- mk_tmp_lval_expression: creates new varinfo/lval-expression (rhs) with a
unique name
"""
def mk_vinfo(
self,
vname: str,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
globaladdress: Optional[int] = None,
llref: bool = False,
vdescr: Optional[str] = None) -> AST.ASTVarInfo:
if (
(globaladdress is not None)
or (vtype and vtype.is_function)):
vinfo = self.symboltable.add_global_symbol(
vname,
vtype=vtype,
globaladdress=globaladdress,
llref=llref,
vdescr=vdescr)
else:
vinfo = self.symboltable.add_symbol(
vname,
vtype=vtype,
parameter=parameter,
vdescr=vdescr)
return vinfo
def mk_vinfo_main_function(self, gaddr: str) -> AST.ASTVarInfo:
"""Return the prototype for the main function."""
vtype = self.mk_funtyp_main_function()
return self.mk_vinfo(
"main",
vtype=vtype,
globaladdress=int(gaddr, 16),
vdescr="main function prototype")
def mk_vinfo_variable(self, vinfo: AST.ASTVarInfo) -> AST.ASTVariable:
return AST.ASTVariable(vinfo)
def mk_lval(
self,
lhost: AST.ASTLHost,
offset: AST.ASTOffset,
optlvalid: Optional[int] = None,
storage: Optional[ASTStorage] = None) -> AST.ASTLval:
lvalid = self.get_lvalid(optlvalid)
if storage is not None:
self.storage[lvalid] = storage
return AST.ASTLval(lvalid, lhost, offset)
def mk_vinfo_lval(
self,
vinfo: AST.ASTVarInfo,
offset: AST.ASTOffset = nooffset,
optlvalid: Optional[int] = None,
storage: Optional[ASTStorage] = None) -> AST.ASTLval:
var = self.mk_vinfo_variable(vinfo)
return self.mk_lval(
var,
offset,
optlvalid=optlvalid,
storage=storage)
def mk_vinfo_lval_expression(
self,
vinfo: AST.ASTVarInfo,
offset: AST.ASTOffset = nooffset,
optlvalid: Optional[int] = None,
optexprid: Optional[int] = None,
storage: Optional[ASTStorage] = None) -> AST.ASTLvalExpr:
lval = self.mk_vinfo_lval(
vinfo,
offset,
optlvalid=optlvalid,
storage=storage)
exprid = self.get_exprid(optexprid)
return AST.ASTLvalExpr(exprid, lval)
def mk_named_variable(
self,
vname: str,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
globaladdress: Optional[int] = None,
llref: bool = False,
vdescr: Optional[str] = None) -> AST.ASTVariable:
vinfo = self.mk_vinfo(
vname,
vtype=vtype,
parameter=parameter,
globaladdress=globaladdress,
llref=llref,
vdescr=vdescr)
return self.mk_vinfo_variable(vinfo)
def mk_named_lval(
self,
vname: str,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
globaladdress: Optional[int] = None,
llref: bool = False,
vdescr: Optional[str] = None,
offset: AST.ASTOffset = nooffset,
optlvalid: Optional[int] = None,
storage: Optional[ASTStorage] = None,
anonymous: bool = False) -> AST.ASTLval:
var = self.mk_named_variable(
vname,
vtype=vtype,
parameter=parameter,
globaladdress=globaladdress,
llref=llref,
vdescr=vdescr)
if optlvalid is None and anonymous:
optlvalid = -1
return self.mk_lval(
var,
offset,
optlvalid=optlvalid,
storage=storage)
def mk_register_variable_lval(
self,
name: str,
registername: Optional[str] = None,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
vdescr: Optional[str] = None,
optlvalid: Optional[int] = None) -> AST.ASTLval:
if registername is None:
registername = name
storage = self.storageconstructor.mk_register_storage(registername)
return self.mk_named_lval(
name,
vtype=vtype,
parameter=parameter,
vdescr=vdescr,
storage=storage,
optlvalid=optlvalid)
def mk_register_variable_lval_expression(
self,
name: str,
registername: Optional[str] = None,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
vdescr: Optional[str] = None,
optlvalid: Optional[int] = None,
optexprid: Optional[int] = None) -> AST.ASTLvalExpr:
lval = self.mk_register_variable_lval(
name,
registername=registername,
vtype=vtype,
parameter=parameter,
vdescr=vdescr,
optlvalid=optlvalid)
exprid = self.get_exprid(optexprid)
return AST.ASTLvalExpr(exprid, lval)
def mk_flag_variable_lval(
self,
name: str,
flagname: Optional[str] = None,
vdescr: Optional[str] = None,
optlvalid: Optional[int] = None) -> AST.ASTLval:
if flagname is None:
flagname = name
storage = self.storageconstructor.mk_flag_storage(flagname)
return self.mk_named_lval(
name,
storage=storage,
optlvalid=optlvalid)
def mk_flag_variable_lval_expression(
self,
name: str,
flagname: Optional[str] = None,
vdescr: Optional[str] = None,
optlvalid: Optional[int] = None,
optexprid: Optional[int] = None) -> AST.ASTLvalExpr:
lval = self.mk_flag_variable_lval(
name, flagname=flagname, vdescr=vdescr, optlvalid=optlvalid)
exprid = self.get_exprid(optexprid)
return AST.ASTLvalExpr(exprid, lval)
def mk_stack_variable_lval(
self,
name: str,
offset: int,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
vdescr: Optional[str] = None,
size: Optional[int] = None,
optlvalid: Optional[int] = None) -> AST.ASTLval:
storage = self.storageconstructor.mk_stack_storage(offset, size)
return self.mk_named_lval(
name,
vtype=vtype,
parameter=parameter,
vdescr=vdescr,
storage=storage,
optlvalid=optlvalid)
def mk_named_lval_expression(
self,
vname: str,
vtype: Optional[AST.ASTTyp] = None,
parameter: Optional[int] = None,
globaladdress: Optional[int] = None,
llref: bool = False,
vdescr: Optional[str] = None,
offset: AST.ASTOffset = nooffset,
optlvalid: Optional[int] = None,
optexprid: Optional[int] = None,
storage: Optional[ASTStorage] = None,
anonymous: bool = False) -> AST.ASTLvalExpr:
if optlvalid is None and anonymous:
optlvalid = -1
lval = self.mk_named_lval(
vname,
vtype=vtype,