-
-
Notifications
You must be signed in to change notification settings - Fork 373
/
diaphora.py
executable file
·3933 lines (3418 loc) · 122 KB
/
diaphora.py
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
#!/usr/bin/python3
"""
Diaphora, a binary diffing tool
Copyright (c) 2015-2024, Joxean Koret
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import re
import sys
import time
import json
import decimal
import sqlite3
import logging
import datetime
import importlib
import threading
import traceback
from io import StringIO
from threading import Lock
from multiprocessing import cpu_count
import diaphora_config as config
import diaphora_heuristics
try:
from cdifflib import CSequenceMatcher as SequenceMatcher
HAS_CDIFFLIB = True
except ImportError:
HAS_CDIFFLIB = False
if config.SHOW_IMPORT_WARNINGS:
print("WARNING: Python library 'cdifflib' not found. Installing it will significantly improve text diffing performance.")
print("INFO: Alternatively, you can silence this warning by changing the value of SHOW_IMPORT_WARNINGS in diaphora_config.py.")
from difflib import SequenceMatcher
from difflib import unified_diff
import ml
from ml.basic_engine import get_model_comparison_data, ML_AVAILABLE
from diaphora_heuristics import (
HEURISTICS,
HEUR_TYPE_RATIO,
HEUR_TYPE_RATIO_MAX,
HEUR_TYPE_RATIO_MAX_TRUSTED,
HEUR_FLAG_UNRELIABLE,
HEUR_FLAG_SLOW,
HEUR_FLAG_SAME_CPU,
HEUR_TYPE_NO_FPS,
get_query_fields,
)
import db_support
from db_support import schema
import jkutils.threads as jk_threads
from jkutils.threads import threads_apply
from jkutils.kfuzzy import CKoretFuzzyHashing
from jkutils.factor import (
FACTORS_CACHE,
difference,
difference_ratio,
primesbelow as primes,
)
try:
# pylint: disable-next=unused-import
import idaapi
IS_IDA = True
except ImportError:
IS_IDA = False
importlib.reload(ml.basic_engine)
importlib.reload(config)
importlib.reload(schema)
importlib.reload(jk_threads)
importlib.reload(db_support)
importlib.reload(diaphora_heuristics)
if hasattr(sys, "set_int_max_str_digits"):
sys.set_int_max_str_digits(0)
#-------------------------------------------------------------------------------
VERSION_VALUE = "3.2.1"
COPYRIGHT_VALUE = "Copyright(c) 2015-2024 Joxean Koret"
ITEM_MAIN_EA = 0
ITEM_MAIN_NAME = 1
ITEM_DIFF_EA = 2
ITEM_DIFF_NAME = 3
ITEM_RATIO = 5
# Yes, yes, I know, parsing C/C++ with regular expressions is wrong and cannot
# be done, but we don't need to parse neither real nor complete C/C++, and we
# just want to extract potential function names from matching lines of assembly
# and pseudo-code that, also, can be partial or non C/C++ compliant but, for a
# reason, in a format supported by IDA.
CPP_NAMES_RE = "([a-zA-Z_][a-zA-Z0-9_]{3,}((::){0,1}[a-zA-Z0-9_]+)*)"
#-------------------------------------------------------------------------------
fmt = "[Diaphora: %(asctime)s] %(levelname)s: %(message)s"
logging.basicConfig(format=fmt, level=logging.INFO)
#-------------------------------------------------------------------------------
def load_source(modname, filename):
# Copied from https://docs.python.org/3.12/whatsnew/3.12.html#imp as a
# replacement for the removed imp.load_source().
loader = importlib.machinery.SourceFileLoader(modname, filename)
spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
module = importlib.util.module_from_spec(spec)
# The module is always executed and not cached in sys.modules.
loader.exec_module(module)
return module
#-------------------------------------------------------------------------------
def result_iter(cursor, arraysize=1000):
"""An iterator that uses fetchmany to keep memory usage down."""
while True:
results = cursor.fetchmany(arraysize)
if not results:
break
for result in results:
yield result
#-------------------------------------------------------------------------------
def quick_ratio(buf1, buf2):
"""
Call SequenceMatcher.quick_ratio() to get a comparison ratio.
"""
if buf1 is None or buf2 is None or buf1 == "" or buf1 == "":
return 0
seq = SequenceMatcher(None, buf1.split("\n"), buf2.split("\n"))
return seq.quick_ratio()
#-------------------------------------------------------------------------------
def real_quick_ratio(buf1, buf2):
"""
Call SequenceMatcher.real_quick_ratio() to get a comparison ratio.
"""
if buf1 is None or buf2 is None or buf1 == "" or buf1 == "":
return 0
seq = SequenceMatcher(None, buf1.split("\n"), buf2.split("\n"))
return seq.real_quick_ratio()
#-------------------------------------------------------------------------------
def ast_ratio(ast1, ast2):
"""
Quickly compare 2 fuzzy Abstract Syntax Trees and return a ratio.
"""
if ast1 is None or ast2 is None:
return 0
if ast1 == ast2:
return 1.0
return difference_ratio(decimal.Decimal(ast1), decimal.Decimal(ast2))
#-------------------------------------------------------------------------------
def log(message):
"""
Print a message
"""
# pylint: disable=protected-access
if IS_IDA or os.getenv("DIAPHORA_LOG_PRINT") is not None:
print(f"[Diaphora: {time.asctime()}] {message}")
else:
logging.info(message)
# pylint: enable=protected-access
#-------------------------------------------------------------------------------
def log_refresh(msg, do_log=True):
"""
Print a message and refresh if required (not really used outside of IDA)
"""
if do_log:
log(msg)
#-------------------------------------------------------------------------------
def is_debug_enabled():
return os.getenv("DIAPHORA_DEBUG") is not None
#-------------------------------------------------------------------------------
def debug_refresh(msg):
"""
Print a debugging message if debugging is enabled.
"""
if is_debug_enabled():
log(msg)
#-------------------------------------------------------------------------------
# pylint: disable=consider-using-f-string
class CChooser:
"""
Our own chooser for displaying diffing results.
"""
class Item:
"""
A single chooser item.
"""
def __init__(self, ea, name, ea2=None, name2=None, desc=None, ratio=0, nodes1=0, nodes2=0):
self.ea = ea
self.vfname = name
self.ea2 = ea2
self.vfname2 = name2
self.description = desc
self.ratio = ratio
self.nodes1 = int(nodes1)
self.nodes2 = int(nodes2)
def __str__(self):
return "%08x" % int(self.ea)
def __init__(self, title, bindiff, show_commands=True):
self.primary = True
if title == "Unmatched in secondary":
self.primary = False
self.title = title
self.n = 0
self.items = []
self.bindiff = bindiff
self.show_commands = show_commands
self.cmd_diff_asm = None
self.cmd_diff_graph = None
self.cmd_diff_c = None
self.cmd_import_selected = None
self.cmd_import_all = None
self.cmd_import_all_funcs = None
self.cmd_show_asm = None
self.cmd_show_pseudo = None
self.cmd_highlight_functions = None
self.cmd_unhighlight_functions = None
self.selected_items = []
def add_item(self, item):
"""
Add a single item
"""
if self.title.startswith("Unmatched in"):
self.items.append(["%05lu" % self.n, "%08x" % int(item.ea), item.vfname])
else:
dec_vals = "%." + config.DECIMAL_VALUES
self.items.append(
[
"%05lu" % self.n,
"%08x" % int(item.ea),
item.vfname,
"%08x" % int(item.ea2),
item.vfname2,
dec_vals % item.ratio,
"%d" % item.nodes1,
"%d" % item.nodes2,
item.description,
]
)
self.n += 1
def get_color(self):
"""
Return the highlighting colour for the current chooser.
"""
if self.title.startswith("Best"):
return config.HIGHLIGHT_FUNCTION_BEST
elif self.title.startswith("Partial"):
return config.HIGHLIGHT_FUNCTION_PARTIAL
elif self.title.startswith("Unreliable"):
return config.HIGHLIGHT_FUNCTION_UNRELIABLE
def show(self, force):
"""
Fake method, it is only used when running from within IDA.
"""
# pylint: enable=consider-using-f-string
#-------------------------------------------------------------------------------
class CBytesEncoder(json.JSONEncoder):
"""
Class used to JSON encode some Python types that aren't supported by default.
"""
def default(self, o):
if isinstance(o, bytes):
return o.decode("utf-8")
return json.JSONEncoder.default(self, o)
#-------------------------------------------------------------------------------
# pylint: disable=used-before-assignment
# pylint: disable=global-variable-not-assigned
if "_DATABASES" not in globals():
_DATABASES = {}
if len(_DATABASES) > 0:
for _key in dict(_DATABASES):
log(f"Closing previously opened database {_key}")
tmp_db = _DATABASES[_key]
tmp_db.close()
del _DATABASES[_key]
def sqlite3_connect(db_name):
"""
Return a SQL connection object.
"""
global _DATABASES
db = sqlite3.connect(db_name, check_same_thread=False)
db.text_factory = str
db.row_factory = sqlite3.Row
_DATABASES[db_name] = db
return db
# pylint: enable=global-variable-not-assigned
# pylint: enable=used-before-assignment
#-------------------------------------------------------------------------------
class CBinDiff:
"""
The main binary diffing class.
"""
def __init__(self, db_name, chooser=CChooser):
self.names = dict()
self.primes = primes(2048 * 2048)
self.db_name = db_name
self.dbs_dict = {}
self.db = None # Used exclusively by the exporter!
self.open_db()
self.all_matches = {"best": [], "partial": [], "unreliable": []}
self.matched_primary = {}
self.matched_secondary = {}
self.total_functions1 = None
self.total_functions2 = None
self.equal_callgraph = False
self.kfh = CKoretFuzzyHashing()
# With this block size we're sure it will only apply to "big" functions
self.kfh.bsize = config.FUZZY_HASHING_BLOCK_SIZE
self.pseudo = {}
self.pseudo_hash = {}
self.pseudo_comments = {}
self.microcode = {}
self.unreliable = self.get_value_for(
"unreliable", config.DIFFING_ENABLE_UNRELIABLE
)
self.relaxed_ratio = self.get_value_for(
"relaxed_ratio", config.DIFFING_ENABLE_RELAXED_RATIO
)
self.experimental = self.get_value_for(
"experimental", config.DIFFING_ENABLE_EXPERIMENTAL
)
self.slow_heuristics = self.get_value_for(
"slow_heuristics", config.DIFFING_ENABLE_SLOW_HEURISTICS
)
self.use_trained_model = self.get_value_for(
"use_trained_model", config.ML_USE_TRAINED_MODEL
)
self.exclude_library_thunk = self.get_value_for(
"exclude_library_thunk", config.EXPORTING_EXCLUDE_LIBRARY_THUNK
)
self.use_decompiler = self.get_value_for(
"use_decompiler", config.EXPORTING_USE_DECOMPILER
)
self.project_script = self.get_value_for("project_script", None)
self.hooks = None
# Create the choosers
self.chooser = chooser
self.create_choosers()
self.last_diff_db = None
self.re_cache = {}
self._funcs_cache = {}
self.ratios_cache = {}
self.items_lock = Lock()
self.is_symbols_stripped = False
self.is_patch_diff = False
self.is_same_processor = False
self.unmatched_primary = None
self.unmatched_second = None
self.do_continue = None
# How much do call graphs from both binaries differ?
self.percent = 0
self.classifier = None
####################################################################
# LIMITS
#
# Do not run heuristics for more than SQL_TIMEOUT_LIMIT seconds.
self.timeout = self.get_value_for("SQL_TIMEOUT_LIMIT", config.SQL_TIMEOUT_LIMIT)
# It's typical in SQL queries to get a cartesian product of the results in
# the functions tables. Do not process more than this number of rows.
self.sql_max_processed_rows = self.get_value_for(
"SQL_MAX_PROCESSED_ROWS", config.SQL_MAX_PROCESSED_ROWS
)
# Limits to filter the functions to export
self.min_ea = 0
self.max_ea = 0
# Export only non IDA automatically generated function names? I.e.,
# excluding these starting with sub_*
self.ida_subs = config.EXPORTING_ONLY_NON_IDA_SUBS
# Export only function summaries instead of also exporting both the
# basic blocks and all instructions used by functions?
self.function_summaries_only = config.EXPORTING_FUNCTION_SUMMARIES_ONLY
# Ignore IDA's automatically generated sub_* names for heuristics
# like the 'Same name'?
self.ignore_sub_names = config.DIFFING_IGNORE_SUB_FUNCTION_NAMES
# Ignore any and all function names for the 'Same name' heuristic?
self.ignore_all_names = self.get_value_for(
"ignore_all_names", config.DIFFING_IGNORE_ALL_FUNCTION_NAMES
)
# Ignore small functions?
self.ignore_small_functions = self.get_value_for(
"ignore_small_functions", config.DIFFING_IGNORE_SMALL_FUNCTIONS
)
# Export microcode instructions?
self.export_microcode = self.get_value_for(
"export_microcode", config.EXPORTING_USE_MICROCODE
)
# Number of CPU threads/cores to use?
cpus = cpu_count() - 1
if cpus < 1:
cpus = 1
self.cpu_count = self.get_value_for("CPU_COUNT", cpus)
# XXX: FIXME: Parallel diffing is broken outside of IDA due to parallelism problems
if not IS_IDA:
self.cpu_count = 1
####################################################################
def __del__(self):
if self.db is not None:
try:
if self.last_diff_db is not None:
tid = threading.current_thread().ident
if tid in self.dbs_dict:
db = self.dbs_dict[tid]
with db.cursor() as cur:
cur.execute(f'detach "{self.last_diff_db}"')
except:
pass
self.db_close()
def log(self, message):
log(message)
def log_refresh(self, message):
log_refresh(message)
def refresh(self):
"""
Fake member, it is only useful (and implemented) when running from within IDA.
"""
def load_hooks(self):
"""
Load the project specific python script, if any was set.
"""
if self.project_script is None or self.project_script == "":
return True
try:
log(f"Loading project specific Python script {self.project_script}")
module = load_source("diaphora_hooks", self.project_script)
except:
err = str(sys.exc_info()[1])
print(f"Error loading project specific Python script: {err}")
return False
keys = dir(module)
if "HOOKS" not in keys:
msg = "Error: The project specific script doesn't export the HOOKS dictionary"
log(msg)
return False
hooks = module.HOOKS
if "DiaphoraHooks" not in hooks:
msg = "Error: The project specific script exports the HOOK dictionary but it doesn't contain a 'DiaphoraHooks' entry."
log(msg)
return False
hook_class = hooks["DiaphoraHooks"]
self.hooks = hook_class(self)
return True
def get_value_for(self, value_name, default):
"""
Try to search for a DIAPHORA_<value_name> environment variable.
"""
value = os.getenv(f"DIAPHORA_{value_name.upper()}")
if value is not None:
if isinstance(value, type(default)):
value = type(default)(value)
return value
return default
# pylint: disable=protected-access
def open_db(self):
"""
Open the database @self.db_name.
"""
db = sqlite3_connect(self.db_name)
tid = threading.current_thread().ident
self.dbs_dict[tid] = db
if isinstance(threading.current_thread(), threading._MainThread):
self.db = db
self.create_schema()
# pylint: enable=protected-access
def get_db(self):
"""
Return the current thread's assigned database object.
"""
tid = threading.current_thread().ident
if tid not in self.dbs_dict:
self.open_db()
if self.last_diff_db is not None:
self.attach_database(self.last_diff_db)
return self.dbs_dict[tid]
def db_cursor(self):
"""
Get a database cursors. This is the preferred method to use instead of doing
db.cursor() every time one cursor is required somewhere.
"""
db = self.get_db()
return db.cursor()
# pylint: disable=protected-access
def db_close(self):
"""
Close the main database.
"""
tid = threading.current_thread().ident
if tid in self.dbs_dict:
self.dbs_dict[tid].close()
del self.dbs_dict[tid]
if isinstance(threading.current_thread(), threading._MainThread):
self.db.close()
# pylint: enable=protected-access
def create_schema(self):
"""
Create the database schema.
"""
cur = self.db_cursor()
try:
cur.execute("PRAGMA foreign_keys = ON")
for sql in schema.TABLES:
cur.execute(sql)
cur.execute("select 1 from version")
row = cur.fetchone()
if not row:
cur.execute("insert into main.version values (?)", (VERSION_VALUE,))
cur.execute("commit")
finally:
cur.close()
def create_indices(self):
"""
Create the required indices for the exported database.
"""
cur = self.db_cursor()
template = "create index if not exists idx_{index} on {table}({fields})"
try:
for i, index in enumerate(schema.INDICES):
table, fields = index
sql = template.format(index=i, table=table, fields=fields)
cur.execute(sql)
sql = "analyze"
cur.execute(sql)
finally:
cur.close()
def attach_database(self, diff_db):
"""
Attach @diff_db as the diffing database.
"""
cur = self.db_cursor()
try:
cur.execute(f'attach "{diff_db}" as diff')
finally:
cur.close()
def equal_db(self):
"""
Check if both opened databases (main and diff) are equal.
"""
cur = self.db_cursor()
ret = None
try:
sql = "select count(*) total from program p, diff.program dp where p.md5sum = dp.md5sum"
cur.execute(sql)
row = cur.fetchone()
ret = row["total"] == 1
if not ret:
sql = """select count(*) total
from (select id, address, size, nodes, edges
from functions
except
select id, address, size, nodes, edges
from diff.functions) x"""
cur.execute(sql)
row = cur.fetchone()
ret = row["total"] == 0
else:
log("Same MD5 in both databases")
finally:
cur.close()
return ret
def add_program_data(self, type_name, key, value):
"""
Add a row of program data to the database.
"""
cur = self.db_cursor()
try:
sql = "insert into main.program_data (name, type, value) values (?, ?, ?)"
values = (key, type_name, value)
cur.execute(sql, values)
finally:
cur.close()
def get_bb_id(self, addr):
"""
Get the id of the given basic block at address @addr
"""
cur = self.db_cursor()
rowid = None
try:
sql = "select id from basic_blocks where address = ?"
cur.execute(sql, (str(addr),))
row = cur.fetchone()
rowid = None
if row is not None:
rowid = row["id"]
finally:
cur.close()
return rowid
def get_valid_prop(self, prop):
"""
Get a valid property to insert into the SQLite database.
This is a hack for 64 bit architectures kernels.
"""
if isinstance(prop, int) and (prop > 0xFFFFFFFF or prop < -0xFFFFFFFF):
prop = str(prop)
elif isinstance(prop, bytes):
prop = prop.encode("utf-8")
return prop
def save_instructions_to_database(self, cur, bb_data, func_id):
"""
Save all the native assembly instructions in the basic block @bb_data to the
database.
"""
instructions_ids = {}
sql = """insert into main.instructions (address, mnemonic, disasm,
comment1, comment2, operand_names, name,
type, pseudocomment, pseudoitp, func_id,
asm_type)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'native')"""
cur_execute = cur.execute
for key in bb_data:
for instruction in bb_data[key]:
instruction_properties = []
for instruction_property in instruction:
if isinstance(instruction_property, (list, set)):
instruction_properties.append(
json.dumps(
list(instruction_property),
ensure_ascii=False,
cls=CBytesEncoder,
)
)
elif isinstance(instruction_property, int):
if instruction_property > 0x8000000000000000:
instruction_property = str(instruction_property)
instruction_properties.append(instruction_property)
else:
instruction_properties.append(instruction_property)
addr = instruction[0]
pseudocomment = None
pseudoitp = None
if addr in self.pseudo_comments:
pseudocomment, pseudoitp = self.pseudo_comments[addr]
instruction_properties.append(pseudocomment)
instruction_properties.append(pseudoitp)
instruction_properties.append(func_id)
cur.execute(sql, instruction_properties)
db_id = cur.lastrowid
instructions_ids[addr] = db_id
return cur_execute, instructions_ids
def insert_basic_blocks_to_database(
self, bb_data, cur_execute, cur, instructions_ids, bb_relations, func_id
):
"""
Insert basic blocks information as well as the relationship between assembly
instructions and basic blocks.
"""
num = 0
bb_ids = {}
sql1 = "insert into main.basic_blocks (num, address, asm_type) values (?, ?, 'native')"
sql2 = "insert into main.bb_instructions (basic_block_id, instruction_id) values (?, ?)"
self_get_bb_id = self.get_bb_id
for key in bb_data:
# Insert each basic block
num += 1
ins_ea = str(key)
last_bb_id = self_get_bb_id(ins_ea)
if last_bb_id is None:
cur_execute(sql1, (num, str(ins_ea)))
last_bb_id = cur.lastrowid
bb_ids[ins_ea] = last_bb_id
# Insert relations between basic blocks and instructions
insert_args = []
for instruction in bb_data[key]:
ins_id = instructions_ids[instruction[0]]
insert_args.append([last_bb_id, ins_id])
cur.executemany(sql2, insert_args)
# Insert relations between basic blocks
sql = "insert into main.bb_relations (parent_id, child_id) values (?, ?)"
insert_args = []
for key in bb_relations:
for bb in bb_relations[key]:
bb = str(bb)
key = str(key)
insert_args.append([bb_ids[key], bb_ids[bb]])
cur.executemany(sql, insert_args)
# And finally insert the functions to basic blocks relations
insert_args = []
sql = "insert into main.function_bblocks (function_id, basic_block_id, asm_type) values (?, ?, 'native')"
for key, bb_id in bb_ids.items():
insert_args.append([func_id, bb_id])
cur.executemany(sql, insert_args)
def save_microcode_instructions(
self, func_id, cur, cur_execute, microcode_bblocks, microcode_bbrelations
):
"""
Save all the microcode instructions in the basic block @bb_data to the database.
"""
sql_inst = """insert into main.instructions (address, mnemonic, disasm, comment1,
pseudocomment, func_id, asm_type)
values (?, ?, ?, ?, ?, ?, 'microcode')"""
sql_bblock = "insert into main.basic_blocks (num, address, asm_type) values (?, ?, 'microcode')"
sql_bbinst = "insert into main.bb_instructions (basic_block_id, instruction_id) values (?, ?)"
sql_bbrelations = (
"insert into main.bb_relations (parent_id, child_id) values (?, ?)"
)
sql_func_blocks = "insert into main.function_bblocks (function_id, basic_block_id, asm_type) values (?, ?, 'microcode')"
num = 0
for key in microcode_bblocks:
# Create a new microcode basic block
start_ea = self.get_valid_prop(microcode_bblocks[key]["start"])
cur_execute(sql_bblock, [num, start_ea])
bblock_id = cur.lastrowid
microcode_bblocks[key]["bblock_id"] = bblock_id
# Add the function -> basic block relation
cur_execute(sql_func_blocks, (func_id, bblock_id))
insert_args = []
for line in microcode_bblocks[key]["lines"]:
if line["mnemonic"] is not None:
address = self.get_valid_prop(line["address"])
mnemonic = line["mnemonic"]
disasm = line["line"]
comment1 = line["color_line"]
pseudocomment = line["comments"]
# Insert the microcode instruction
arguments = [
address,
mnemonic,
disasm,
comment1,
pseudocomment,
func_id,
]
cur_execute(sql_inst, arguments)
inst_id = cur.lastrowid
line["instruction_id"] = inst_id
# Add the microcode instrution to the current basic block
insert_args.append([bblock_id, inst_id])
cur.executemany(sql_bbinst, insert_args)
# Incrase the current basic block number
num += 1
# And, finally, insert the relationships between basic blocks
insert_args = []
for node in microcode_bbrelations:
parent_id = microcode_bblocks[node]["bblock_id"]
for children in microcode_bbrelations[node]:
# Microcode generates empty basic blocks, we don't want to do anything
# with them, just ignore...
if children in microcode_bblocks:
child_id = microcode_bblocks[children]["bblock_id"]
insert_args.append([parent_id, child_id])
cur.executemany(sql_bbrelations, insert_args)
def get_function_from_dictionary(self, d):
"""
Get a list ready to be used to insert rows from a given dictionary.
"""
list_dict = (
d["name"],
d["nodes"],
d["edges"],
d["indegree"],
d["outdegree"],
d["size"],
d["instructions"],
d["mnems"],
d["names"],
d["proto"],
d["cc"],
d["prime"],
d["f"],
d["comment"],
d["true_name"],
d["bytes_hash"],
d["pseudo"],
d["pseudo_lines"],
d["pseudo_hash1"],
d["pseudocode_primes"],
d["function_flags"],
d["asm"],
d["proto2"],
d["pseudo_hash2"],
d["pseudo_hash3"],
d["strongly_connected_size"],
d["loops"],
d["rva"],
d["bb_topological"],
d["strongly_connected_spp"],
d["clean_assembly"],
d["clean_pseudo"],
d["mnemonics_spp"],
d["switches"],
d["function_hash"],
d["bytes_sum"],
d["md_index"],
d["constants"],
d["constants_size"],
d["seg_rva"],
d["assembly_addrs"],
d["kgh_hash"],
d["source_file"],
d["userdata"],
d["microcode"],
d["clean_microcode"],
d["microcode_spp"],
d["microcode_bblocks"],
d["microcode_bbrelations"],
d["export_time"],
d["callers"],
d["callees"],
d["basic_blocks_data"],
d["bb_relations"],
)
return list_dict
# pylint: disable=redefined-outer-name
def create_function_dictionary(self, list_dict):
"""
Create a dictionary to be used with project specific hooks from a given list.
"""
(
name,
nodes,
edges,
indegree,
outdegree,
size,
instructions,
mnems,
names,
proto,
cc,
prime,
f,
comment,
true_name,
bytes_hash,
pseudo,
pseudo_lines,
pseudo_hash1,
pseudocode_primes,
function_flags,
asm,
proto2,
pseudo_hash2,
pseudo_hash3,
strongly_connected_size,
loops,
rva,
bb_topological,
strongly_connected_spp,
clean_assembly,
clean_pseudo,
mnemonics_spp,
switches,
function_hash,
bytes_sum,
md_index,
constants,
constants_size,
seg_rva,
assembly_addrs,
kgh_hash,
source_file,
userdata,
microcode,
clean_microcode,
microcode_spp,
export_time,
microcode_bblocks,
microcode_bbrelations,
callers,
callees,
basic_blocks_data,
bb_relations,
) = list_dict
d = dict(
name=name,
nodes=nodes,
edges=edges,
indegree=indegree,
outdegree=outdegree,
size=size,
instructions=instructions,
mnems=mnems,