-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathresults.cc
1655 lines (1515 loc) · 64.3 KB
/
results.cc
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
// Copyright 2011-2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "third_party/zynamics/bindiff/ida/results.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <exception>
#include <fstream>
#include <ios>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
// clang-format off
#include "third_party/zynamics/binexport/ida/begin_idasdk.inc" // NOLINT
#include <idp.hpp> // NOLINT
#include <bytes.hpp> // NOLINT
#include <funcs.hpp> // NOLINT
#include <frame.hpp> // NOLINT
#include <ida.hpp> // NOLINT
#include <kernwin.hpp> // NOLINT
#include <lines.hpp> // NOLINT
#include <netnode.hpp> // NOLINT
#include <name.hpp> // NOLINT
#include <ua.hpp> // NOLINT
#include <xref.hpp> // NOLINT
#if IDP_INTERFACE_VERSION >= 900
#include <typeinf.hpp> // NOLINT
#else
#include <enum.hpp> // NOLINT
#include <struct.hpp> // NOLINT
#endif
#include "third_party/zynamics/binexport/ida/end_idasdk.inc" // NOLINT
// clang-format on
#include "third_party/absl/container/flat_hash_map.h"
#include "third_party/absl/container/flat_hash_set.h"
#include "third_party/absl/log/check.h"
#include "third_party/absl/log/log.h"
#include "third_party/absl/memory/memory.h"
#include "third_party/absl/status/status.h"
#include "third_party/absl/strings/str_cat.h"
#include "third_party/absl/strings/string_view.h"
#include "third_party/absl/types/span.h"
#include "third_party/zynamics/bindiff/change_classifier.h"
#include "third_party/zynamics/bindiff/comment.h"
#include "third_party/zynamics/bindiff/database_writer.h"
#include "third_party/zynamics/bindiff/differ.h"
#include "third_party/zynamics/bindiff/fixed_points.h"
#include "third_party/zynamics/bindiff/flow_graph.h"
#include "third_party/zynamics/bindiff/ida/names.h"
#include "third_party/zynamics/bindiff/instruction.h"
#include "third_party/zynamics/bindiff/match/call_graph.h"
#include "third_party/zynamics/bindiff/match/context.h"
#include "third_party/zynamics/bindiff/match/flow_graph.h"
#include "third_party/zynamics/bindiff/reader.h"
#include "third_party/zynamics/bindiff/sqlite.h"
#include "third_party/zynamics/bindiff/statistics.h"
#include "third_party/zynamics/bindiff/writer.h"
#include "third_party/zynamics/binexport/binexport2.pb.h"
#include "third_party/zynamics/binexport/ida/names.h"
#include "third_party/zynamics/binexport/ida/ui.h"
#include "third_party/zynamics/binexport/ida/util.h"
#include "third_party/zynamics/binexport/util/filesystem.h"
#include "third_party/zynamics/binexport/util/format.h"
#include "third_party/zynamics/binexport/util/status_macros.h"
#include "third_party/zynamics/binexport/util/timer.h"
#include "third_party/zynamics/binexport/util/types.h"
namespace security::bindiff {
using binexport::FormatAddress;
using binexport::FormatFunctionName;
using binexport::GetDemangledName;
using binexport::GetName;
using binexport::HumanReadableDuration;
using binexport::ToStringView;
namespace {
absl::Status ReadTemporaryFlowGraph(Address address,
const FlowGraphInfos& flow_graph_infos,
CallGraph* call_graph,
FlowGraph* flow_graph,
Instruction::Cache* instruction_cache) {
auto info = flow_graph_infos.find(address);
if (info == flow_graph_infos.end()) {
return absl::NotFoundError(absl::StrCat("Flow graph not found for address",
FormatAddress(address)));
}
std::ifstream stream(call_graph->GetFilePath(), std::ios::binary);
BinExport2 proto;
if (!proto.ParseFromIstream(&stream)) {
return absl::UnknownError(absl::StrCat(
"Failed parsing protocol buffer for ", call_graph->GetFilePath()));
}
for (const auto& proto_flow_graph : proto.flow_graph()) {
// Entry point address is always set.
const auto address =
proto
.instruction(
proto.basic_block(proto_flow_graph.entry_basic_block_index())
.instruction_index(0)
.begin_index())
.address();
if (address == info->second.address) {
flow_graph->SetCallGraph(call_graph);
return flow_graph->Read(proto, proto_flow_graph, call_graph,
instruction_cache);
}
}
return absl::UnknownError(
absl::StrCat("Flow graph data not found for address ",
FormatAddress(info->second.address)));
}
// TODO(cblichmann): Move to names.h
void UpdateName(CallGraph* call_graph, Address address) {
const std::string& name = GetName(address);
const CallGraph::Vertex vertex = call_graph->GetVertex(address);
if (!name.empty() && name != call_graph->GetName(vertex)) {
call_graph->SetName(vertex, name);
const std::string& demangled_name = GetDemangledName(address);
if (demangled_name != name) {
call_graph->SetDemangledName(vertex, demangled_name);
} else {
call_graph->SetDemangledName(vertex, "");
}
}
}
// Sort by: similarity desc, confidence desc, address asc.
bool SortBySimilarity(const FixedPointInfo* one, const FixedPointInfo* two) {
CHECK(one && two);
return one->similarity == two->similarity
? (one->confidence == two->confidence
? one->primary < two->primary
: one->confidence > two->confidence)
: one->similarity > two->similarity;
}
bool PortFunctionName(FixedPoint* fixed_point) {
CallGraph* secondary_call_graph = fixed_point->GetSecondary()->GetCallGraph();
const Address secondary_address =
fixed_point->GetSecondary()->GetEntryPointAddress();
if (!secondary_call_graph->HasRealName(
secondary_call_graph->GetVertex(secondary_address))) {
return false; // No name to port
}
CallGraph* primary_call_graph = fixed_point->GetPrimary()->GetCallGraph();
const Address primary_address =
fixed_point->GetPrimary()->GetEntryPointAddress();
const func_t* function = get_func(static_cast<ea_t>(primary_address));
if (!function || function->start_ea != primary_address) {
return false; // Function does not exist in primary (manually deleted?)
}
const qstring buffer =
get_name(static_cast<ea_t>(primary_address), /*gtn_flags=*/0);
const std::string& name = fixed_point->GetSecondary()->GetName();
if (ToStringView(buffer) == name) {
return false; // Function already has the same name
}
set_name(static_cast<ea_t>(primary_address), name.c_str(),
SN_NOWARN | SN_CHECK);
const auto vertex = primary_call_graph->GetVertex(primary_address);
primary_call_graph->SetName(vertex, name);
primary_call_graph->SetDemangledName(
vertex, GetDemangledName(static_cast<ea_t>(primary_address)));
return true;
}
size_t SetComments(Address source, Address target,
const CommentsByOperatorId& comments,
FixedPoint* fixed_point = nullptr) {
int comment_count = 0;
for (auto i = comments.lower_bound({source, 0});
i != comments.end() && i->first.first == source; ++i, ++comment_count) {
CHECK(source == i->first.first);
const Comment& comment = i->second;
const Address address = target;
const int operand_id = i->first.second;
// Do not port auto-generated names (unfortunately this does not work for
// comments that were auto-generated).
if ((comment.type == Comment::ENUM || comment.type == Comment::LOCATION ||
comment.type == Comment::GLOBAL_REFERENCE ||
comment.type == Comment::LOCAL_REFERENCE) &&
!is_uname(comment.comment.c_str())) {
continue;
}
switch (comment.type) {
case Comment::REGULAR:
set_cmt(static_cast<ea_t>(address), comment.comment.c_str(),
comment.repeatable);
break;
case Comment::ENUM: {
#if IDP_INTERFACE_VERSION >= 900
if (is_enum0(get_full_flags(static_cast<ea_t>(address))) ||
is_enum1(get_full_flags(static_cast<ea_t>(address)))) {
tinfo_t tif;
if (get_tinfo(&tif, address) && tif.is_enum()) {
tif.rename_type(comment.comment.c_str());
}
}
#else
uint8_t serial;
if (is_enum0(get_full_flags(static_cast<ea_t>(address))) &&
operand_id == 0) {
const auto id =
get_enum_id(&serial, static_cast<ea_t>(address), operand_id);
if (id != BADNODE) {
set_enum_name(id, comment.comment.c_str());
}
}
if (is_enum1(get_full_flags(static_cast<ea_t>(address))) &&
operand_id == 1) {
const auto id =
get_enum_id(&serial, static_cast<ea_t>(address), operand_id);
if (id != BADNODE) {
set_enum_name(id, comment.comment.c_str());
}
}
#endif
break;
}
case Comment::FUNCTION:
if (func_t* function = get_func(static_cast<ea_t>(address));
function && function->start_ea == address) {
set_func_cmt(function, comment.comment.c_str(), comment.repeatable);
}
break;
case Comment::LOCATION:
if (fixed_point) {
PortFunctionName(fixed_point);
}
break;
case Comment::ANTERIOR:
if (const std::string existing_comment =
GetLineComments(address, LineComment::kAnterior);
existing_comment.rfind(comment.comment) == std::string::npos) {
add_extra_cmt(static_cast<ea_t>(address), /*isprev=*/true, "%s",
comment.comment.c_str());
}
break;
case Comment::POSTERIOR:
if (const std::string existing_comment =
GetLineComments(address, LineComment::kPosterior);
existing_comment.rfind(comment.comment) == std::string::npos) {
add_extra_cmt(static_cast<ea_t>(address), /*isprev=*/false, "%s",
comment.comment.c_str());
}
break;
case Comment::GLOBAL_REFERENCE: {
int count = 0;
xrefblk_t xb;
for (bool ok = xb.first_from(static_cast<ea_t>(address), XREF_DATA); ok;
ok = xb.next_from(), ++count) {
if (count == operand_id - UA_MAXOP - 1024) {
qstring current_name = get_name(xb.to, /*gtn_flags=*/0);
if (ToStringView(current_name) == comment.comment) {
set_name(xb.to, comment.comment.c_str(), SN_NOWARN | SN_CHECK);
}
break;
}
}
break;
}
case Comment::LOCAL_REFERENCE: {
func_t* function = get_func(static_cast<ea_t>(address));
if (!function) {
break;
}
#if IDP_INTERFACE_VERSION >= 900
tinfo_t frame_tif;
if (!get_func_frame(&frame_tif, function)) {
break;
}
udt_type_data_t udt_data;
if (!frame_tif.get_udt_details(&udt_data)) {
break;
}
#else
struc_t* frame = get_frame(function);
if (!frame) {
break;
}
#endif
insn_t instruction;
if (decode_insn(&instruction, address) <= 0) {
break;
}
for (int operand_num = 0; operand_num < UA_MAXOP; ++operand_num) {
const ea_t offset =
calc_stkvar_struc_offset(function, instruction, operand_num);
if (offset == BADADDR) {
continue;
}
if (operand_num == operand_id - UA_MAXOP - 2048) {
#if IDP_INTERFACE_VERSION >= 900
udm_t udm;
udm.offset = offset;
if (auto idx = frame_tif.find_udm(&udm, STRMEM_AUTO); idx != -1) {
frame_tif.rename_udm(idx, comment.comment.c_str());
}
#else
set_member_name(frame, offset, comment.comment.c_str());
#endif
}
}
break;
}
case Comment::STRUCTURE: {
/*
tid_t id = 0;
adiff_t disp = 0;
adiff_t delta = 0;
if (get_struct_operand(address, operand_num, &id, &disp, &delta)) {
// Bug: this must be recursive for nested structs
if (const struc_t* structure = get_struc(id)) {
set_struc_name(structure->id, comment.m_Comment.c_str());
}
// TODO: structure members
} */
break;
}
default:
LOG(INFO) << absl::StrCat(
"Unknown comment type ", comment.type, ": ", FormatAddress(source),
" -> ", FormatAddress(target), " ", i->second.comment);
break;
}
}
return comment_count;
}
size_t SetComments(FixedPoint* fixed_point,
const CommentsByOperatorId& comments, Address start_source,
Address end_source, Address start_target, Address end_target,
double min_confidence, double min_similarity) {
// Symbols and comments are always ported from secondary to primary:
const FlowGraph* source_flow_graph = fixed_point->GetSecondary();
const FlowGraph* target_flow_graph = fixed_point->GetPrimary();
// SetComments is called three times below which potentially sets a single
// comment multiple times. This is necessary however, because iterating over
// fixed points might miss comments otherwise. For instance, there may be a
// function fixed point but no corresponding instruction fixed point for the
// function's entry point address.
size_t counts = 0;
Address source = source_flow_graph->GetEntryPointAddress();
Address target = target_flow_graph->GetEntryPointAddress();
fixed_point->SetCommentsPorted(true);
auto address_pair_in_range = [start_source, end_source, start_target,
end_target](Address source, Address target) {
return source >= start_source && source <= end_source &&
target >= start_target && target <= end_target;
};
if (address_pair_in_range(source, target)) {
if (fixed_point->GetConfidence() >= min_confidence &&
fixed_point->GetSimilarity() >= min_similarity) {
counts += SetComments(source, target, comments, fixed_point);
counts += PortFunctionName(fixed_point);
} else {
// Skip whole function if similarity or confidence criteria aren't
// satisfied.
return counts;
}
}
FlowGraph::Vertex source_vertex = -1; // Invalid vertex
FlowGraph::Vertex target_vertex = -1; // Invalid vertex
for (const auto& basic_block : fixed_point->GetBasicBlockFixedPoints()) {
if (source_vertex != basic_block.GetSecondaryVertex() ||
target_vertex != basic_block.GetPrimaryVertex()) {
source_vertex = basic_block.GetSecondaryVertex();
target_vertex = basic_block.GetPrimaryVertex();
source = source_flow_graph->GetAddress(source_vertex);
target = target_flow_graph->GetAddress(target_vertex);
if (address_pair_in_range(source, target)) {
counts +=
SetComments(source, target, comments, /*fixed_point=*/nullptr);
}
}
for (const auto& instruction_match : basic_block.GetInstructionMatches()) {
source = instruction_match.second->GetAddress();
target = instruction_match.first->GetAddress();
if (address_pair_in_range(source, target)) {
counts +=
SetComments(source, target, comments, /*fixed_point=*/nullptr);
}
}
}
return counts;
}
std::string VisualDiffMessage(bool call_graph_match,
const std::string& database,
const std::string& primary_path,
Address primary_address,
const std::string& secondary_path,
Address secondary_address) {
return absl::StrCat("<BinDiffMatch type=\"",
call_graph_match ? "call_graph" : "flow_graph", "\">",
"<Database path =\"", database, "\"/><Primary path=\"",
primary_path, "\" address=\"", primary_address,
"\"/><Secondary path=\"", secondary_path, "\" address=\"",
secondary_address, "\"/></BinDiffMatch>");
}
// Maps algorithm names from the config file to their respective display names.
std::string GetMatchingStepDisplayName(absl::string_view name) {
static auto* algorithms =
[]() -> absl::flat_hash_map<std::string, std::string>* {
auto* algorithms = new absl::flat_hash_map<std::string, std::string>();
(*algorithms)[MatchingStep::kFunctionManualName] =
MatchingStep::kFunctionManualDisplayName;
(*algorithms)[MatchingStep::kFunctionCallReferenceName] =
MatchingStep::kFunctionCallReferenceDisplayName;
for (const auto* step : GetDefaultMatchingSteps()) {
(*algorithms)[step->name()] = step->display_name();
}
(*algorithms)[MatchingStepFlowGraph::kBasicBlockManualName] =
MatchingStepFlowGraph::kBasicBlockManualDisplayName;
(*algorithms)[MatchingStepFlowGraph::kBasicBlockPropagationName] =
MatchingStepFlowGraph::kBasicBlockPropagationDisplayName;
for (const auto* step : GetDefaultMatchingStepsBasicBlock()) {
(*algorithms)[step->name()] = step->display_name();
}
return algorithms;
}();
auto found = algorithms->find(name);
return found != algorithms->end() ? found->second : std::string(name);
}
} // namespace
Results::~Results() {
// Need to close this explicitly here as otherwise the DeleteTemporaryFiles()
// call below will fail (on Windows) due to locked db file.
temp_database_->Close();
DeleteFlowGraphs(&flow_graphs1_);
DeleteFlowGraphs(&flow_graphs2_);
DatabaseTransmuter::DeleteTempFile();
DeleteTemporaryFiles();
}
absl::StatusOr<std::unique_ptr<Results>> Results::Create() {
auto results = absl::WrapUnique(new Results());
NA_ASSIGN_OR_RETURN(results->temp_database_,
DatabaseWriter::Create("temporary.database", true));
return results;
}
void Results::set_modified() { modified_ = true; }
bool Results::is_modified() const { return modified_; }
void Results::DeleteTemporaryFiles() {
// Extremely dangerous, make very sure GetDirectory _never_ returns something
// like "C:".
auto temp_dir = GetTempDirectory("BinDiff");
if (!temp_dir.ok()) {
return;
}
// Don't care if this fails - only litters the temp dir a bit.
RemoveAll(*temp_dir).IgnoreError();
}
size_t Results::GetNumUnmatchedPrimary() const {
return indexed_flow_graphs1_.size();
}
Results::UnmatchedDescription Results::GetUnmatchedDescriptionPrimary(
size_t index) const {
return GetUnmatchedDescription(indexed_flow_graphs1_, index);
}
size_t Results::GetNumUnmatchedSecondary() const {
return indexed_flow_graphs2_.size();
}
Results::UnmatchedDescription Results::GetUnmatchedDescriptionSecondary(
size_t index) const {
return GetUnmatchedDescription(indexed_flow_graphs2_, index);
}
Results::UnmatchedDescription Results::GetUnmatchedDescription(
const IndexedFlowGraphs& flow_graphs, size_t index) const {
if (index >= flow_graphs.size()) {
return {};
}
const FlowGraphInfo& flow_graph_info = *flow_graphs[index];
// The primary IDB is loaded in IDA and the function name might have been
// changed manually, thus we need to propagate that information.
if (&flow_graphs == &indexed_flow_graphs1_) {
UpdateName(const_cast<CallGraph*>(&call_graph1_), flow_graph_info.address);
}
const std::string* name = flow_graph_info.demangled_name;
if (name == nullptr || name->empty()) {
name = flow_graph_info.name;
}
Results::UnmatchedDescription desc{};
desc.address = flow_graph_info.address;
desc.name = name != nullptr && !name->empty()
? *name
// Fallback, name may still be nullptr, as the underlying
// function simply might not have a name (b/263365607).
: FormatFunctionName(flow_graph_info.address);
desc.basic_block_count = flow_graph_info.basic_block_count;
desc.instruction_count = flow_graph_info.instruction_count;
desc.edge_count = flow_graph_info.edge_count;
return desc;
}
Address Results::GetPrimaryAddress(size_t index) const {
if (index >= indexed_flow_graphs1_.size()) {
return 0;
}
return indexed_flow_graphs1_[index]->address;
}
Address Results::GetSecondaryAddress(size_t index) const {
if (index >= indexed_flow_graphs2_.size()) {
return 0;
}
return indexed_flow_graphs2_[index]->address;
}
Address Results::GetMatchPrimaryAddress(size_t index) const {
if (index >= indexed_fixed_points_.size()) {
return 0;
}
return indexed_fixed_points_[index]->primary;
}
Address Results::GetMatchSecondaryAddress(size_t index) const {
if (index >= indexed_fixed_points_.size()) {
return 0;
}
return indexed_fixed_points_[index]->secondary;
}
absl::Status Results::IncrementalDiff() {
WaitBox wait_box("Performing incremental diff...");
if (is_incomplete()) {
NA_ASSIGN_OR_RETURN(std::string temp_dir,
GetOrCreateTempDirectory("BinDiff"));
const std::string incremental = JoinPath(temp_dir, "incremental.BinDiff");
NA_RETURN_IF_ERROR(::security::bindiff::Read(
call_graph1_.GetFilePath(), &call_graph1_, &flow_graphs1_,
&flow_graph_infos1_, &instruction_cache_));
NA_RETURN_IF_ERROR(::security::bindiff::Read(
call_graph2_.GetFilePath(), &call_graph2_, &flow_graphs2_,
&flow_graph_infos2_, &instruction_cache_));
NA_RETURN_IF_ERROR(CopyFile(input_filename_, incremental));
NA_ASSIGN_OR_RETURN(auto database, SqliteDatabase::Connect(incremental));
DatabaseTransmuter writer(database, fixed_point_infos_);
NA_RETURN_IF_ERROR(Write(&writer));
try {
DatabaseReader::ReadFullMatches(&database, &call_graph1_, &call_graph2_,
&flow_graphs1_, &flow_graphs2_,
&fixed_points_);
} catch (const std::runtime_error& message) {
return absl::UnknownError(message.what());
}
std::remove(incremental.c_str());
incomplete_ = false;
}
Timer<> timer;
MatchingContext context(call_graph1_, call_graph2_, flow_graphs1_,
flow_graphs2_, fixed_points_);
// Try to find any confirmed fixed points. If there aren't any just return.
bool has_confirmed_fixedpoints = false;
for (const FixedPoint& fixed_point : fixed_points_) {
if (fixed_point.GetMatchingStep() ==
absl::string_view(MatchingStep::kFunctionManualName)) {
has_confirmed_fixedpoints = true;
break;
}
}
if (!has_confirmed_fixedpoints) {
warning(
"No manually confirmed fixed points found. Please add some matches "
"or use the matched functions window context menu to confirm automatic "
"matches before running an incremental diff");
return absl::CancelledError("");
}
// Remove all non-manual matches from current result
for (auto it = fixed_points_.begin(), end = fixed_points_.end(); it != end;) {
FixedPoint& fixed_point = const_cast<FixedPoint&>(*it);
FlowGraph* primary = fixed_point.GetPrimary();
FlowGraph* secondary = fixed_point.GetSecondary();
if (fixed_point.GetMatchingStep() ==
absl::string_view{MatchingStep::kFunctionManualName}) {
++it;
continue; // Keep confirmed fixed points.
}
fixed_points_.erase(it++);
primary->ResetMatches();
secondary->ResetMatches();
temp_database_->DeleteFromTempDatabase(primary->GetEntryPointAddress(),
secondary->GetEntryPointAddress());
}
// These will get refilled by ShowResults().
indexed_flow_graphs1_.clear();
indexed_flow_graphs2_.clear();
indexed_fixed_points_.clear();
histogram_.clear();
counts_.clear();
// Diff
const MatchingSteps call_graph_steps = GetDefaultMatchingSteps();
const MatchingStepsFlowGraph basic_block_steps =
GetDefaultMatchingStepsBasicBlock();
Diff(&context, call_graph_steps, basic_block_steps);
// Refill fixed point info.
fixed_point_infos_.clear();
for (const FixedPoint& fixed_point : fixed_points_) {
FixedPointInfo info;
info.algorithm = FindString(fixed_point.GetMatchingStep());
info.confidence = fixed_point.GetConfidence();
info.evaluate = false;
info.flags = fixed_point.GetFlags();
info.primary = fixed_point.GetPrimary()->GetEntryPointAddress();
info.secondary = fixed_point.GetSecondary()->GetEntryPointAddress();
info.similarity = fixed_point.GetSimilarity();
info.comments_ported = fixed_point.GetCommentsPorted();
Counts counts;
Histogram histogram;
FlowGraphs dummy1;
dummy1.insert(fixed_point.GetPrimary());
FlowGraphs dummy2;
dummy2.insert(fixed_point.GetSecondary());
FixedPoints dummy3;
dummy3.insert(fixed_point);
GetCountsAndHistogram(dummy1, dummy2, dummy3, &histogram, &counts);
info.basic_block_count = counts[Counts::kBasicBlockMatchesLibrary] +
counts[Counts::kBasicBlockMatchesNonLibrary];
info.instruction_count = counts[Counts::kInstructionMatchesLibrary] +
counts[Counts::kInstructionMatchesNonLibrary];
info.edge_count = counts[Counts::kFlowGraphEdgeMatchesLibrary] +
counts[Counts::kFlowGraphEdgeMatchesNonLibrary];
fixed_point_infos_.insert(info);
}
LOG(INFO) << absl::StrCat(HumanReadableDuration(timer.elapsed()),
" for incremental matching.");
set_modified();
return absl::OkStatus();
}
size_t Results::GetNumStatistics() const {
return counts_.ui_entry_size() + histogram_.size() +
2 /* Similarity & Confidence */;
}
Results::StatisticDescription Results::GetStatisticDescription(
size_t index) const {
Results::StatisticDescription desc{};
if (index > GetNumStatistics()) {
return desc;
}
if (index < counts_.ui_entry_size()) {
const auto entry = counts_.GetEntry(index);
desc.name = std::string(entry.first);
desc.is_count = true;
desc.count = entry.second;
} else if (index < histogram_.size() + counts_.ui_entry_size()) {
index -= counts_.ui_entry_size();
auto it = histogram_.cbegin();
for (size_t nr = 0; it != histogram_.cend() && nr < index; ++it, ++nr) {
}
desc.name = GetMatchingStepDisplayName(it->first);
desc.is_count = true;
desc.count = it->second;
} else if (index == histogram_.size() + counts_.ui_entry_size() + 1) {
desc.name = "Similarity";
desc.is_count = false;
desc.value = similarity_;
} else {
desc.name = "Confidence";
desc.is_count = false;
desc.value = confidence_;
}
return desc;
}
absl::Status Results::DeleteMatches(absl::Span<const size_t> indices) {
if (indices.empty()) {
return absl::OkStatus();
}
auto num_indexed_fixed_points = indexed_fixed_points_.size();
for (const auto& index : indices) {
if (index >= num_indexed_fixed_points) {
return absl::InvalidArgumentError(
absl::StrCat("Index out of range: ", index));
}
// This is quite involved, especially if results were loaded and not
// calculated:
// - Recalculate statistics
// - Remove fixed point information
// - Remove matching flow graph pointer from both graphs if loaded
// - Remove fixed point if loaded
// [ - Recalculate similarity and confidence ]
// - Update all views
// - Be prepared to save .BinDiff result file (again, tricky if it wasn't
// loaded fully)
const FixedPointInfo& fixed_point_info = *indexed_fixed_points_[index];
const auto primary_address = fixed_point_info.primary;
const auto secondary_address = fixed_point_info.secondary;
auto flow_graph_info_entry1 = flow_graph_infos1_.find(primary_address);
DCHECK(flow_graph_info_entry1 != flow_graph_infos1_.end());
auto flow_graph_info_entry2 = flow_graph_infos2_.find(secondary_address);
DCHECK(flow_graph_info_entry2 != flow_graph_infos2_.end());
temp_database_->DeleteFromTempDatabase(primary_address, secondary_address);
if (call_graph2_.IsLibrary(call_graph2_.GetVertex(secondary_address)) ||
call_graph1_.IsLibrary(call_graph1_.GetVertex(primary_address))) {
counts_[Counts::kFunctionMatchesLibrary] -= 1;
counts_[Counts::kBasicBlockMatchesLibrary] -=
fixed_point_info.basic_block_count;
counts_[Counts::kInstructionMatchesLibrary] -=
fixed_point_info.instruction_count;
counts_[Counts::kFlowGraphEdgeMatchesLibrary] -=
fixed_point_info.edge_count;
} else {
counts_[Counts::kFunctionMatchesNonLibrary] -= 1;
counts_[Counts::kBasicBlockMatchesNonLibrary] -=
fixed_point_info.basic_block_count;
counts_[Counts::kInstructionMatchesNonLibrary] -=
fixed_point_info.instruction_count;
counts_[Counts::kFlowGraphEdgeMatchesNonLibrary] -=
fixed_point_info.edge_count;
}
auto& algorithm_count = histogram_[*fixed_point_info.algorithm];
if (algorithm_count > 0) {
--algorithm_count;
}
// TODO(cblichmann): Tree search, this is O(n^2) when deleting all matches.
if (!is_incomplete()) {
for (auto it = fixed_points_.begin(), end = fixed_points_.end();
it != end; ++it) {
auto* primary_flow_graph = it->GetPrimary();
auto* secondary_flow_graph = it->GetSecondary();
if (primary_flow_graph->GetEntryPointAddress() == primary_address &&
secondary_flow_graph->GetEntryPointAddress() == secondary_address) {
fixed_points_.erase(it);
primary_flow_graph->ResetMatches();
secondary_flow_graph->ResetMatches();
break;
}
}
}
indexed_flow_graphs1_.push_back(&flow_graph_info_entry1->second);
indexed_flow_graphs2_.push_back(&flow_graph_info_entry2->second);
indexed_fixed_points_[index] = nullptr; // Mark for deletion
DCHECK(fixed_point_infos_.find(fixed_point_info) !=
fixed_point_infos_.end());
fixed_point_infos_.erase(fixed_point_info);
}
// Clear out zero entries from histogram.
for (auto it = histogram_.begin(), end = histogram_.end(); it != end;) {
if (it->second == 0) {
histogram_.erase(it++);
} else {
++it;
}
}
// Erase indexed fixed points that were marked for deletion.
indexed_fixed_points_.erase(std::remove(indexed_fixed_points_.begin(),
indexed_fixed_points_.end(), nullptr),
indexed_fixed_points_.end());
num_indexed_fixed_points = indexed_fixed_points_.size();
DCHECK(num_indexed_fixed_points == fixed_point_infos_.size());
DCHECK(is_incomplete() || num_indexed_fixed_points == fixed_points_.size());
set_modified();
should_reset_selection_ = true;
return absl::OkStatus();
}
FlowGraph* FindGraph(FlowGraphs& graphs, // NOLINT(runtime/references)
Address address) {
// TODO(cblichmann): Graphs are sorted, we don't need to search everything.
for (auto i = graphs.begin(), end = graphs.end(); i != end; ++i) {
if ((*i)->GetEntryPointAddress() == address) {
return *i;
}
}
return 0;
}
absl::Status Results::AddMatch(Address primary, Address secondary) {
try {
FixedPointInfo fixed_point_info;
fixed_point_info.algorithm = FindString(MatchingStep::kFunctionManualName);
fixed_point_info.confidence = 1.0;
fixed_point_info.basic_block_count = 0;
fixed_point_info.edge_count = 0;
fixed_point_info.instruction_count = 0;
fixed_point_info.primary = primary;
fixed_point_info.secondary = secondary;
fixed_point_info.similarity = 0.0;
fixed_point_info.flags = 0;
fixed_point_info.comments_ported = false;
// Results have been loaded: we need to reload flow graphs and recreate
// basic block fixed points.
if (is_incomplete()) {
FlowGraph primary_graph;
FlowGraph secondary_graph;
FixedPoint fixed_point;
SetupTemporaryFlowGraphs(fixed_point_info, primary_graph, secondary_graph,
fixed_point, true);
Counts counts;
Histogram histogram;
FlowGraphs dummy1;
dummy1.insert(&primary_graph);
FlowGraphs dummy2;
dummy2.insert(&secondary_graph);
FixedPoints dummy3;
dummy3.insert(fixed_point);
GetCountsAndHistogram(dummy1, dummy2, dummy3, &histogram, &counts);
fixed_point.SetMatchingStep(MatchingStep::kFunctionManualName);
fixed_point.SetSimilarity(GetSimilarityScore(
primary_graph, secondary_graph, histogram, counts));
ClassifyChanges(&fixed_point);
fixed_point_info.basic_block_count =
counts[Counts::kBasicBlockMatchesLibrary] +
counts[Counts::kBasicBlockMatchesNonLibrary];
fixed_point_info.instruction_count =
counts[Counts::kInstructionMatchesLibrary] +
counts[Counts::kInstructionMatchesNonLibrary];
fixed_point_info.edge_count =
counts[Counts::kFlowGraphEdgeMatchesLibrary] +
counts[Counts::kFlowGraphEdgeMatchesNonLibrary];
fixed_point_info.similarity = fixed_point.GetSimilarity();
fixed_point_info.flags = fixed_point.GetFlags();
temp_database_->WriteToTempDatabase(fixed_point);
DeleteTemporaryFlowGraphs();
} else {
FlowGraph* primary_graph = FindGraph(flow_graphs1_, primary);
FlowGraph* secondary_graph = FindGraph(flow_graphs2_, secondary);
if (!primary_graph || primary_graph->GetEntryPointAddress() != primary ||
!secondary_graph ||
secondary_graph->GetEntryPointAddress() != secondary) {
return absl::InternalError("Invalid graphs in AddMatch()");
}
FixedPoint& fixed_point(const_cast<FixedPoint&>(
*fixed_points_
.insert(FixedPoint(primary_graph, secondary_graph,
MatchingStep::kFunctionManualName))
.first));
MatchingContext context(call_graph1_, call_graph2_, flow_graphs1_,
flow_graphs2_, fixed_points_);
primary_graph->SetFixedPoint(&fixed_point);
secondary_graph->SetFixedPoint(&fixed_point);
FindFixedPointsBasicBlock(&fixed_point, &context,
GetDefaultMatchingStepsBasicBlock());
Counts counts;
Histogram histogram;
FlowGraphs dummy1;
dummy1.insert(primary_graph);
FlowGraphs dummy2;
dummy2.insert(secondary_graph);
FixedPoints dummy3;
dummy3.insert(fixed_point);
GetCountsAndHistogram(dummy1, dummy2, dummy3, &histogram, &counts);
fixed_point.SetSimilarity(GetSimilarityScore(
*primary_graph, *secondary_graph, histogram, counts));
fixed_point.SetConfidence(fixed_point_info.confidence);
ClassifyChanges(&fixed_point);
fixed_point_info.basic_block_count =
counts[Counts::kBasicBlockMatchesLibrary] +
counts[Counts::kBasicBlockMatchesNonLibrary];
fixed_point_info.instruction_count =
counts[Counts::kInstructionMatchesLibrary] +
counts[Counts::kInstructionMatchesNonLibrary];
fixed_point_info.edge_count =
counts[Counts::kFlowGraphEdgeMatchesLibrary] +
counts[Counts::kFlowGraphEdgeMatchesNonLibrary];
fixed_point_info.similarity = fixed_point.GetSimilarity();
fixed_point_info.flags = fixed_point.GetFlags();
}
fixed_point_infos_.insert(fixed_point_info);
indexed_fixed_points_.push_back(const_cast<FixedPointInfo*>(
&*fixed_point_infos_.find(fixed_point_info)));
std::sort(indexed_fixed_points_.begin(), indexed_fixed_points_.end(),
&SortBySimilarity);
if (call_graph2_.IsLibrary(
call_graph2_.GetVertex(fixed_point_info.secondary)) ||
flow_graph_infos2_.find(fixed_point_info.secondary) ==
flow_graph_infos2_.end() ||
call_graph1_.IsLibrary(
call_graph1_.GetVertex(fixed_point_info.primary)) ||
flow_graph_infos1_.find(fixed_point_info.primary) ==
flow_graph_infos1_.end()) {
counts_[Counts::kFunctionMatchesLibrary] += 1;
counts_[Counts::kBasicBlockMatchesLibrary] +=
fixed_point_info.basic_block_count;
counts_[Counts::kInstructionMatchesLibrary] +=
fixed_point_info.instruction_count;
counts_[Counts::kFlowGraphEdgeMatchesLibrary] +=
fixed_point_info.edge_count;
} else {
counts_[Counts::kFunctionMatchesNonLibrary] += 1;
counts_[Counts::kBasicBlockMatchesNonLibrary] +=
fixed_point_info.basic_block_count;
counts_[Counts::kInstructionMatchesNonLibrary] +=
fixed_point_info.instruction_count;
counts_[Counts::kFlowGraphEdgeMatchesNonLibrary] +=
fixed_point_info.edge_count;
}
histogram_[*fixed_point_info.algorithm]++;
FlowGraphInfo& primary_info(
flow_graph_infos1_.find(fixed_point_info.primary)->second);
FlowGraphInfo& secondary_info(
flow_graph_infos2_.find(fixed_point_info.secondary)->second);
indexed_flow_graphs1_.erase(std::find(indexed_flow_graphs1_.begin(),
indexed_flow_graphs1_.end(),
&primary_info));
indexed_flow_graphs2_.erase(std::find(indexed_flow_graphs2_.begin(),
indexed_flow_graphs2_.end(),
&secondary_info));
set_modified();
} catch (const std::exception& message) {
return absl::InternalError(
absl::StrCat("Error adding manual match: ", message.what()));
} catch (...) {
return absl::UnknownError("Error adding manual match");
}
return absl::OkStatus();
}
size_t Results::GetNumMatches() const { return indexed_fixed_points_.size(); }
Results::MatchDescription Results::GetMatchDescription(size_t index) const {
if (index >= indexed_fixed_points_.size()) {