-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathevaluator.py
More file actions
1552 lines (1356 loc) · 80.9 KB
/
evaluator.py
File metadata and controls
1552 lines (1356 loc) · 80.9 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
"""Perform a detailed evaluation of idioms.
"""
import warnings
import argparse
import functools
import random
import json
import sys
import re
import time
import tempfile
import subprocess
import itertools
from collections import Counter
from pathlib import Path
from typing import Iterable, Callable, TypeVar, Any, Container
import z3
import torch
from torch.utils.data import DataLoader
import tree_sitter_c
from tree_sitter import Node, Parser, Language
from nltk.translate.bleu_score import sentence_bleu
import numpy as np
from datasets import load_from_disk, Dataset, DatasetDict
from numpy.typing import NDArray
from tqdm import tqdm
from peft import PeftModel # type: ignore # mypy thinks that PeftModel is a private class.
from pygments.lexers.c_cpp import CLexer
from pygments.token import Whitespace
from transformers import (
PreTrainedTokenizerBase,
PreTrainedModel,
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig
)
from prepare import (
Scope,
FileTypeMapping,
PreprocessedFunction,
get_all_user_defined_types,
has_error,
get_child,
TypeNotDefinedError,
TypeNotFoundError,
UnsupportedFeatureError,
TypeNotFoundError
)
from idioms.data.dataset import MatchedFunction, MatchedBinary
from idioms.data.types import *
from idioms.dataiter import MatchedBinaryDataset, MatchedBinaryFunctionWrapper
from idioms.hf import (
causal_stringify_binary_prompt,
causal_stringify_neighbors_prompt,
causal_stringify_function_prompt,
DECOMPILED_ORIG_SEP
)
from codealign import align, Alignment
from codealign.ir import (
Variable,
Parameter,
GlobalVariable,
SSAOperator,
FunctionSSAOperator,
FunctionVarOperator,
STORE_OP
)
from codealign.align import UnionFind
from codealign.lang.c import ParsingError, SemanticError, parse
ADAPTER_NAME="decomp_fn_rewrite"
ORIGINAL_EXAMPLE_ATTR = "raw_exebench_example"
GENERIC_FUNCTION_NAME = "func_"
GENERIC_FIELD_NAME = "field_"
AGGREGATE_SOLVER_TIMEOUT = 60 # seconds
C_LANGUAGE = Language(tree_sitter_c.language())
parser = Parser(C_LANGUAGE)
T = TypeVar("T")
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("checkpoint", type=str, help="The directory produced by training a model, or a huggingface model ID")
parser.add_argument("--dataset", type=str, help="The path to the evaluation dataset. If not specified, will use the dataset specified for training.")
parser.add_argument("--evaluate-existing-predictions", action="store_true", help="load predictions from the predictions JSON file instead of recalculating them.")
parser.add_argument("--eval-partition", choices=["test", "validation"], default="validation", help="The dataset partition to use.")
parser.add_argument("--exebench-subpartition", choices=["real", "synth"], default="real", help="Which partition of the exebench evaluation sets to use: synth or real.")
parser.add_argument("--batch-size", type=int, default=1, help="Batch size during prediction.")
parser.add_argument("--max-context-length", type=int, default=None, help="The maximum length of the pre-prediction context (the decompiled information, including neighboring functions in neighbors mode.)")
parser.add_argument("--max-decompiled-function-size", type=int, default=1024, help="Filter out any any functions with more than this many decompiled tokens.")
parser.add_argument("--max-prediction-length", type=int, default=1024, help="The maximum number of new tokens to be predicted for the original function code and UDT definitions.")
parser.add_argument("--random-seed", type=int, default=80, help=f"Used to seed python's standard random module.")
parser.add_argument("--limit", type=int, help="Only predict this many examples instead of all of them.")
parser.add_argument("--no-exebench-tests", action="store_true", help="Don't execute exebench tests")
parser.add_argument("--missing-predictions-only", action="store_true", help="Only generate predictions for examples that aren't in the original predictions file.")
return parser.parse_args()
class FunctionEvaluator:
def __init__(self, write_output_to: Path | None = None):
self.metric_names: list[str] = [
"bleu",
"syntatically_valid",
"semantically_valid",
"consistently_aligned",
"perfectly_aligned",
"perfectly_aligned_and_typechecks",
"variable_name_accuracy",
"variable_type_accuracy",
"variable_udt_exact_matches",
"variable_udt_composition_matches",
"variables_inherently_alignable",
"oracle_has_nonexistent_field",
"codealign_failures",
"consistency_solver_timeouts"
]
self.write_output_to = write_output_to
self.lexer = CLexer()
def bleu(self, f: MatchedFunction, prediction: str) -> float:
original_tokens: list[str] = [t[1] for t in self.lexer.get_tokens(f.canonical_original_code) if t[0] is not Whitespace]
predicted_tokens: list[str] = [t[1] for t in self.lexer.get_tokens(prediction) if t[0] is not Whitespace]
with warnings.catch_warnings(action="ignore"): # there's a warning when there's no overlaps of a certain n-gram type, which is normal when predictions are poor early in training.
return sentence_bleu([original_tokens], predicted_tokens) # type: ignore (sentence_bleu's type hints are wrong.)
def __iter__(self) -> Iterable[str]:
return iter(self.metric_names)
def __call__(self, predictions: Iterable[tuple[MatchedFunction, str]]) -> dict[str, float]:
if self.write_output_to is not None and not isinstance(predictions, list):
self.predictions = list(predictions)
errors_during_evaluation = 0
metric_values = {m: list() for m in self.metric_names}
for ground_truth, prediction in tqdm(predictions):
metric_values["bleu"].append(self.bleu(ground_truth, prediction))
try:
for metric, value in self.get_analysis_metrics(ground_truth, prediction).items():
metric_values[metric].append(value)
except:
errors_during_evaluation += 1
metrics: dict[str, float] = {}
for metric, values in metric_values.items():
if metric.startswith("variable"):
successful = total = 0
for subsuccessful, subtotal in values:
successful += subsuccessful
total += subtotal
metrics[metric] = float(successful / total) if total > 0 else 0.0
else:
metrics[metric] = float(sum(values) / len(values)) if len(values) > 0 else 0.0
if self.write_output_to is not None:
try:
write_output_to_files(predictions, self.write_output_to) # type: ignore (doesn't handle the conversion to a list in the if above well.)
except FileNotFoundError:
print(f"Evaluation log file {self.write_output_to} not found!", file=sys.stderr)
metrics["errors_during_evaluation"] = float(errors_during_evaluation)
return metrics
def __contains__(self, metric: str) -> bool:
return metric in self.metric_names
def get_analysis_metrics(self, fn: MatchedFunction, prediction: str) -> dict[str, Any]:
"""Compute metrics that require program analysis.
"""
### Compute baselines for adjustment.
try:
original_code = canonicalize_udt_field_names(fn.canonical_original_code, fn.variable_types, fn.user_defined_types)
except NonexistentFieldError:
return {"oracle_has_nonexistent_field": 1}
try:
self_alignment: Alignment = align(fn.canonical_original_code, fn.canonical_original_code, 'c')
except (ParsingError, SemanticError, AssertionError, KeyError, NotImplementedError):
# This is a failure of codealign; we don't want to penalize or reward the model for it so we exclude it from the evaluation.
return {}
alignable = get_aligned_variables(self_alignment)
assert all(k in v for k, v in alignable.items()) # Sanity check, can delete later.
alignable_variables = len(alignable)
alignable_udt_variables = sum(name in alignable and has_udt(typ) for name, typ in fn.variable_types.items())
variables_inherently_alignable = (len(alignable), len(fn.variable_types))
### Set up default metric results. These will be overriden as values are computed.
metrics = {
"syntatically_valid": 0,
"semantically_valid": 0,
"consistently_aligned": 0,
"perfectly_aligned": 0,
"perfectly_aligned_and_typechecks": 0,
"variable_name_accuracy": (0, alignable_variables),
"variable_type_accuracy": (0, alignable_variables),
"variable_udt_exact_matches": (0, alignable_udt_variables),
"variable_udt_composition_matches": (0, alignable_udt_variables),
"variables_inherently_alignable": variables_inherently_alignable,
"oracle_has_nonexistent_field": 0,
"codealign_failures": 0,
"consistency_solver_timeouts": 0
}
### Parse and sort nodes
root = parser.parse(bytes(prediction, "utf8")).root_node
if root.type == "ERROR":
return metrics
assert root.type == "translation_unit"
fn_nodes: list[Node] = []
udt_nodes: list[Node] = []
other_nodes: list[Node] = []
for node in root.children:
if node.type == "function_definition":
fn_nodes.append(node)
elif node.type in {"struct_specifier", "union_specifier", "enum_specifier"}:
udt_nodes.append(node)
elif node.type == ";":
pass
else:
other_nodes.append(node)
# Process all UDTs
types = FileTypeMapping()
for type_node in udt_nodes:
if not has_error(type_node):
try:
types.parse_type(type_node)
except:
pass # Ignore the misgenerated type. If it's necessary, we'll get another exception later.
if len(fn_nodes) == 0:
return metrics
fn_node = fn_nodes[0]
assert fn_node.text is not None # To make mypy happy
# We don't track or measure the accuracy of types not associated with variables (though this is taken into account when computing an alignment).
# However PreprocessedFunction will throw an exception if it encounters an unrecognized type in a typecast.
# To prevent this, we add generic placholder types.
predicted_body = fn_node.child_by_field_name("body")
assert predicted_body is not None
try: # Add placholders in a try-except in case a non-variable type is unparsable.
add_placeholders_for_nonvariable_types(predicted_body, types)
predicted_fn = PreprocessedFunction(fn_node, types)
except (TypeNotFoundError, TypeNotDefinedError, UnsupportedFeatureError, AssertionError):
# We need the variable-type mapping that PreprocessedFunction provides to standardize the field names
# for the alignment. We don't return here, however, because PreprocessedFunction is very strict about
# types; a function may be syntatically, or arguably, semantically valid but fail here. Thus, we
# assign predicted_fn to None here and then do the early return later.
predicted_fn = None
predicted_code = fn_node.text.decode()
if predicted_fn is not None:
predicted_udts = get_all_user_defined_types(predicted_fn)
try:
predicted_code = canonicalize_udt_field_names(predicted_code, predicted_fn.variable_types, predicted_udts)
except NonexistentFieldError:
pass # Do nothing; will fail to perfectly align and then the relevant types will be counted as incorrect later.
try:
alignment: Alignment = align(predicted_code, original_code, 'c')
except ParsingError:
return metrics
except SemanticError:
metrics["syntatically_valid"] = 1
return metrics
except (AssertionError, AttributeError, KeyError, NotImplementedError):
# This is a failure of codealign; we don't want to penalize or reward the model for it so we exclude it from the evaluation.
return {"codealign_failures": 1, "variables_inherently_alignable": variables_inherently_alignable}
is_perfectly_aligned = perfectly_aligned(alignment)
metrics["perfectly_aligned"] = is_perfectly_aligned
metrics["syntatically_valid"] = 1
metrics["semantically_valid"] = 1
try:
# get_consistent_alignment checks perfectly_aligned as a condition to return an alignment, so we don't need to check it again.
# If consistent_alignment is not None, then the alignment must be perfect.
consistent_alignment = get_consistent_alignment(fn, fn_node.text.decode())
metrics["consistently_aligned"] = consistent_alignment is not None
except AggregateSolverTimeoutError:
metrics["consistency_solver_timeouts"] = 1
del metrics["consistently_aligned"] # this is a failure of our solver; we don't want to penalize or reward the model for it.
if predicted_fn is None:
return metrics
# Standardize types
ground_truth_types = FileTypeMapping()
for udt in fn.user_defined_types:
ground_truth_types.add_type(str(udt.stub), udt)
fn.variable_types = expand_all(fn.variable_types, ground_truth_types)
predicted_fn.variable_types = expand_all(predicted_fn.variable_types, types)
var_map = get_aligned_variables(alignment)
def get_predicted_var_info(ground_truth_name: str) -> list[tuple[str, TypeInfo]] | None:
if ground_truth_name not in var_map:
return None
predicted_names = var_map[ground_truth_name]
if any(name not in predicted_fn.variable_types for name in predicted_names):
# This shouldn't happen, but it isn't serious enough that we'll want to crash everything with an assertion.
warnings.warn(f"Property violation: {predicted_names} is in the alignment but not the preprocessed function.")
return None
return [(predicted_name, predicted_fn.variable_types[predicted_name]) for predicted_name in predicted_names]
variable_name_matches = 0
variable_type_exact_matches = 0
variable_udt_exact_matches = 0
variable_udt_composition_matches = 0
typechecks: bool = True # a function with no variables trivially typechecks. (We ignore return type here.)
for ground_truth_name, ground_truth_type in fn.variable_types.items():
if ground_truth_name not in alignable:
continue
predicted_var_info = get_predicted_var_info(ground_truth_name)
if predicted_var_info is None:
continue # add zero to the totals of each variable-name level metrics.
ground_truth_has_udt = has_udt(ground_truth_type)
# shape: (number of applicable metrics, number of predictions)
variable_results = np.zeros((2 + 2 * ground_truth_has_udt, len(predicted_var_info)))
for i, (predicted_name, predicted_type) in enumerate(predicted_var_info):
variable_results[0][i] = ground_truth_name == predicted_name
variable_results[1][i] = ground_truth_type == predicted_type
if ground_truth_has_udt:
variable_results[2][i] = ground_truth_type == predicted_type
variable_results[3][i] = type(ground_truth_type) == type(predicted_type) and has_identical_composition(predicted_type, ground_truth_type) # the type(...) == type(...) is to improve efficiency and is not strictly necessary.
# When len(predicted_var_info) > 1, this ground-truth variable aligns with multiple variables in prediction.
# This just mean the variables have equivalent values, which can happen even in two identical functions.
# We choose the one that maximizes the number of scoring metrics (as must be done even when two functions are
# identical to get a perfect score.)
scores: NDArray = variable_results.sum(axis=0)
assert scores.dtype == variable_results.dtype # Sanity check; can delete later.
argmax_idx = scores.argmax(axis=0) # axis=0 because sum() reduces the axis.
max_score = scores[argmax_idx]
if (max_score == scores).sum() > 1: # There is a tie in the scores. We break it by prioritizing names over types.
# First, zero-out all rows that aren't involved in the tie.
variable_results[np.repeat((max_score!=scores)[:,np.newaxis], variable_results.shape[0], axis=1).transpose()] = 0
variable_results[0] *= 2 # Upweight variable name scores, the first row.
argmax_idx = variable_results.sum(axis=0).argmax(axis=0) # recalculate the (arg)maximum
variable_results = (variable_results > 0).astype(scores.dtype) # convert everything back to 0s and 1s.
best_results = variable_results[:,argmax_idx]
variable_name_matches += best_results[0]
variable_type_exact_matches += best_results[1]
if ground_truth_has_udt:
variable_udt_exact_matches += best_results[2]
variable_udt_composition_matches += best_results[3]
typechecks = typechecks and bool(best_results[3 if ground_truth_has_udt else 1])
if alignable_variables > 0:
metrics |= {
"variable_name_accuracy": (variable_name_matches, alignable_variables),
"variable_type_accuracy": (variable_type_exact_matches, alignable_variables),
"perfectly_aligned_and_typechecks": is_perfectly_aligned and typechecks
}
if alignable_udt_variables > 0:
metrics |= {
"variable_udt_exact_matches": (variable_udt_exact_matches, alignable_udt_variables),
"variable_udt_composition_matches": (variable_udt_composition_matches, alignable_udt_variables)
}
return metrics
### Utility functions for working with TypeInfo objects
def expand_all(variable_types: dict[str, TypeInfo], types: FileTypeMapping) -> dict[str, TypeInfo]:
scope = Scope(mapping=types)
return {
name: scope.expand_type(typ)
for name, typ in variable_types.items()
}
def has_identical_composition(candidate: TypeInfo, reference: TypeInfo, _seen_udts: dict[TypeStub, TypeStub] | None = None) -> bool:
"""Return true if both types have fields of the same types in the same order, and false otherwise. This is defined recursively for nested structs.
The _seen_udts argument is used internally and should not be supplied by the caller.
"""
if _seen_udts is None:
_seen_udts = {}
if type(candidate) == type(reference):
if isinstance(candidate, (Struct, Union)):
layouts = ((candidate.layout, reference.layout) if isinstance(candidate, Struct) else (candidate.members, reference.members)) # type: ignore (mypy doesn't handle the equivalent types condition on the if)
if len(layouts[0]) != len(layouts[1]):
return False
_seen_udts[candidate.stub] = reference.stub # type: ignore
for cand_member, ref_member in zip(*layouts):
if type(cand_member) != type(ref_member):
return False
if isinstance(cand_member, (Struct, Union)):
if not has_identical_composition(cand_member, ref_member, _seen_udts): # type: ignore
return False
else:
assert isinstance(cand_member, UDT.Field)
if not has_identical_composition(cand_member.type_name, ref_member.type_name, _seen_udts): # type: ignore
return False
elif isinstance(candidate, Pointer):
return has_identical_composition(candidate.target_type_name, reference.target_type_name, _seen_udts) # type: ignore
elif isinstance(candidate, Array):
return candidate.nelements == reference.nelements and has_identical_composition(candidate.element_type, reference.element_type, _seen_udts) # type: ignore
elif isinstance(candidate, FunctionType):
return len(candidate.parameters) == len(reference.parameters) and has_identical_composition(candidate.return_type, reference.return_type, _seen_udts) and all(has_identical_composition(t1, t2, _seen_udts) for (t1, _), (t2, _) in zip(candidate.parameters, reference.parameters)) # type: ignore
elif isinstance(candidate, TypeStub):
return _seen_udts[candidate] == reference
else:
return candidate == reference
else:
return False
return True
def has_udt(typ: TypeInfo) -> bool:
"""Return true if there is a struct or union type, or a stub of such, in this type
"""
if type(typ) is TypeInfo:
return False
# When types are expanded/standardized, the StructStub and UnionStub should become redundant,
# because they will only exist for recursive types, which means the struct/union is already defined.
# However, this is handy pre-expansion/standardization for checking which types will contain structs/unions.
if isinstance(typ, (Struct, Union, StructStub, UnionStub)):
return True
if isinstance(typ, Pointer):
assert isinstance(typ.target_type_name, TypeInfo)
return has_udt(typ.target_type_name)
if isinstance(typ, Array):
assert isinstance(typ.element_type, TypeInfo)
return has_udt(typ.element_type)
if isinstance(typ, FunctionType):
return has_udt(typ.return_type) or any(has_udt(t) for t, _ in typ.parameters)
return False
def add_placeholders_for_nonvariable_types(node: Node, types: FileTypeMapping):
"""Functions may have references to types outside of their variables' types and return types, including
in typecasts and sizeof expressions. This function identifies such situations and adds a generic
placeholder to the FileTypeMapping so that they can be interpreted by PreprocessedFunction.
"""
if node.type == "type_descriptor":
base_type_node = node.child_by_field_name("type")
assert base_type_node is not None and base_type_node.text is not None
base_type_text = base_type_node.text.decode()
if base_type_text not in types.types:
typ = types.parse_type(base_type_node)
assert typ is not None, f"Failed to parse type {base_type_text}."
# Add generic placeholder UDT types. Normally we wouldn't want to do this, but
# we'll never actually need the full definitions of the types during evaluation,
# so it's fine here.
if isinstance(typ, StructStub):
typ = Struct(name=typ.name, layout=[])
elif isinstance(typ, UnionStub):
typ = Union(name=typ.name, members=[])
elif isinstance(typ, EnumStub):
typ = Enum(name=typ.name, members=[])
types.add_type(base_type_text, typ)
elif node.type != "declaration":
for child in node.children:
add_placeholders_for_nonvariable_types(child, types)
### Utility functions for working with Alignment objects
def perfectly_aligned(alignment: Alignment) -> bool:
return all(bool(alignment[op]) for bb in alignment.reference_ir for op in bb) and \
all(bool(alignment[op]) for bb in alignment.candidate_ir for op in bb)
def get_aligned_variables(alignment: Alignment) -> dict[str, set[str]]:
"""Return the variables from the reference that align with those in the candidate.
:alignment: an Alignment object for which to compute variable alignment.
:returns: a dictionary mapping reference variable to target variable.
"""
var_map: dict[str, set[str]] = {} # candidate (ground-truth) to reference (prediction)
for candidate_op, reference_op in alignment.alignment_list:
if isinstance(candidate_op, Parameter) or isinstance(reference_op, Parameter):
assert type(candidate_op) == type(reference_op), f"Only paramters should be aligned with parameters."
if reference_op.name not in var_map: # type: ignore
var_map[reference_op.name] = set() # type: ignore
var_map[reference_op.name].add(candidate_op.name) # type: ignore
elif candidate_op is not None and candidate_op.var_operator is not None and isinstance(candidate_op.var_operator.result, Variable) and not candidate_op.var_operator.result.is_temporary and not isinstance(candidate_op.var_operator.result, GlobalVariable) and \
reference_op is not None and reference_op.var_operator is not None and isinstance(reference_op.var_operator.result, Variable) and not reference_op.var_operator.result.is_temporary and not isinstance(reference_op.var_operator.result, GlobalVariable):
if (ref_name := reference_op.var_operator.result.name) not in var_map:
var_map[ref_name] = set()
var_map[ref_name].add(candidate_op.var_operator.result.name)
return var_map
### Functions for editing code to standard form ###
def try_dereference(t: TypeInfo) -> TypeInfo | None:
"""Returns the target of t if it's a pointer or array type. Otherwise, return None.
"""
if isinstance(t, Pointer):
assert isinstance(t.target_type_name, TypeInfo)
return t.target_type_name
elif isinstance(t, Array):
assert isinstance(t.element_type, TypeInfo)
return t.element_type
else: # Can't dereference something that is not a pointer
return None
def field_index(t: TypeInfo, field_expression: Node, udts: dict[TypeStub, UDT]) -> tuple[int, TypeInfo] | None:
"""Return the index in the struct or union that field_name occurs at or None if t is not a
struct or union or if the field does not exist.
"""
assert field_expression.type == "field_expression"
if get_child(field_expression, "operator").text.decode() == "->": # type: ignore
t = try_dereference(t) # type: ignore # re-defining t as a variable that could be None.
if isinstance(t, TypeStub) and t in udts:
t = udts[t]
if isinstance(t, (Struct, Union)): # t == None is filtered out here.
field_name: str = get_child(field_expression, "field").text.decode() # type: ignore
for i, f in enumerate(t.layout if isinstance(t, Struct) else t.members):
if isinstance(f, UDT.Field) and f.name == field_name:
assert isinstance(f.type_name, TypeInfo)
return (i, f.type_name)
return None
def get_type_of_field_expression_argument(expression: Node, variable_types: dict[str, TypeInfo], udts: dict[TypeStub, UDT]) -> TypeInfo | None:
"""Returns the type of the provided expression.
"""
if expression.type == "identifier":
variable_name: str = expression.text.decode() # type: ignore
return variable_types.get(variable_name, None)
if expression.type == "field_expression":
t = get_type_of_field_expression_argument(get_child(expression, "argument"), variable_types, udts)
if t is None:
return None
field_info = field_index(t, expression, udts)
if field_info is None:
return None
else:
return field_info[1]
if expression.type == "parenthesized_expression":
assert len(expression.children) == 3 and expression.children[0].type =="(" and expression.children[2].type == ")"
return get_type_of_field_expression_argument(expression.children[1], variable_types, udts)
if expression.type == "pointer_expression":
operator: str = get_child(expression, "operator").text.decode() # type: ignore
argument = get_child(expression, "argument")
assert operator == "&" or operator == "*"
t = get_type_of_field_expression_argument(argument, variable_types, udts)
if t is None:
return None
if operator == "*":
return try_dereference(t)
else:
return Pointer(t)
if expression.type == "subscript_expression":
argument = get_child(expression, "argument")
t = get_type_of_field_expression_argument(argument, variable_types, udts)
if isinstance(t, Array):
assert isinstance(t.element_type, TypeInfo)
return t.element_type
if isinstance(t, Pointer):
assert isinstance(t.target_type_name, TypeInfo)
return t.target_type_name
return None
if expression.type == "cast_expression":
# non () children are "type" and "value".
# The value actually doesn't matter here because we only care about it for its type, but
# the type is being changed to the type specifed in the cast. So we just parse and return that.
descriptor = get_child(expression, "type")
assert descriptor.type == "type_descriptor", f"Expected a type descriptor in a cast expression but found {descriptor.type}"
base_type_node = descriptor.child_by_field_name("type")
declarator = get_child(descriptor, "declarator")
assert base_type_node is not None and base_type_node.text is not None
base_type_text = base_type_node.text.decode()
type_mapping = FileTypeMapping()
typ = type_mapping.parse_type(base_type_node)
assert typ is not None, f"Failed to parse type {base_type_text}."
if isinstance(typ, (TypeStub)) and typ in udts:
full_type, _ = type_mapping.parse_abstract_declarators(declarator, udts[typ])
return full_type
else:
return None
if expression.type == "binary_expression":
return None # Could handle this, but is extremely rare and requires parsing both operands; exactly one must be a normal expression.
if expression.type == "call_expression":
return None # we can't do anything with this unless we know the called function's return type.
raise NotImplementedError(f"Not supported: field name canonicalization: {expression.type}")
class NonexistentFieldError(Exception):
pass
def canonicalize_udt_field_names(code: str, variable_types: dict[str, TypeInfo], user_defined_types: list[UDT]) -> str:
"""Replace all field names used in field expressions (e.g point.x or point->x) with the
standard name "fieldX", where X is the index of the field in the corresponding type.
"""
# For field_expressions:
# expression.children[0]: (argument) - an expression that resolves to the struct
# expression.children[1]: (operator) ->
# expression.children[2]: (field) - the field being accessed.
# Contains the changes we want to make to the text.
# Tuples of (node to be deleted, text replacement).
edits: list[tuple[Node, str]] = []
udts = {t.stub: t for t in user_defined_types}
def find_field_expression(node: Node):
if node.type == "field_expression":
t = get_type_of_field_expression_argument(get_child(node, "argument"), variable_types, udts)
if t is not None:
field_info = field_index(t, node, udts)
if field_info is not None:
canonical_field_name = f"field{field_info[0]}"
edits.append((get_child(node, "field"), canonical_field_name))
else:
raise NonexistentFieldError()
for child in node.children:
find_field_expression(child)
root = parser.parse(bytes(code, 'utf8')).root_node
find_field_expression(root) # populate the list 'edits'
return edit_function(root, edits)
def edit_function(root: Node, edits: list[tuple[Node, str]]) -> str:
"""For the code represented in the ast rooted at `root`, replace each node in the `edits` list
with the corresponding string.
"""
# Sorting edits in reverse order reduces the offset bookkeeping we have to do.
edits.sort(key=lambda x: x[0].start_byte, reverse=True)
assert all(a[0].start_byte > b[0].end_byte for a, b in zip(edits, itertools.islice(edits, 1, None)))
start = root.start_byte # should always be 0 in this context
text = root.text
assert text is not None
components = []
for subnode, replacement in edits:
components.append(text[(subnode.end_byte - start):])
components.append(bytes(replacement, 'utf8'))
text = text[:(subnode.start_byte - start)]
components.append(text[(root.start_byte - start):])
components.reverse() # We've been adding components backwards, reverse them for the correct output.
return b"".join(components).decode("utf8")
class ASTIsomorphism:
def __init__(self, root1: Node, root2: Node):
"""Represents a mapping from one AST to another based on those nodes' positions within the AST.
Precondition: The two ASTs have exactly the same structure (same node types with the same children).
This does not include the values of the nodes, e.g. identifier names.
"""
self.root1 = root1
self.root2 = root2
# Maps Node IDs to the corresponding nodes.
mapping: dict[Node, Node] = {}
def recurse(node1: Node, node2: Node) -> bool:
mapping[node1] = node2
if node1.type != node2.type:
return False
return all(recurse(c1, c2) for c1, c2 in zip(node1.children, node2.children))
if not recurse(root1, root2):
raise ValueError(f"Precondition violated: code snippets do not have isomorphic ASTs.")
self.mapping = mapping
def __getitem__(self, item: Node) -> Node:
return self.mapping[item]
def genericize_func_and_field_names(code: str) -> tuple[list[tuple[Node, str]], Node]:
"""Replace all function names in the provided function with the name "func"
and replace all field names with the name "field."
"""
# When parsing a call_expression, it is important to determine whether the
# identifier in the call expression refers to a function name or a variable (in
# a call from a function pointer). This requires some analysis, which codealign
# already does for us. Therefore, we use it and the AST produced by its call to
# tree-sitter.
codealign_ir = parse(bytes(code, "utf8"))
assert len(codealign_ir) == 1, "Expected only one function, but found " + ", ".join(f.name for f in codealign_ir)
root = codealign_ir[0].node.parent
assert root is not None and root.type == "translation_unit"
call_instructions: dict[Node, FunctionVarOperator] = {}
for bb in codealign_ir[0]:
for ins in bb:
if isinstance(ins, FunctionVarOperator):
assert ins.ast_node is not None
call_instructions[ins.ast_node] = ins
edits: list[tuple[Node, str]] = []
def recurse(node: Node):
if node.type == "call_expression":
# expression.children[0]: (function) - the name of the function.
# expression.children[1]: (arguments; argument_list) - a list of arguments.
if node in call_instructions:
instruction = call_instructions[node]
else:
print(f"Warning: Missing call instruction for call expression in AST; may be due to dead code.")
return
if isinstance(instruction.name, str):
name_node = get_child(node, "function")
# The following is NOT true the other way around: You can have situations where the node is an identifer
# and it is not a regular function call but instead is a call based on a function poitner: hence the whole
# reason we're using codealign in the first place!
assert name_node.type == "identifier", f"Codealign determines {node.text} is a regular function but the AST node type is not an identifier."
assert name_node.text.decode() == instruction.name, f"Inconsistent names for function." # type: ignore
edits.append((name_node, GENERIC_FUNCTION_NAME))
else:
# The function could be the result of an expression which contains a field or another funciton call
recurse(get_child(node, "function"))
# There could be yet more function calls in the arguments.
recurse(get_child(node, "arguments"))
elif node.type == "field_expression":
# expression.children[0]: (argument) - an expression that resolves to the struct
# expression.children[1]: (operator) ->
# expression.children[2]: (field) - the field being accessed.
field_node = get_child(node, "field")
assert field_node.type == "field_identifier", (field_node.type, field_node.text.decode()) # type: ignore
edits.append((field_node, GENERIC_FIELD_NAME))
# The field itself must be an identifier, but the left node could
# be an arbitrarily complicated expression, so we must recurse.
recurse(get_child(node, "argument"))
else:
for child in node.children:
recurse(child)
# populates the list "edits"
recurse(root)
return edits, root
def get_nongeneric_function_name(instruction: SSAOperator, astmapping: ASTIsomorphism) -> str | None:
"""If this instruction is a call instruction on a function with a name (not a function pointer),
return the name of that function. Otherise, return None.
"""
if isinstance(instruction, FunctionSSAOperator) and isinstance(instruction.name, str):
assert instruction.ast_node is not None, instruction
node = astmapping[instruction.ast_node]
function_name_node = get_child(node, "function")
assert function_name_node.type == "identifier"
return function_name_node.text.decode() # type: ignore
return None
def get_nongeneric_field_name(instruction: SSAOperator, astmapping: ASTIsomorphism) -> str | None:
"""If this instruction is a field-access instruction, return the name of the field accessed.
Otherwise, return None.
"""
if instruction.op == "." or instruction.op == "->":
assert instruction.ast_node is not None, instruction
node = astmapping[instruction.ast_node]
field_node = get_child(node, "field")
assert field_node.type == "field_identifier"
return field_node.text.decode() # type: ignore
return None
def build_and_solve_constraints(alignment: Alignment,
candidate_mapping: ASTIsomorphism,
reference_mapping: ASTIsomorphism,
namegetter: Callable[[SSAOperator, ASTIsomorphism], str | None],
generic_name: str
) -> Iterable[tuple[dict[str, str], dict[str, str]]]:
"""Determine if the names in the candidate and reference function are consistent (i.e. form a bijective mapping between one another.)
"""
# Outer index: IR type (candidate, reference)
# Middle index: instruction in the IR. Only contains relevant instructions.
# Inner index: [0] SSAOperator and [1] the name that corresponds to it (either the function call name or field name)
instructions_by_ir: list[list[tuple[SSAOperator, str]]] = []
for i, (ir, mapping) in enumerate(zip((alignment.candidate_ir, alignment.reference_ir), (candidate_mapping, reference_mapping))):
relevant_instructions = []
for bb in ir:
for instruction in bb:
name = namegetter(instruction, mapping)
if name is not None:
relevant_instructions.append((instruction, name))
instructions_by_ir.append(relevant_instructions)
# Each variable represents a relevant instruction (either a function call or a struct-field access.)
variables: list[list[z3.ArithRef]] = [] # This form is more convenient for constraints within a given IR and for linking back to the original source.
# Note: can store both candidate and reference instructions in the same dictionary because they hash by id()
variable_by_instruction: dict[SSAOperator, z3.ArithRef] = {} # This form is more convenient when dealing with alignment clusters.
for i, instructions in enumerate(instructions_by_ir):
variables.append(list())
for j in range(len(instructions)):
variable = z3.Int(f"var{i}_{j}")
variables[i].append(variable)
variable_by_instruction[instructions[j][0]] = variable
constraints: list = [] # The constraints that we'll feed to z3
for i, instructions in enumerate(instructions_by_ir):
## Constraints within a given IR
for j in range(len(instructions)):
for k in range(j + 1, len(instructions)):
if instructions[j][1] == instructions[k][1]:
# Instructions with the same names in the non-genericized code should have the same integer value
constraints.append(variables[i][j] == variables[i][k])
else:
# Instructions with the different names in the non-genericized code should have different integer values.
constraints.append(variables[i][j] != variables[i][k])
# Instructions aligned with each other must have the same values.
for j, instruction in enumerate(instructions):
variable = variables[i][j]
aligned = alignment[instruction[0]]
assert isinstance(aligned, list), f"Expected a relational alignment."
# The second part of the condition is because
if len(aligned) == 1:
constraints.append(variable == variable_by_instruction[aligned[0]])
elif len(aligned) > 1:
constraints.append(
z3.Or(*(variable == variable_by_instruction[other] for other in aligned))
)
# Some additional constraints that are often helpful in the case of differentiating field-accesses used as lvals.
# Funciton calls cannot be used as lvals so this only applies to UDT field-accesses.
if generic_name == GENERIC_FIELD_NAME:
for i, ir in enumerate((alignment.candidate_ir, alignment.reference_ir)):
for bb in ir:
for ins in bb:
ins: SSAOperator
if ins.op == STORE_OP and ins.operands[0] in variable_by_instruction:
aligned = alignment[ins]
field_access_var = variable_by_instruction[ins.operands[0]] # type: ignore # We check this directly above in the if condition.
assert isinstance(aligned, list), f"Expected a relational alignment."
constraints.append(
z3.Or(*(field_access_var == variable_by_instruction[store_op.operands[0]] for store_op in aligned)) # type: ignore # the assertion should be true based on how codealign works but mypy doesn't know that.
)
clusterer = UnionFind(operator for fn in (alignment.candidate_ir, alignment.reference_ir) for block in fn.basic_blocks for operator in block if isinstance(operator, SSAOperator))
for left, right in alignment.alignment_list:
if left in variable_by_instruction and right in variable_by_instruction:
clusterer.union(left, right)
equivalence_classes: list[set[SSAOperator]] = clusterer.export_sets() # type: ignore
opset = lambda ir: {op for bb in ir for op in bb}
cand_ops = opset(alignment.candidate_ir)
ref_ops = opset(alignment.reference_ir)
# For equivalence classes with exactly two elements, there's only one possible
# combination that satisfies the constraints, so it's not interesting to examine these further.
clusters: list[tuple[set[z3.ArithRef], set[z3.ArithRef]]] = [
({variable_by_instruction[ins] for ins in eqc if ins in cand_ops},
{variable_by_instruction[ins] for ins in eqc if ins in ref_ops})
for eqc in equivalence_classes if len(eqc) > 2
]
def build_name_mapping(model, is_reference: bool):
name_mapping: dict[str, str] = {}
for j, v in enumerate(variables[is_reference]):
# Sometimes the solver may choose a negative integer value, which doesn't work well for the generic_name + str(value) pattern below, because
# dashes are not valid characters for C identifiers. Instead, we map the integer values onto the natural numbers.
value = model[v].as_long() # type: ignore
value = -1 * (2 * value + 1) if value < 0 else 2 * value
name_mapping[instructions_by_ir[is_reference][j][1]] = generic_name + str(value)
return name_mapping
def make_solution(model):
return (build_name_mapping(model, False), build_name_mapping(model, True))
solver = z3.Solver()
solver.add(constraints)
solver.set("timeout", 60)
if solver.check() == z3.sat:
yield make_solution(solver.model())
modelno = 0
def find_solutions(clusters: list[tuple[set[z3.ArithRef], set[z3.ArithRef]]]):
# There's no sense in searching ever deeper down the tree of more constrained problems if the less-constrained
# root isn't satisfiable in the first place.
if solver.check() == z3.sat:
if len(clusters) == 0:
nonlocal modelno
modelno += 1
yield make_solution(solver.model())
else:
cand_vars, ref_vars = clusters[0]
remaining_clusters = clusters[1:]
if len(cand_vars) < len(ref_vars):
cand_vars = list(cand_vars) + [None] * (len(ref_vars) - len(cand_vars))
elif len(ref_vars) > len(cand_vars):
ref_vars = list(ref_vars) + [None] * (len(cand_vars) - len(ref_vars))
for permutation in itertools.permutations(ref_vars, len(ref_vars)):
eqs = [cand_var == ref_var for cand_var, ref_var in zip(cand_vars, permutation) if cand_var is not None and ref_var is not None]
solver.push()
solver.add(eqs)
yield from find_solutions(remaining_clusters)
solver.pop()
yield from find_solutions(clusters)
class AggregateSolverTimeoutError(Exception):
"""A constraint-solving problem has taken too long across different invocations of the solver.
"""
def get_consistent_alignment(fn: MatchedFunction, prediction: str) -> Alignment | None:
"""Return an alignment that is less strict that normal alignment: function names and field names need not be identical
to the original in order to be counted as equivalent; rather, they must simply form a bijective mapping with the names in the
original code.
"""
# These can fail with parsing errors from codealign's parser. If they do, simply exit early and return None because that'll
# just happen later when we call "align."
prediction_edits, prediction_root = genericize_func_and_field_names(prediction)
original_edits, original_root = genericize_func_and_field_names(fn.canonical_original_code)
generic_prediction = edit_function(prediction_root, prediction_edits)
generic_original = edit_function(original_root, original_edits)
alignment: Alignment = align(generic_prediction, generic_original, 'c') # type: ignore
# May cause incomplete constraints to be generated if not prefectly aligned.
if not perfectly_aligned(alignment):
return None
candidate_mapping = ASTIsomorphism(alignment.candidate_ir.node.parent, prediction_root) # type: ignore
reference_mapping = ASTIsomorphism(alignment.reference_ir.node.parent, original_root) # type: ignore
has_functions_to_edit = any(edit[1] == GENERIC_FUNCTION_NAME for edit in original_edits)
has_fields_to_edit = any(edit[1] == GENERIC_FIELD_NAME for edit in original_edits)
# These mappings represent consistent canonicalizations of function names and field names, respectively.
# We use itertools.product below, which will iterate over nothing if there are no elements in any of the iterables in its arguments.
# This is problematic if there are no function or field names to align: there will be no calls to align()
if has_functions_to_edit:
fnname_mappingss = build_and_solve_constraints(alignment, candidate_mapping, reference_mapping, get_nongeneric_function_name, GENERIC_FUNCTION_NAME)
else:
fnname_mappingss = (({}, {}),)
if has_fields_to_edit:
field_mappingss = build_and_solve_constraints(alignment, candidate_mapping, reference_mapping, get_nongeneric_field_name, GENERIC_FIELD_NAME)
else:
field_mappingss = (({}, {}),)
start = time.time()
reusable_field_mappings: list[tuple[dict[str, str], dict[str, str]]] = []
for fnname_mappings in fnname_mappingss:
# The return value of build_and_solve constraints is a generator, so it can't be iterated through a second time after
# it is exhausted. However, we may need to iterate through it multiple times if the first function name mapping doesn't work.
# Therefore, we save it in a list and use that on all iterations beyond the first.
field_mappings_iter = field_mappingss if len(reusable_field_mappings) == 0 else reusable_field_mappings
for field_mappings in field_mappings_iter:
if time.time() - start > AGGREGATE_SOLVER_TIMEOUT:
raise AggregateSolverTimeoutError()
def make_consistent_function_definition(is_reference: bool, old_edits: list[tuple[Node, str]], root: Node):
fnname_mapping = fnname_mappings[is_reference]
field_mapping = field_mappings[is_reference]
edits: list[tuple[Node, str]] = []
for node, name in old_edits:
if name == GENERIC_FUNCTION_NAME:
edits.append((node, fnname_mapping[node.text.decode()])) # type: ignore
else:
assert name == GENERIC_FIELD_NAME
edits.append((node, field_mapping[node.text.decode()])) # type: ignore
return edit_function(root, edits)
consistent_prediction = make_consistent_function_definition(False, prediction_edits, prediction_root)
consistent_original = make_consistent_function_definition(True, original_edits, original_root)
# Any exceptions in alignment should have been encountered already.
alignment = align(consistent_prediction, consistent_original, 'c')
if perfectly_aligned(alignment):
return alignment
reusable_field_mappings.append(field_mappings)
# This means there are fields, but no satisfiable field mappings. Thus, there's no point in continuing to iterate
# in the outer function-mappings loop because both must be satisfiable for a non-None return.
if len(reusable_field_mappings) == 0:
break
return None
### Running exebench tests ###
def get_function_name(definition: Node) -> str:
"""Get the name of a function.
"""
assert definition.type == "function_definition", f"{definition.type} is not a function_definition"
declarator = get_child(definition, "declarator")
while declarator.type == "pointer_declarator":
declarator = get_child(declarator, "declarator")
assert declarator.type == "function_declarator"
name = get_child(declarator, "declarator")
assert name.type == "identifier"
return name.text.decode("utf8") # type: ignore
def run_command_in_docker(
command: list[str],
cwd: str | None, # inside the docker container
directory_mapping: dict[str | Path, str | Path] = {},
timeout: float | None = None,
image: str = 'exebench-test'
) -> subprocess.CompletedProcess[bytes]:
"""Run the command 'command' inside a docker container
"""
full_command: list[str] = ["docker", "run", "--rm"]
for host, container in directory_mapping.items():
full_command.extend(["-v", f"{os.path.abspath(host)}:{container}"])
if cwd is not None: # cwd of the command inside the docker container.
full_command.extend(["-w", cwd])