forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jumptable.cc
2356 lines (2054 loc) · 71.2 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"
void LoadTable::saveXml(ostream &s) const
{
s << "<loadtable";
a_v_i(s,"size",size);
a_v_i(s,"num",num);
s << ">\n ";
addr.saveXml(s);
s << "</loadtable>\n";
}
void LoadTable::restoreXml(const Element *el,Architecture *glb)
{
istringstream s1(el->getAttributeValue("size"));
s1.unsetf(ios::dec | ios::hex | ios::oct);
s1 >> size;
istringstream s2(el->getAttributeValue("num"));
s2.unsetf(ios::dec | ios::hex | ios::oct);
s2 >> num;
const List &list( el->getChildren() );
List::const_iterator iter = list.begin();
addr = Address::restoreXml( *iter, glb);
}
void LoadTable::collapseTable(vector<LoadTable> &table)
{ // Assuming -table- is sorted, collapse sequential LoadTable entries into single LoadTable entries
if (table.empty()) return;
vector<LoadTable>::iterator iter,lastiter;
int4 count = 1;
iter = table.begin();
lastiter = iter;
Address 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 (collectloads) {
uintb off = getVarnodeValue(currentOp->getIn(1));
AddrSpace *spc = Address::getSpaceFromConst(currentOp->getIn(0)->getAddr());
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();
}
EmulateFunction::EmulateFunction(Funcdata *f)
: EmulatePcodeOp(f->getArch())
{
fd = f;
collectloads = false;
}
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
}
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);
}
void EmulateFunction::collectLoadPoints(vector<LoadTable> &res) const
{
if (loadpoints.empty()) return;
bool issorted = true;
vector<LoadTable>::const_iterator iter;
vector<LoadTable>::iterator lastiter;
iter = loadpoints.begin();
res.push_back( *iter ); // Copy the first entry
++iter;
lastiter = res.begin();
Address nextaddr = (*lastiter).addr + (*lastiter).size;
for(;iter!=loadpoints.end();++iter) {
if (issorted && (( (*iter).addr == nextaddr ) && ((*iter).size == (*lastiter).size))) {
(*lastiter).num += (*iter).num;
nextaddr = (*iter).addr + (*iter).size;
}
else {
issorted = false;
res.push_back( *iter );
}
}
if (!issorted) {
sort(res.begin(),res.end());
LoadTable::collapseTable(res);
}
}
/// 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) return false;
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) 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;
}
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;
}
bool JumpBasic::ispoint(Varnode *vn)
{ // Is this a possible switch variable
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;
}
uintb JumpBasic::backup2Switch(Funcdata *fd,uintb output,Varnode *outvn,Varnode *invn)
{ // Back up constant normalized value -outvn- to unnormalized
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;
}
void JumpBasic::findDeterminingVarnodes(PcodeOp *op,int4 slot)
{
vector<PcodeOp *> path;
vector<int4> slotpath;
PcodeOp *curop;
Varnode *curvn;
bool firstpoint = false; // Have not seen likely switch variable yet
path.push_back(op);
slotpath.push_back(slot);
do { // Traverse through tree of inputs to final address
curop = path.back();
curvn = curop->getIn(slotpath.back());
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,slotpath); // Take the current path as the result
firstpoint = true;
}
else // If we have already seen at least one possible
pathMeld.meld(path,slotpath);
}
slotpath.back() += 1;
while(slotpath.back() >= path.back()->numInput()) {
path.pop_back();
slotpath.pop_back();
if (path.empty()) break;
slotpath.back() += 1;
}
}
else { // This varnode is not pruned
path.push_back(curvn->getDef());
slotpath.push_back(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));
}
}
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;
}
GuardRecord::GuardRecord(PcodeOp *op,int4 path,const CircleRange &rng,Varnode *v)
{
cbranch = op;
indpath = path;
range = rng;
vn = v;
baseVn = quasiCopy(v,bitsPreserved,false); // Look for varnode whose bits are copied
}
int4 GuardRecord::valueMatch(Varnode *vn2,Varnode *baseVn2,int4 bitsPreserved2) const
{ // Return 0, if -vn- and -vn2- are not clearly the same value
// Return 1, if -vn- and -vn2- are clearly the same value
// Return 2, if -vn- and -vn2- are clearly the same value, pending no writes beteen the def of -vn- and -vn2-
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;
}
int4 GuardRecord::oneOffMatch(PcodeOp *op1,PcodeOp *op2)
{ // Return 1 if -op1- and -op2- produce exactly the same value, 0 if otherwise
// (one value is allowed to be the zero extension of the other)
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;
}
Varnode *GuardRecord::quasiCopy(Varnode *vn,int4 &bitsPreserved,bool noWholeValue)
{
Varnode *origVn = vn;
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) {
if (noWholeValue && (vn != origVn)) {
uintb inputMask = vn->getNZMask() | mask;
if (mask == inputMask)
return origVn; // vn contains whole value, -noWholeValue- indicates we should abort
}
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;
}
void PathMeld::internalIntersect(vector<int4> &parentMap)
{ // Calculate intersection of new path (marked vn's) with old path (commonVn)
// Put intersection back into commonVn
// Calculate parentMap : from old commonVn index to new commonVn index
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;
}
}
int4 PathMeld::meldOps(const vector<PcodeOp *> &path,int4 cutOff,const vector<int4> &parentMap)
{ // Meld old ops (opMeld) with new ops (path), updating rootVn with new commonVn order
// Ops should remain in (reverse) execution order
// Ops that split (use a vn not in intersection) and do not rejoin (have a predecessor vn in intersection)
// get cut
// If splitting ops arent can't be ordered with the existing meld, we get a new cut point
// 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]; // 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;
}
void PathMeld::truncatePaths(int4 cutPoint)
{ // Make sure all paths in opMeld terminate at -cutPoint- varnode
// and cut varnodes beyond the cutPoint out of the intersection (commonVn)
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
}
void PathMeld::set(const PathMeld &op2)
{
commonVn = op2.commonVn;
opMeld = op2.opMeld;
}
void PathMeld::set(const vector<PcodeOp *> &path,const vector<int4> &slot)
{
for(int4 i=0;i<path.size();++i) {
PcodeOp *op = path[i];
Varnode *vn = op->getIn(slot[i]);
opMeld.push_back(RootedOp(op,i));
commonVn.push_back(vn);
}
}
void PathMeld::set(PcodeOp *op,Varnode *vn)
{ // Set a single varnode and op as the path
commonVn.push_back(vn);
opMeld.push_back(RootedOp(op,0));
}
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();
}
void PathMeld::meld(vector<PcodeOp *> &path,vector<int4> &slot)
{ // Meld the new -path- into our collection of paths
// making sure all ops that split from the main path intersection eventually rejoin
vector<int4> parentMap;
for(int4 i=0;i<path.size();++i) {
Varnode *vn = path[i]->getIn(slot[i]);
vn->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) {
Varnode *vn = path[i]->getIn(slot[i]);
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);
slot.resize(cutOff);
}
PcodeOp *PathMeld::getEarliestOp(int4 pos) const
{ // Find "earliest" op that has commonVn[i] as input
for(int4 i=opMeld.size()-1;i>=0;--i) {
if (opMeld[i].rootVn == pos)
return opMeld[i].op;
}
return (PcodeOp *)0;
}
void JumpBasic::analyzeGuards(BlockBasic *bl,int4 pathout)
{ // Analyze each CBRANCH leading up to -bl- switch.
// (if pathout>=0, also analyze the CBRANCH in -bl- that chooses this path)
// Analyze the range restrictions on the various variables which allow
// control flow to pass through the CBRANCHs to the switch.
// Make note of all these restrictions in the guard list
// For later determination of the correct switch variable.
int4 i,j,indpath;
int4 maxbranch = 2; // Maximum number of CBRANCHs to consider
int4 maxpullback = 2;
bool usenzmask = (jumptable->getStage() == 0);
selectguards.clear();
BlockBasic *prevbl;
Varnode *vn;
for(i=0;i<maxbranch;++i) {
if ((pathout>=0)&&(bl->sizeOut()==2)) {
prevbl = bl;
bl = (BlockBasic *)prevbl->getOut(pathout);
indpath = pathout;
pathout = -1;
}
else {
pathout = -1; // Make sure not to use pathout next time around
for(;;) {
if (bl->sizeIn() != 1) return; // Assume only 1 path to switch
prevbl = (BlockBasic *)bl->getIn(0);
if (prevbl->sizeOut() != 1) break; // Is it possible to deviate from switch path in this block
bl = prevbl; // If not, back up to next block
}
indpath = bl->getInRevIndex(0);
}
PcodeOp *cbranch = prevbl->lastOp();
if ((cbranch==(PcodeOp *)0)||(cbranch->code() != CPUI_CBRANCH))
break;
bool toswitchval = (indpath == 1);
if (cbranch->isBooleanFlip())
toswitchval = !toswitchval;
bl = prevbl;
vn = cbranch->getIn(1);
CircleRange rng(toswitchval);
// The boolean variable could conceivably be the switch variable
int4 indpathstore = prevbl->getFlipPath() ? 1-indpath : indpath;
selectguards.push_back(GuardRecord(cbranch,indpathstore,rng,vn));
for(j=0;j<maxpullback;++j) {
Varnode *markup; // Throw away markup information
if (!vn->isWritten()) break;
vn = rng.pullBack(vn->getDef(),&markup,usenzmask);
if (vn == (Varnode *)0) break;
if (rng.isEmpty()) break;
selectguards.push_back(GuardRecord(cbranch,indpathstore,rng,vn));
}
}
}
void JumpBasic::calcRange(Varnode *vn,CircleRange &rng) const
{ // For a putative switch variable, calculate the range of
// possible values that variable can have AT the switch
// by using the precalculated guard ranges.
// Get an initial range, based on the size/type of -vn-
int4 stride = 1;
if (vn->isConstant())
rng = CircleRange(vn->getOffset(),vn->getSize());
else if (vn->isWritten() && vn->getDef()->isBoolOutput())
rng = CircleRange(0,2,1,1); // Only 0 or 1 possible
else { // Should we go ahead and use nzmask in all cases?
uintb maxValue = 0; // Every possible value
if (vn->isWritten()) {
PcodeOp *andop = vn->getDef();
if (andop->code() == CPUI_INT_AND) {
Varnode *constvn = andop->getIn(1);
if (constvn->isConstant()) {
maxValue = coveringmask( constvn->getOffset() );
maxValue = (maxValue + 1) & calc_mask(vn->getSize());
}
}
}
stride = getStride(vn);
rng = CircleRange(0,maxValue,vn->getSize(),stride);
}
// Intersect any guard ranges which apply to -vn-
int4 bitsPreserved;
Varnode *baseVn = GuardRecord::quasiCopy(vn, bitsPreserved, true);
vector<GuardRecord>::const_iterator iter;
for(iter=selectguards.begin();iter!=selectguards.end();++iter) {
const GuardRecord &guard( *iter );
int4 matchval = guard.valueMatch(vn,baseVn,bitsPreserved);
// if (matchval == 2) TODO: we need to check for aliases
if (matchval==0) continue;
if (rng.intersect(guard.getRange())!=0) continue;
}
// It may be an assumption that the switch value is positive
// in which case the guard might not check for it. If the
// size is too big, we try only positive values
if (rng.getSize() > 0x10000) {
CircleRange positive(0,(rng.getMask()>>1)+1,vn->getSize(),stride);
positive.intersect(rng);
if (!positive.isEmpty())
rng = positive;
}
}
void JumpBasic::findSmallestNormal(uint4 matchsize)
{ // Find normalized switch variable with smallest range of values
CircleRange rng;
uintb sz,maxsize;
varnodeIndex = 0;
calcRange(pathMeld.getVarnode(0),rng);
jrange->setRange(rng);
jrange->setStartVn(pathMeld.getVarnode(0));
jrange->setStartOp(pathMeld.getOp(0));
maxsize = rng.getSize();
for(uint4 i=1;i<pathMeld.numCommonVarnode();++i) {
if (maxsize == matchsize) // Found variable that gives (already recovered) size
return;
calcRange(pathMeld.getVarnode(i),rng);
sz = rng.getSize();
if (sz < maxsize) {
// Don't let a 1-byte switch variable get thru without a guard
if ((sz != 256)||(pathMeld.getVarnode(i)->getSize()!=1)) {
varnodeIndex = i;
maxsize = sz;
jrange->setRange(rng);
jrange->setStartVn(pathMeld.getVarnode(i));
jrange->setStartOp(pathMeld.getEarliestOp(i));
}
}