-
Notifications
You must be signed in to change notification settings - Fork 49
/
jumptable.cc
2827 lines (2513 loc) · 92.8 KB
/
jumptable.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
/* ###
* IP: GHIDRA
*
* 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
*
* http://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 "jumptable.hh"
#include "emulate.hh"
#include "flow.hh"
namespace ghidra {
AttributeId ATTRIB_LABEL = AttributeId("label",131);
AttributeId ATTRIB_NUM = AttributeId("num",132);
ElementId ELEM_BASICOVERRIDE = ElementId("basicoverride",211);
ElementId ELEM_DEST = ElementId("dest",212);
ElementId ELEM_JUMPTABLE = ElementId("jumptable",213);
ElementId ELEM_LOADTABLE = ElementId("loadtable",214);
ElementId ELEM_NORMADDR = ElementId("normaddr",215);
ElementId ELEM_NORMHASH = ElementId("normhash",216);
ElementId ELEM_STARTVAL = ElementId("startval",217);
const uint8 JumpValues::NO_LABEL = 0xBAD1ABE1BAD1ABE1;
/// \param encoder is the stream encoder
void LoadTable::encode(Encoder &encoder) const
{
encoder.openElement(ELEM_LOADTABLE);
encoder.writeSignedInteger(ATTRIB_SIZE, size);
encoder.writeSignedInteger(ATTRIB_NUM, num);
addr.encode(encoder);
encoder.closeElement(ELEM_LOADTABLE);
}
/// \param decoder is the stream decoder
void LoadTable::decode(Decoder &decoder)
{
uint4 elemId = decoder.openElement(ELEM_LOADTABLE);
size = decoder.readSignedInteger(ATTRIB_SIZE);
num = decoder.readSignedInteger(ATTRIB_NUM);
addr = Address::decode( decoder );
decoder.closeElement(elemId);
}
/// Sort the entries and collapse any contiguous sequences into a single LoadTable entry.
/// \param table is the list of entries to collapse
void LoadTable::collapseTable(vector<LoadTable> &table)
{
if (table.empty()) return;
// Test if the table is already sorted and contiguous entries
bool issorted = true;
vector<LoadTable>::iterator iter = table.begin();
int4 num = (*iter).num;
int4 size = (*iter).size;
Address nextaddr = (*iter).addr + size;
++iter;
for(;iter!=table.end();++iter) {
if ( (*iter).addr == nextaddr && (*iter).size == size) {
num += (*iter).num;
nextaddr = (*iter).addr + (*iter).size;
}
else {
issorted = false;
break;
}
}
if (issorted) {
// Table is sorted and contiguous.
table.resize(1); // Truncate everything but the first entry
table.front().num = num;
return;
}
sort(table.begin(),table.end());
int4 count = 1;
iter = table.begin();
vector<LoadTable>::iterator lastiter = iter;
nextaddr = (*iter).addr + (*iter).size * (*iter).num;
++iter;
for(;iter!=table.end();++iter) {
if (( (*iter).addr == nextaddr ) && ((*iter).size == (*lastiter).size)) {
(*lastiter).num += (*iter).num;
nextaddr = (*iter).addr + (*iter).size * (*iter).num;
}
else if (( nextaddr < (*iter).addr )|| ((*iter).size != (*lastiter).size)) {
// Starting a new table
lastiter++;
*lastiter = *iter;
nextaddr = (*iter).addr + (*iter).size * (*iter).num;
count += 1;
}
}
table.resize(count,LoadTable(nextaddr,0));
}
void EmulateFunction::executeLoad(void)
{
if (loadpoints != (vector<LoadTable> *)0) {
uintb off = getVarnodeValue(currentOp->getIn(1));
AddrSpace *spc = currentOp->getIn(0)->getSpaceFromConst();
off = AddrSpace::addressToByte(off,spc->getWordSize());
int4 sz = currentOp->getOut()->getSize();
loadpoints->push_back(LoadTable(Address(spc,off),sz));
}
EmulatePcodeOp::executeLoad();
}
void EmulateFunction::executeBranch(void)
{
throw LowlevelError("Branch encountered emulating jumptable calculation");
}
void EmulateFunction::executeBranchind(void)
{
throw LowlevelError("Indirect branch encountered emulating jumptable calculation");
}
void EmulateFunction::executeCall(void)
{
// Ignore calls, as presumably they have nothing to do with final address
fallthruOp();
}
void EmulateFunction::executeCallind(void)
{
// Ignore calls, as presumably they have nothing to do with final address
fallthruOp();
}
void EmulateFunction::executeCallother(void)
{
// Ignore callothers
fallthruOp();
}
/// \param f is the function to emulate within
EmulateFunction::EmulateFunction(Funcdata *f)
: EmulatePcodeOp(f->getArch())
{
fd = f;
loadpoints = (vector<LoadTable> *)0;
}
void EmulateFunction::setExecuteAddress(const Address &addr)
{
if (!addr.getSpace()->hasPhysical())
throw LowlevelError("Bad execute address");
currentOp = fd->target(addr);
if (currentOp == (PcodeOp *)0)
throw LowlevelError("Could not set execute address");
currentBehave = currentOp->getOpcode()->getBehavior();
}
uintb EmulateFunction::getVarnodeValue(Varnode *vn) const
{ // Get the value of a Varnode which is in a syntax tree
// We can't just use the memory location as, within the tree,
// this is just part of the label
if (vn->isConstant())
return vn->getOffset();
map<Varnode *,uintb>::const_iterator iter;
iter = varnodeMap.find(vn);
if (iter != varnodeMap.end())
return (*iter).second; // We have seen this varnode before
return getLoadImageValue(vn->getSpace(),vn->getOffset(),vn->getSize());
}
void EmulateFunction::setVarnodeValue(Varnode *vn,uintb val)
{
varnodeMap[vn] = val;
}
void EmulateFunction::fallthruOp(void)
{
lastOp = currentOp; // Keep track of lastOp for MULTIEQUAL
// Otherwise do nothing: outer loop is controlling execution flow
}
/// \brief Execute from a given starting point and value to the common end-point of the path set
///
/// Flow the given value through all paths in the path container to produce the
/// single output value.
/// \param val is the starting value
/// \param pathMeld is the set of paths to execute
/// \param startop is the starting PcodeOp within the path set
/// \param startvn is the Varnode holding the starting value
/// \return the calculated value at the common end-point
uintb EmulateFunction::emulatePath(uintb val,const PathMeld &pathMeld,
PcodeOp *startop,Varnode *startvn)
{
uint4 i;
for(i=0;i<pathMeld.numOps();++i)
if (pathMeld.getOp(i) == startop) break;
if (startop->code() == CPUI_MULTIEQUAL) { // If we start on a MULTIEQUAL
int4 j;
for(j=0;j<startop->numInput();++j) { // Is our startvn one of the branches
if (startop->getIn(j) == startvn)
break;
}
if ((j == startop->numInput())||(i==0)) // If not, we can't continue;
throw LowlevelError("Cannot start jumptable emulation with unresolved MULTIEQUAL");
// If the startvn was a branch of the MULTIEQUAL, emulate as if we just came from that branch
startvn = startop->getOut(); // So the output of the MULTIEQUAL is the new startvn (as if a COPY from old startvn)
i -= 1; // Move to the next instruction to be executed
startop = pathMeld.getOp(i);
}
if (i==pathMeld.numOps())
throw LowlevelError("Bad jumptable emulation");
if (!startvn->isConstant())
setVarnodeValue(startvn,val);
while(i>0) {
PcodeOp *curop = pathMeld.getOp(i);
--i;
setCurrentOp( curop );
try {
executeCurrentOp();
}
catch(DataUnavailError &err) {
ostringstream msg;
msg << "Could not emulate address calculation at " << curop->getAddr();
throw LowlevelError(msg.str());
}
}
Varnode *invn = pathMeld.getOp(0)->getIn(0);
return getVarnodeValue(invn);
}
/// The starting value for the range and the step is preserved. The
/// ending value is set so there are exactly the given number of elements
/// in the range.
/// \param nm is the given number
void JumpValuesRange::truncate(int4 nm)
{
int4 rangeSize = 8*sizeof(uintb) - count_leading_zeros(range.getMask());
rangeSize >>= 3;
uintb left = range.getMin();
int4 step = range.getStep();
uintb right = (left + step * nm) & range.getMask();
range.setRange(left, right, rangeSize, step);
}
uintb JumpValuesRange::getSize(void) const
{
return range.getSize();
}
bool JumpValuesRange::contains(uintb val) const
{
return range.contains(val);
}
bool JumpValuesRange::initializeForReading(void) const
{
if (range.getSize()==0) return false;
curval = range.getMin();
return true;
}
bool JumpValuesRange::next(void) const
{
return range.getNext(curval);
}
uintb JumpValuesRange::getValue(void) const
{
return curval;
}
Varnode *JumpValuesRange::getStartVarnode(void) const
{
return normqvn;
}
PcodeOp *JumpValuesRange::getStartOp(void) const
{
return startop;
}
JumpValues *JumpValuesRange::clone(void) const
{
JumpValuesRange *res = new JumpValuesRange();
res->range = range;
res->normqvn = normqvn;
res->startop = startop;
return res;
}
uintb JumpValuesRangeDefault::getSize(void) const
{
return range.getSize() + 1;
}
bool JumpValuesRangeDefault::contains(uintb val) const
{
if (extravalue == val)
return true;
return range.contains(val);
}
bool JumpValuesRangeDefault::initializeForReading(void) const
{
if (range.getSize()==0) {
curval = extravalue;
lastvalue = true;
}
else {
curval = range.getMin();
lastvalue = false;
}
return true;
}
bool JumpValuesRangeDefault::next(void) const
{
if (lastvalue) return false;
if (range.getNext(curval))
return true;
lastvalue = true;
curval = extravalue;
return true;
}
Varnode *JumpValuesRangeDefault::getStartVarnode(void) const
{
return lastvalue ? extravn : normqvn;
}
PcodeOp *JumpValuesRangeDefault::getStartOp(void) const
{
return lastvalue ? extraop : startop;
}
JumpValues *JumpValuesRangeDefault::clone(void) const
{
JumpValuesRangeDefault *res = new JumpValuesRangeDefault();
res->range = range;
res->normqvn = normqvn;
res->startop = startop;
res->extravalue = extravalue;
res->extravn = extravn;
res->extraop = extraop;
return res;
}
bool JumpModelTrivial::recoverModel(Funcdata *fd,PcodeOp *indop,uint4 matchsize,uint4 maxtablesize)
{
size = indop->getParent()->sizeOut();
return ((size != 0)&&(size<=matchsize));
}
void JumpModelTrivial::buildAddresses(Funcdata *fd,PcodeOp *indop,vector<Address> &addresstable,
vector<LoadTable> *loadpoints,vector<int4> *loadcounts) const
{
addresstable.clear();
BlockBasic *bl = indop->getParent();
for(int4 i=0;i<bl->sizeOut();++i) {
const BlockBasic *outbl = (const BlockBasic *)bl->getOut(i);
addresstable.push_back( outbl->getStart() );
}
}
void JumpModelTrivial::buildLabels(Funcdata *fd,vector<Address> &addresstable,vector<uintb> &label,const JumpModel *orig) const
{
for(uint4 i=0;i<addresstable.size();++i)
label.push_back(addresstable[i].getOffset()); // Address itself is the label
}
JumpModel *JumpModelTrivial::clone(JumpTable *jt) const
{
JumpModelTrivial *res = new JumpModelTrivial(jt);
res->size = size;
return res;
}
/// \param vn is the Varnode we are testing for pruning
/// \return \b true if the search should be pruned here
bool JumpBasic::isprune(Varnode *vn)
{
if (!vn->isWritten()) return true;
PcodeOp *op = vn->getDef();
if (op->isCall()||op->isMarker()) return true;
if (op->numInput()==0) return true;
return false;
}
/// \param vn is the given Varnode to test
/// \return \b false if it is impossible for the Varnode to be the switch variable
bool JumpBasic::ispoint(Varnode *vn)
{
if (vn->isConstant()) return false;
if (vn->isAnnotation()) return false;
if (vn->isReadOnly()) return false;
return true;
}
/// If the some of the least significant bits of the given Varnode are known to
/// be zero, translate this into a stride for the jumptable range.
/// \param vn is the given Varnode
/// \return the calculated stride = 1,2,4,...
int4 JumpBasic::getStride(Varnode *vn)
{
uintb mask = vn->getNZMask();
if ((mask & 0x3f)==0) // Limit the maximum stride we can return
return 32;
int4 stride = 1;
while((mask&1)==0) {
mask >>= 1;
stride <<= 1;
}
return stride;
}
/// \brief Back up the constant value in the output Varnode to the value in the input Varnode
///
/// This does the work of going from a normalized switch value to the unnormalized value.
/// PcodeOps between the output and input Varnodes must be reversible or an exception is thrown.
/// \param fd is the function containing the switch
/// \param output is the constant value to back up
/// \param outvn is the output Varnode of the data-flow
/// \param invn is the input Varnode to back up to
/// \return the recovered value associated with the input Varnode
uintb JumpBasic::backup2Switch(Funcdata *fd,uintb output,Varnode *outvn,Varnode *invn)
{
Varnode *curvn = outvn;
PcodeOp *op;
TypeOp *top;
int4 slot;
while(curvn != invn) {
op = curvn->getDef();
top = op->getOpcode();
for(slot=0;slot<op->numInput();++slot) // Find first non-constant input
if (!op->getIn(slot)->isConstant()) break;
if (op->getEvalType() == PcodeOp::binary) {
const Address &addr(op->getIn(1-slot)->getAddr());
uintb otherval;
if (!addr.isConstant()) {
MemoryImage mem(addr.getSpace(),4,1024,fd->getArch()->loader);
otherval = mem.getValue(addr.getOffset(),op->getIn(1-slot)->getSize());
}
else
otherval = addr.getOffset();
output = top->recoverInputBinary(slot,op->getOut()->getSize(),output,
op->getIn(slot)->getSize(),otherval);
curvn = op->getIn(slot);
}
else if (op->getEvalType() == PcodeOp::unary) {
output = top->recoverInputUnary(op->getOut()->getSize(),output,op->getIn(slot)->getSize());
curvn = op->getIn(slot);
}
else
throw LowlevelError("Bad switch normalization op");
}
return output;
}
/// If the Varnode has a restricted range due to masking via INT_AND, the maximum value of this range is returned.
/// Otherwise, 0 is returned, indicating that the Varnode can take all possible values.
/// \param vn is the given Varnode
/// \return the maximum value or 0
uintb JumpBasic::getMaxValue(Varnode *vn)
{
uintb maxValue = 0; // 0 indicates maximum possible value
if (!vn->isWritten())
return maxValue;
PcodeOp *op = vn->getDef();
if (op->code() == CPUI_INT_AND) {
Varnode *constvn = op->getIn(1);
if (constvn->isConstant()) {
maxValue = coveringmask( constvn->getOffset() );
maxValue = (maxValue + 1) & calc_mask(vn->getSize());
}
}
else if (op->code() == CPUI_MULTIEQUAL) { // Its possible the AND is duplicated across multiple blocks
int4 i;
for(i=0;i<op->numInput();++i) {
Varnode *subvn = op->getIn(i);
if (!subvn->isWritten()) break;
PcodeOp *andOp = subvn->getDef();
if (andOp->code() != CPUI_INT_AND) break;
Varnode *constvn = andOp->getIn(1);
if (!constvn->isConstant()) break;
if (maxValue < constvn->getOffset())
maxValue = constvn->getOffset();
}
if (i == op->numInput()) {
maxValue = coveringmask( maxValue );
maxValue = (maxValue + 1) & calc_mask(vn->getSize());
}
else
maxValue = 0;
}
return maxValue;
}
/// \brief Calculate the initial set of Varnodes that might be switch variables
///
/// Paths that terminate at the given PcodeOp are calculated and organized
/// in a PathMeld object that determines Varnodes that are common to all the paths.
/// \param op is the given PcodeOp
/// \param slot is input slot to the PcodeOp all paths must terminate at
void JumpBasic::findDeterminingVarnodes(PcodeOp *op,int4 slot)
{
vector<PcodeOpNode> path;
bool firstpoint = false; // Have not seen likely switch variable yet
path.push_back(PcodeOpNode(op,slot));
do { // Traverse through tree of inputs to final address
PcodeOpNode &node(path.back());
Varnode *curvn = node.op->getIn(node.slot);
if (isprune(curvn)) { // Here is a node of the tree
if (ispoint(curvn)) { // Is it a possible switch variable
if (!firstpoint) { // If it is the first possible
pathMeld.set(path); // Take the current path as the result
firstpoint = true;
}
else // If we have already seen at least one possible
pathMeld.meld(path);
}
path.back().slot += 1;
while(path.back().slot >= path.back().op->numInput()) {
path.pop_back();
if (path.empty()) break;
path.back().slot += 1;
}
}
else { // This varnode is not pruned
path.push_back(PcodeOpNode(curvn->getDef(),0));
}
} while(path.size() > 1);
if (pathMeld.empty()) { // Never found a likely point, which means that
// it looks like the address is uniquely determined
// but the constants/readonlys haven't been collapsed
pathMeld.set(op,op->getIn(slot));
}
}
/// \brief Check if the two given Varnodes are matching constants
///
/// \param vn1 is the first given Varnode
/// \param vn2 is the second given Varnode
/// \return \b true if the Varnodes are both constants with the same value
static bool matching_constants(Varnode *vn1,Varnode *vn2)
{
if (!vn1->isConstant()) return false;
if (!vn2->isConstant()) return false;
if (vn1->getOffset() != vn2->getOffset()) return false;
return true;
}
/// \param bOp is the CBRANCH \e guarding the switch
/// \param rOp is the PcodeOp immediately reading the Varnode
/// \param path is the specific branch to take from the CBRANCH to reach the switch
/// \param rng is the range of values causing the switch path to be taken
/// \param v is the Varnode holding the value controlling the CBRANCH
/// \param unr is \b true if the guard is duplicated across multiple blocks
GuardRecord::GuardRecord(PcodeOp *bOp,PcodeOp *rOp,int4 path,const CircleRange &rng,Varnode *v,bool unr)
{
cbranch = bOp;
readOp = rOp;
indpath = path;
range = rng;
vn = v;
baseVn = quasiCopy(v,bitsPreserved); // Look for varnode whose bits are copied
unrolled = unr;
}
/// \brief Determine if \b this guard applies to the given Varnode
///
/// The guard applies if we know the given Varnode holds the same value as the Varnode
/// attached to the guard. So we return:
/// - 0, if the two Varnodes do not clearly hold the same value.
/// - 1, if the two Varnodes clearly hold the same value.
/// - 2, if the two Varnode clearly hold the same value, pending no writes between their defining op.
///
/// \param vn2 is the given Varnode being tested against \b this guard
/// \param baseVn2 is the earliest Varnode from which the given Varnode is quasi-copied.
/// \param bitsPreserved2 is the number of potentially non-zero bits in the given Varnode
/// \return the matching code 0, 1, or 2
int4 GuardRecord::valueMatch(Varnode *vn2,Varnode *baseVn2,int4 bitsPreserved2) const
{
if (vn == vn2) return 1; // Same varnode, same value
PcodeOp *loadOp,*loadOp2;
if (bitsPreserved == bitsPreserved2) { // Are the same number of bits being copied
if (baseVn == baseVn2) // Are bits being copied from same varnode
return 1; // If so, values are the same
loadOp = baseVn->getDef(); // Otherwise check if different base varnodes hold same value
loadOp2 = baseVn2->getDef();
}
else {
loadOp = vn->getDef(); // Check if different varnodes hold same value
loadOp2 = vn2->getDef();
}
if (loadOp == (PcodeOp *)0) return 0;
if (loadOp2 == (PcodeOp *)0) return 0;
if (oneOffMatch(loadOp,loadOp2) == 1) // Check for simple duplicate calculations
return 1;
if (loadOp->code() != CPUI_LOAD) return 0;
if (loadOp2->code() != CPUI_LOAD) return 0;
if (loadOp->getIn(0)->getOffset() != loadOp2->getIn(0)->getOffset()) return 0;
Varnode *ptr = loadOp->getIn(1);
Varnode *ptr2 = loadOp2->getIn(1);
if (ptr == ptr2) return 2;
if (!ptr->isWritten()) return 0;
if (!ptr2->isWritten()) return 0;
PcodeOp *addop = ptr->getDef();
if (addop->code() != CPUI_INT_ADD) return 0;
Varnode *constvn = addop->getIn(1);
if (!constvn->isConstant()) return 0;
PcodeOp *addop2 = ptr2->getDef();
if (addop2->code() != CPUI_INT_ADD) return 0;
Varnode *constvn2 = addop2->getIn(1);
if (!constvn2->isConstant()) return 0;
if (addop->getIn(0) != addop2->getIn(0)) return 0;
if (constvn->getOffset() != constvn2->getOffset()) return 0;
return 2;
}
/// \brief Return 1 if the two given PcodeOps produce exactly the same value, 0 if otherwise
///
/// We up through only one level of PcodeOp calculation and only for certain binary ops
/// where the second parameter is a constant.
/// \param op1 is the first given PcodeOp to test
/// \param op2 is the second given PcodeOp
/// \return 1 if the same value is produced, 0 otherwise
int4 GuardRecord::oneOffMatch(PcodeOp *op1,PcodeOp *op2)
{
if (op1->code() != op2->code())
return 0;
switch(op1->code()) {
case CPUI_INT_AND:
case CPUI_INT_ADD:
case CPUI_INT_XOR:
case CPUI_INT_OR:
case CPUI_INT_LEFT:
case CPUI_INT_RIGHT:
case CPUI_INT_SRIGHT:
case CPUI_INT_MULT:
case CPUI_SUBPIECE:
if (op2->getIn(0) != op1->getIn(0)) return 0;
if (matching_constants(op2->getIn(1),op1->getIn(1)))
return 1;
break;
default:
break;
}
return 0;
}
/// \brief Compute the source of a quasi-COPY chain for the given Varnode
///
/// A value is a \b quasi-copy if a sequence of PcodeOps producing it always hold
/// the value as the least significant bits of their output Varnode, but the sequence
/// may put other non-zero values in the upper bits.
/// This method computes the earliest ancestor Varnode for which the given Varnode
/// can be viewed as a quasi-copy.
/// \param vn is the given Varnode
/// \param bitsPreserved will hold the number of least significant bits preserved by the sequence
/// \return the earliest source of the quasi-copy, which may just be the given Varnode
Varnode *GuardRecord::quasiCopy(Varnode *vn,int4 &bitsPreserved)
{
bitsPreserved = mostsigbit_set(vn->getNZMask()) + 1;
if (bitsPreserved == 0) return vn;
uintb mask = 1;
mask <<= bitsPreserved;
mask -= 1;
PcodeOp *op = vn->getDef();
Varnode *constVn;
while(op != (PcodeOp *)0) {
switch(op->code()) {
case CPUI_COPY:
vn = op->getIn(0);
op = vn->getDef();
break;
case CPUI_INT_AND:
constVn = op->getIn(1);
if (constVn->isConstant() && constVn->getOffset() == mask) {
vn = op->getIn(0);
op = vn->getDef();
}
else
op = (PcodeOp *)0;
break;
case CPUI_INT_OR:
constVn = op->getIn(1);
if (constVn->isConstant() && ((constVn->getOffset() | mask) == (constVn->getOffset() ^ mask))) {
vn = op->getIn(0);
op = vn->getDef();
}
else
op = (PcodeOp *)0;
break;
case CPUI_INT_SEXT:
case CPUI_INT_ZEXT:
if (op->getIn(0)->getSize() * 8 >= bitsPreserved) {
vn = op->getIn(0);
op = vn->getDef();
}
else
op = (PcodeOp *)0;
break;
case CPUI_PIECE:
if (op->getIn(1)->getSize() * 8 >= bitsPreserved) {
vn = op->getIn(1);
op = vn->getDef();
}
else
op = (PcodeOp *)0;
break;
case CPUI_SUBPIECE:
constVn = op->getIn(1);
if (constVn->isConstant() && constVn->getOffset() == 0) {
vn = op->getIn(0);
op = vn->getDef();
}
else
op = (PcodeOp *)0;
break;
default:
op = (PcodeOp *)0;
break;
}
}
return vn;
}
/// \brief Calculate intersection of a new Varnode path with the old path
///
/// The new path of Varnodes must all be \e marked. The old path, commonVn,
/// is replaced with the intersection. A map is created from the index of each
/// Varnode in the old path with its index in the new path. If the Varnode is
/// not in the intersection, its index is mapped to -1.
/// \param parentMap will hold the new index map
void PathMeld::internalIntersect(vector<int4> &parentMap)
{
vector<Varnode *> newVn;
int4 lastIntersect = -1;
for(int4 i=0;i<commonVn.size();++i) {
Varnode *vn = commonVn[i];
if (vn->isMark()) { // Look for previously marked varnode, so we know it is in both lists
lastIntersect = newVn.size();
parentMap.push_back(lastIntersect);
newVn.push_back(vn);
vn->clearMark();
}
else
parentMap.push_back(-1);
}
commonVn = newVn;
lastIntersect = -1;
for(int4 i=parentMap.size()-1;i>=0;--i) {
int4 val = parentMap[i];
if (val == -1) // Fill in varnodes that are cut out of intersection
parentMap[i] = lastIntersect; // with next earliest varnode that is in intersection
else
lastIntersect = val;
}
}
/// \brief Meld in PcodeOps from a new path into \b this container
///
/// Execution order of the PcodeOps in the container is maintained. Each PcodeOp, old or new,
/// has its split point from the common path recalculated.
/// PcodeOps that split (use a vn not in intersection) and do not rejoin
/// (have a predecessor Varnode in the intersection) get removed.
/// If splitting PcodeOps can't be ordered with the existing meld, we get a new cut point.
/// \param path is the new path of PcodeOps in sequence
/// \param cutOff is the number of PcodeOps with an input in the common path
/// \param parentMap is the map from old common Varnodes to the new common Varnodes
/// \return the index of the last (earliest) Varnode in the common path or -1
int4 PathMeld::meldOps(const vector<PcodeOpNode> &path,int4 cutOff,const vector<int4> &parentMap)
{
// First update opMeld.rootVn with new intersection information
for(int4 i=0;i<opMeld.size();++i) {
int4 pos = parentMap[opMeld[i].rootVn];
if (pos == -1) {
opMeld[i].op = (PcodeOp *)0; // Op split but did not rejoin
}
else
opMeld[i].rootVn = pos; // New index
}
// Do a merge sort, keeping ops in execution order
vector<RootedOp> newMeld;
int4 curRoot = -1;
int4 meldPos = 0; // Ops moved from old opMeld into newMeld
const BlockBasic *lastBlock = (const BlockBasic *)0;
for(int4 i=0;i<cutOff;++i) {
PcodeOp *op = path[i].op; // Current op in the new path
PcodeOp *curOp = (PcodeOp *)0;
while(meldPos < opMeld.size()) {
PcodeOp *trialOp = opMeld[meldPos].op; // Current op in the old opMeld
if (trialOp == (PcodeOp *)0) {
meldPos += 1;
continue;
}
if (trialOp->getParent() != op->getParent()) {
if (op->getParent() == lastBlock) {
curOp = (PcodeOp *)0; // op comes AFTER trialOp
break;
}
else if (trialOp->getParent() != lastBlock) {
// Both trialOp and op come from different blocks that are not the lastBlock
int4 res = opMeld[meldPos].rootVn; // Force truncatePath at (and above) this op
// Found a new cut point
opMeld = newMeld; // Take what we've melded so far
return res; // return the new cutpoint
}
}
else if (trialOp->getSeqNum().getOrder() <= op->getSeqNum().getOrder()) {
curOp = trialOp; // op is equal to or comes later than trialOp
break;
}
lastBlock = trialOp->getParent();
newMeld.push_back(opMeld[meldPos]); // Current old op moved into newMeld
curRoot = opMeld[meldPos].rootVn;
meldPos += 1;
}
if (curOp == op) {
newMeld.push_back(opMeld[meldPos]);
curRoot = opMeld[meldPos].rootVn;
meldPos += 1;
}
else {
newMeld.push_back(RootedOp(op,curRoot));
}
lastBlock = op->getParent();
}
opMeld = newMeld;
return -1;
}
/// \brief Truncate all paths at the given new Varnode
///
/// The given Varnode is provided as an index into the current common Varnode list.
/// All Varnodes and PcodeOps involved in execution before this new cut point are removed.
/// \param cutPoint is the given new Varnode
void PathMeld::truncatePaths(int4 cutPoint)
{
while(opMeld.size() > 1) {
if (opMeld.back().rootVn < cutPoint) // If we see op using varnode earlier than cut point
break; // Keep that and all subsequent ops
opMeld.pop_back(); // Otherwise cut the op
}
commonVn.resize(cutPoint); // Since intersection is ordered, just resize to cutPoint
}
/// \param op2 is the path container to copy from
void PathMeld::set(const PathMeld &op2)
{
commonVn = op2.commonVn;
opMeld = op2.opMeld;
}
/// This container is initialized to hold a single data-flow path.
/// \param path is the list of PcodeOpNode edges in the path (in reverse execution order)
void PathMeld::set(const vector<PcodeOpNode> &path)
{
for(int4 i=0;i<path.size();++i) {
const PcodeOpNode &node(path[i]);
Varnode *vn = node.op->getIn(node.slot);
opMeld.push_back(RootedOp(node.op,i));
commonVn.push_back(vn);
}
}
/// \param op is the one PcodeOp in the path
/// \param vn is the one Varnode (input to the PcodeOp) in the path
void PathMeld::set(PcodeOp *op,Varnode *vn)
{
commonVn.push_back(vn);
opMeld.push_back(RootedOp(op,0));
}
/// The new paths must all start at the common end-point of the paths in
/// \b this container. The new set of melded paths start at the original common start
/// point for \b this container, flow through this old common end-point, and end at
/// the new common end-point.
/// \param op2 is the set of paths to be appended
void PathMeld::append(const PathMeld &op2)
{
commonVn.insert(commonVn.begin(),op2.commonVn.begin(),op2.commonVn.end());
opMeld.insert(opMeld.begin(),op2.opMeld.begin(),op2.opMeld.end());
// Renumber all the rootVn refs to varnodes we have moved
for(int4 i=op2.opMeld.size();i<opMeld.size();++i)
opMeld[i].rootVn += op2.commonVn.size();
}
void PathMeld::clear(void)
{
commonVn.clear();
opMeld.clear();
}
/// Add the new path, recalculating the set of Varnodes common to all paths.
/// Paths are trimmed to ensure that any path that splits from the common intersection
/// must eventually rejoin.
/// \param path is the new path of PcodeOpNode edges to meld, in reverse execution order
void PathMeld::meld(vector<PcodeOpNode> &path)
{
vector<int4> parentMap;
for(int4 i=0;i<path.size();++i) {
PcodeOpNode &node(path[i]);
node.op->getIn(node.slot)->setMark(); // Mark varnodes in the new path, so its easy to see intersection
}
internalIntersect(parentMap); // Calculate varnode intersection, and map from old intersection -> new
int4 cutOff = -1;
// Calculate where the cutoff point is in the new path
for(int4 i=0;i<path.size();++i) {
PcodeOpNode &node(path[i]);
Varnode *vn = node.op->getIn(node.slot);
if (!vn->isMark()) { // If mark already cleared, we know it is in intersection
cutOff = i + 1; // Cut-off must at least be past this -vn-
}
else
vn->clearMark();
}
int4 newCutoff = meldOps(path,cutOff,parentMap); // Given cutoff point, meld in new ops
if (newCutoff >= 0) // If not all ops could be ordered
truncatePaths(newCutoff); // Cut off at the point where we couldn't order
path.resize(cutOff);
}
/// The starting Varnode, common to all paths, is provided as an index.
/// All PcodeOps up to the final BRANCHIND are (un)marked.
/// \param val is \b true for marking, \b false for unmarking
/// \param startVarnode is the index of the starting PcodeOp
void PathMeld::markPaths(bool val,int4 startVarnode)