-
Notifications
You must be signed in to change notification settings - Fork 50
/
coreaction.cc
5633 lines (5214 loc) · 194 KB
/
coreaction.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 "coreaction.hh"
#include "condexe.hh"
#include "double.hh"
#include "subflow.hh"
namespace ghidra {
/// \brief A stack equation
struct StackEqn {
int4 var1; ///< Variable with 1 coefficient
int4 var2; ///< Variable with -1 coefficient
int4 rhs; ///< Right hand side of the equation
static bool compare(const StackEqn &a,const StackEqn &b); ///< Order two equations
};
/// \brief A class that solves for stack-pointer changes across unknown sub-functions
class StackSolver {
vector<StackEqn> eqs; ///< Known equations based on operations that explicitly change the stack-pointer
vector<StackEqn> guess; ///< Guessed equations for underdetermined systems
vector<Varnode *> vnlist; ///< The indexed set of variables, one for each reference to the stack-pointer
vector<int4> companion; ///< Index of companion input for variable produced by CPUI_INDIRECT
Address spacebase; ///< Starting address of the stack-pointer
vector<int4> soln; ///< Collected solutions (corresponding to array of variables)
int4 missedvariables; ///< Number of variables for which we are missing an equation
void duplicate(void); ///< Duplicate each equation, multiplying by -1
void propagate(int4 varnum,int4 val); ///< Propagate solution for one variable to other variables
public:
void solve(void); ///< Solve the system of equations
void build(const Funcdata &data,AddrSpace *id,int4 spcbase); ///< Build the system of equations
int4 getNumVariables(void) const { return vnlist.size(); } ///< Get the number of variables in the system
Varnode *getVariable(int4 i) const { return vnlist[i]; } ///< Get the i-th Varnode variable
int4 getCompanion(int4 i) const { return companion[i]; } ///< Get the i-th variable's companion index
int4 getSolution(int4 i) const { return soln[i]; } ///< Get the i-th variable's solution
};
/// \param a is the first equation to compare
/// \param b is the second
/// \return true if the first equation comes before the second
bool StackEqn::compare(const StackEqn &a,const StackEqn &b)
{
return (a.var1<b.var1);
}
/// Given a solution for one variable, look for equations containing the variable
/// and attempt to solve for the other variable. Continue propagating new
/// solutions to other equations to find even more solutions. Populate
/// the \b soln array with the solutions.
/// \param varnum is the index of the initial variable
/// \param val is the solution for the variable
void StackSolver::propagate(int4 varnum,int4 val)
{
if (soln[varnum] != 65535) return; // This variable already specified
soln[varnum] = val;
StackEqn eqn;
vector<int4> workstack;
workstack.reserve(soln.size());
workstack.push_back(varnum);
vector<StackEqn>::iterator top;
while(!workstack.empty()) {
varnum = workstack.back();
workstack.pop_back();
eqn.var1 = varnum;
top = lower_bound(eqs.begin(),eqs.end(),eqn,StackEqn::compare);
while((top!=eqs.end())&&((*top).var1 == varnum)) {
int4 var2 = (*top).var2;
if (soln[var2] == 65535) {
soln[var2] = soln[varnum]-(*top).rhs;
workstack.push_back(var2);
}
++top;
}
}
}
void StackSolver::duplicate(void)
{
int4 size,i;
StackEqn eqn;
size = eqs.size();
for(i=0;i<size;++i) {
eqn.var1 = eqs[i].var2;
eqn.var2 = eqs[i].var1;
eqn.rhs = -eqs[i].rhs;
eqs.push_back(eqn);
}
stable_sort(eqs.begin(),eqs.end(),StackEqn::compare);
}
void StackSolver::solve(void)
{
// Use guesses to resolve subsystems not uniquely determined
int4 i,size,var1,var2,count,lastcount;
soln.clear();
soln.resize(vnlist.size(),65535); // Initialize solutions vector
duplicate(); // Duplicate and sort the equations
propagate(0,0); // We know one variable
size = guess.size();
lastcount = size+2;
do {
count = 0;
for(i=0;i<size;++i) {
var1 = guess[i].var1;
var2 = guess[i].var2;
if ((soln[var1]!=65535)&&(soln[var2]==65535))
propagate(var2,soln[var1]-guess[i].rhs);
else if ((soln[var1]==65535)&&(soln[var2]!=65535))
propagate(var1,soln[var2]+guess[i].rhs);
else if ((soln[var1]==65535)&&(soln[var2]==65535))
count += 1;
}
if (count == lastcount) break;
lastcount = count;
} while(count > 0);
}
/// Collect references to the stack-pointer as variables, and examine their defining PcodeOps
/// to determine equations and coefficient.
/// \param data is the function being analyzed
/// \param id is the \e stack address space
/// \param spcbase is the index, relative to the stack space, of the stack pointer
void StackSolver::build(const Funcdata &data,AddrSpace *id,int4 spcbase)
{
const VarnodeData &spacebasedata(id->getSpacebase(spcbase));
spacebase = Address(spacebasedata.space,spacebasedata.offset);
VarnodeLocSet::const_iterator begiter,enditer;
begiter = data.beginLoc(spacebasedata.size,spacebase);
enditer = data.endLoc(spacebasedata.size,spacebase);
while(begiter != enditer) { // All instances of the spacebase
if ((*begiter)->isFree()) break;
vnlist.push_back(*begiter);
companion.push_back(-1);
++begiter;
}
missedvariables = 0;
if (vnlist.empty()) return;
if (!vnlist[0]->isInput())
throw LowlevelError("Input value of stackpointer is not used");
vector<Varnode *>::iterator iter;
StackEqn eqn;
for(int4 i=1;i<vnlist.size();++i) {
Varnode *vn = vnlist[i];
Varnode *othervn,*constvn;
PcodeOp *op = vn->getDef();
if (op->code() == CPUI_INT_ADD) {
othervn = op->getIn(0);
constvn = op->getIn(1);
if (othervn->isConstant()) {
constvn = othervn;
othervn = op->getIn(1);
}
if (!constvn->isConstant()) { missedvariables+=1; continue; }
if (othervn->getAddr() != spacebase) { missedvariables+=1; continue; }
iter = lower_bound(vnlist.begin(),vnlist.end(),othervn,Varnode::comparePointers);
eqn.var1 = i;
eqn.var2 = iter-vnlist.begin();
eqn.rhs = constvn->getOffset();
eqs.push_back(eqn);
}
else if (op->code() == CPUI_COPY) {
othervn = op->getIn(0);
if (othervn->getAddr() != spacebase) { missedvariables+=1; continue; }
iter = lower_bound(vnlist.begin(),vnlist.end(),othervn,Varnode::comparePointers);
eqn.var1 = i;
eqn.var2 = iter-vnlist.begin();
eqn.rhs = 0;
eqs.push_back(eqn);
}
else if (op->code() == CPUI_INDIRECT) {
othervn = op->getIn(0);
if (othervn->getAddr() != spacebase) { missedvariables += 1; continue; }
iter = lower_bound(vnlist.begin(),vnlist.end(),othervn,Varnode::comparePointers);
eqn.var1 = i;
eqn.var2 = iter-vnlist.begin();
companion[i] = eqn.var2;
Varnode *iopvn = op->getIn(1);
if (iopvn->getSpace()->getType()==IPTR_IOP) { // If INDIRECT is due call
PcodeOp *iop = PcodeOp::getOpFromConst(iopvn->getAddr());
FuncCallSpecs *fc = data.getCallSpecs(iop); // Look up function proto
if (fc != (FuncCallSpecs *)0) {
if (fc->getExtraPop() != ProtoModel::extrapop_unknown) { // Double check that extrapop is unknown
eqn.rhs = fc->getExtraPop(); // As the deindirect process may have filled it in
eqs.push_back(eqn);
continue;
}
}
}
eqn.rhs = 4; // Otherwise make a guess
guess.push_back(eqn);
}
else if (op->code() == CPUI_MULTIEQUAL) {
for(int4 j=0;j<op->numInput();++j) {
othervn = op->getIn(j);
if (othervn->getAddr() != spacebase) { missedvariables += 1; continue; }
iter = lower_bound(vnlist.begin(),vnlist.end(),othervn,Varnode::comparePointers);
eqn.var1 = i;
eqn.var2 = iter-vnlist.begin();
eqn.rhs = 0;
eqs.push_back(eqn);
}
}
else if (op->code() == CPUI_INT_AND) {
// This can occur if a function aligns its stack pointer
othervn = op->getIn(0);
constvn = op->getIn(1);
if (othervn->isConstant()) {
constvn = othervn;
othervn = op->getIn(1);
}
if (!constvn->isConstant()) { missedvariables+=1; continue; }
if (othervn->getAddr() != spacebase) { missedvariables+=1; continue; }
iter = lower_bound(vnlist.begin(),vnlist.end(),othervn,Varnode::comparePointers);
eqn.var1 = i;
eqn.var2 = iter-vnlist.begin();
eqn.rhs = 0; // Treat this as a copy
eqs.push_back(eqn);
}
else
missedvariables += 1;
}
}
/// \brief Calculate stack-pointer change across \e undetermined sub-functions
///
/// If there are sub-functions for which \e extra \e pop is not explicit,
/// do full linear analysis to (attempt to) recover the values.
/// \param data is the function to analyze
/// \param stackspace is the space associated with the stack-pointer
/// \param spcbase is the index (relative to the stackspace) of the stack-pointer
void ActionStackPtrFlow::analyzeExtraPop(Funcdata &data,AddrSpace *stackspace,int4 spcbase)
{
ProtoModel *myfp = data.getArch()->evalfp_called;
if (myfp == (ProtoModel *)0)
myfp = data.getArch()->defaultfp;
if (myfp->getExtraPop()!=ProtoModel::extrapop_unknown) return;
StackSolver solver;
try {
solver.build(data,stackspace,spcbase);
} catch(LowlevelError &err) {
ostringstream s;
s << "Stack frame is not setup normally: " << err.explain;
data.warningHeader(s.str());
return;
}
if (solver.getNumVariables() == 0) return;
solver.solve(); // Solve the equations
Varnode *invn = solver.getVariable(0);
bool warningprinted = false;
for(int4 i=1;i<solver.getNumVariables();++i) {
Varnode *vn = solver.getVariable(i);
int4 soln = solver.getSolution(i);
if (soln == 65535) {
if (!warningprinted) {
data.warningHeader("Unable to track spacebase fully for "+stackspace->getName());
warningprinted = true;
}
continue;
}
PcodeOp *op = vn->getDef();
if (op->code() == CPUI_INDIRECT) {
Varnode *iopvn = op->getIn(1);
if (iopvn->getSpace()->getType()==IPTR_IOP) {
PcodeOp *iop = PcodeOp::getOpFromConst(iopvn->getAddr());
FuncCallSpecs *fc = data.getCallSpecs(iop);
if (fc != (FuncCallSpecs *)0) {
int4 soln2 = 0;
int4 comp = solver.getCompanion(i);
if (comp >= 0)
soln2 = solver.getSolution(comp);
fc->setEffectiveExtraPop(soln-soln2);
}
}
}
vector<Varnode *> paramlist;
paramlist.push_back(invn);
int4 sz = invn->getSize();
paramlist.push_back(data.newConstant(sz,soln&calc_mask(sz)));
data.opSetOpcode(op,CPUI_INT_ADD);
data.opSetAllInput(op,paramlist);
}
return;
}
/// \brief Is the given Varnode defined as a pointer relative to the stack-pointer?
///
/// Return true if -vn- is defined as the stackpointer input plus a constant (or zero)
/// This works through the general case and the special case when the constant is zero.
/// The constant value is passed-back to the caller.
/// \param spcbasein is the Varnode holding the \e input value of the stack-pointer
/// \param vn is the Varnode to check for relativeness
/// \param constval is a reference for passing back the constant offset
/// \return true if \b vn is stack relative
bool ActionStackPtrFlow::isStackRelative(Varnode *spcbasein,Varnode *vn,uintb &constval)
{
if (spcbasein == vn) {
constval = 0;
return true;
}
if (!vn->isWritten()) return false;
PcodeOp *addop = vn->getDef();
if (addop->code() != CPUI_INT_ADD) return false;
if (addop->getIn(0) != spcbasein) return false;
Varnode *constvn = addop->getIn(1);
if (!constvn->isConstant()) return false;
constval = constvn->getOffset();
return true;
}
/// \brief Adjust the LOAD where the stack-pointer alias has been recovered.
///
/// We've matched a LOAD with its matching store, now convert the LOAD op to a COPY of what was stored.
/// \param data is the function being analyzed
/// \param loadop is the LOAD op to adjust
/// \param storeop is the matching STORE op
/// \return true if the adjustment is successful
bool ActionStackPtrFlow::adjustLoad(Funcdata &data,PcodeOp *loadop,PcodeOp *storeop)
{
Varnode *vn = storeop->getIn(2);
if (vn->isConstant())
vn = data.newConstant(vn->getSize(),vn->getOffset());
else if (vn->isFree())
return false;
data.opRemoveInput(loadop,1);
data.opSetOpcode(loadop,CPUI_COPY);
data.opSetInput(loadop,vn,0);
return true;
}
/// \brief Link LOAD to matching STORE of a constant
///
/// Try to find STORE op using same stack relative pointer as a given LOAD op.
/// If we find it and the STORE stores a constant, change the LOAD to a COPY.
/// \param data is the function owning the LOAD
/// \param id is the stackspace
/// \param spcbasein is the stack-pointer
/// \param loadop is the given LOAD op
/// \param constz is the stack relative offset of the LOAD pointer
/// \return 1 if we successfully change LOAD to COPY, 0 otherwise
int4 ActionStackPtrFlow::repair(Funcdata &data,AddrSpace *id,Varnode *spcbasein,PcodeOp *loadop,uintb constz)
{
int4 loadsize = loadop->getOut()->getSize();
BlockBasic *curblock = loadop->getParent();
list<PcodeOp *>::iterator begiter = curblock->beginOp();
list<PcodeOp *>::iterator iter = loadop->getBasicIter();
for(;;) {
if (iter == begiter) {
if (curblock->sizeIn() != 1) return 0; // Can trace back to next basic block if only one path
curblock = (BlockBasic *)curblock->getIn(0);
begiter = curblock->beginOp();
iter = curblock->endOp();
continue;
}
else {
--iter;
}
PcodeOp *curop = *iter;
if (curop->isCall()) return 0; // Don't try to trace aliasing through a call
if (curop->code() == CPUI_STORE) {
Varnode *ptrvn = curop->getIn(1);
Varnode *datavn = curop->getIn(2);
uintb constnew;
if (isStackRelative(spcbasein,ptrvn,constnew)) {
if ((constnew == constz)&&(loadsize == datavn->getSize())) {
// We found the matching store
if (adjustLoad(data,loadop,curop))
return 1;
return 0;
}
else if ((constnew <= constz + (loadsize-1))&&(constnew+(datavn->getSize()-1)>=constz))
return 0;
}
else
return 0; // Any other kind of STORE we can't solve aliasing
}
else {
Varnode *outvn = curop->getOut();
if (outvn != (Varnode *)0) {
if (outvn->getSpace() == id) return 0; // Stack already traced, too late
}
}
}
}
/// \brief Find any stack pointer clogs and pass it on to the repair routines
///
/// A stack pointer \b clog is a constant addition to the stack-pointer,
/// but where the constant comes from the stack.
/// \param data is the function to analyze
/// \param id is the stack space
/// \param spcbase is the index of the stack-pointer relative to the stack space
/// \return the number of clogs that were repaired
int4 ActionStackPtrFlow::checkClog(Funcdata &data,AddrSpace *id,int4 spcbase)
{
const VarnodeData &spacebasedata(id->getSpacebase(spcbase));
Address spacebase = Address(spacebasedata.space,spacebasedata.offset);
VarnodeLocSet::const_iterator begiter,enditer;
int4 clogcount = 0;
begiter = data.beginLoc(spacebasedata.size,spacebase);
enditer = data.endLoc(spacebasedata.size,spacebase);
Varnode *spcbasein;
if (begiter == enditer) return clogcount;
spcbasein = *begiter;
++begiter;
if (!spcbasein->isInput()) return clogcount;
while(begiter != enditer) {
Varnode *outvn = *begiter;
++begiter;
if (!outvn->isWritten()) continue;
PcodeOp *addop = outvn->getDef();
if (addop->code() != CPUI_INT_ADD) continue;
Varnode *y = addop->getIn(1);
if (!y->isWritten()) continue; // y must not be a constant
Varnode *x = addop->getIn(0); // is y is not constant than x (in position 0) isn't either
uintb constx;
if (!isStackRelative(spcbasein,x,constx)) { // If x is not stack relative
x = y; // Swap x and y
y = addop->getIn(0);
if (!isStackRelative(spcbasein,x,constx)) continue; // Now maybe the new x is stack relative
}
PcodeOp *loadop = y->getDef();
if (loadop->code() == CPUI_INT_MULT) { // If we multiply
Varnode *constvn = loadop->getIn(1);
if (!constvn->isConstant()) continue;
if (constvn->getOffset() != calc_mask(constvn->getSize())) continue; // Must multiply by -1
y = loadop->getIn(0);
if (!y->isWritten()) continue;
loadop = y->getDef();
}
if (loadop->code() != CPUI_LOAD) continue;
Varnode *ptrvn = loadop->getIn(1);
uintb constz;
if (!isStackRelative(spcbasein,ptrvn,constz)) continue;
clogcount += repair(data,id,spcbasein,loadop,constz);
}
return clogcount;
}
int4 ActionStackPtrFlow::apply(Funcdata &data)
{
if (analysis_finished)
return 0;
if (stackspace == (AddrSpace *)0) {
analysis_finished = true; // No stack to do analysis on
return 0;
}
int4 numchange = checkClog(data,stackspace,0);
if (numchange > 0) {
count += 1;
}
if (numchange == 0) {
analyzeExtraPop(data,stackspace,0);
analysis_finished = true;
}
return 0;
}
/// \brief Examine the PcodeOps using the given Varnode to determine possible lane sizes
///
/// Run through the defining op and any descendant ops of the given Varnode, looking for
/// CPUI_PIECE and CPUI_SUBPIECE. Use these to determine possible lane sizes and
/// register them with the given LanedRegister object.
/// \param vn is the given Varnode
/// \param allowedLanes is used to determine if a putative lane size is allowed
/// \param checkLanes collects the possible lane sizes
void ActionLaneDivide::collectLaneSizes(Varnode *vn,const LanedRegister &allowedLanes,LanedRegister &checkLanes)
{
list<PcodeOp *>::const_iterator iter = vn->beginDescend();
int4 step = 0; // 0 = descendants, 1 = def, 2 = done
if (iter == vn->endDescend()) {
step = 1;
}
while(step < 2) {
int4 curSize; // Putative lane size
if (step == 0) {
PcodeOp *op = *iter;
++iter;
if (iter == vn->endDescend())
step = 1;
if (op->code() != CPUI_SUBPIECE) continue; // Is the big register split into pieces
curSize = op->getOut()->getSize();
}
else {
step = 2;
if (!vn->isWritten()) continue;
PcodeOp *op = vn->getDef();
if (op->code() != CPUI_PIECE) continue; // Is the big register formed from smaller pieces
curSize = op->getIn(0)->getSize();
int4 tmpSize = op->getIn(1)->getSize();
if (tmpSize < curSize)
curSize = tmpSize;
}
if (allowedLanes.allowedLane(curSize))
checkLanes.addLaneSize(curSize); // Register this possible size
}
}
/// \brief Search for a likely lane size and try to divide a single Varnode into these lanes
///
/// There are different ways to search for a lane size:
///
/// Mode 0: Collect putative lane sizes based on the local ops using the Varnode. Attempt
/// to divide based on each of those lane sizes in turn.
///
/// Mode 1: Similar to mode 0, except we allow for SUBPIECE operations that truncate to
/// variables that are smaller than the lane size.
///
/// Mode 2: Attempt to divide based on a default lane size.
/// \param data is the function being transformed
/// \param vn is the given single Varnode
/// \param lanedRegister is acceptable set of lane sizes for the Varnode
/// \param mode is the lane size search mode (0, 1, or 2)
/// \return \b true if the Varnode (and its data-flow) was successfully split
bool ActionLaneDivide::processVarnode(Funcdata &data,Varnode *vn,const LanedRegister &lanedRegister,int4 mode)
{
LanedRegister checkLanes; // Lanes we are going to try, initialized to no lanes
bool allowDowncast = (mode > 0);
if (mode < 2)
collectLaneSizes(vn,lanedRegister,checkLanes);
else {
checkLanes.addLaneSize(4); // Default lane size
}
LanedRegister::const_iterator enditer = checkLanes.end();
for(LanedRegister::const_iterator iter=checkLanes.begin();iter!=enditer;++iter) {
int4 curSize = *iter;
LaneDescription description(lanedRegister.getWholeSize(),curSize); // Lane scheme dictated by curSize
LaneDivide laneDivide(&data,vn,description,allowDowncast);
if (laneDivide.doTrace()) {
laneDivide.apply();
count += 1; // Indicate a change was made
return true;
}
}
return false;
}
int4 ActionLaneDivide::apply(Funcdata &data)
{
map<VarnodeData,const LanedRegister *>::const_iterator iter;
for(int4 mode=0;mode<3;++mode) {
bool allStorageProcessed = true;
for(iter=data.beginLaneAccess();iter!=data.endLaneAccess();++iter) {
const LanedRegister *lanedReg = (*iter).second;
Address addr = (*iter).first.getAddr();
int4 sz = (*iter).first.size;
VarnodeLocSet::const_iterator viter = data.beginLoc(sz,addr);
VarnodeLocSet::const_iterator venditer = data.endLoc(sz,addr);
bool allVarnodesProcessed = true;
while(viter != venditer) {
Varnode *vn = *viter;
if (processVarnode(data, vn, *lanedReg, mode)) {
viter = data.beginLoc(sz,addr);
venditer = data.endLoc(sz, addr); // Recalculate bounds
allVarnodesProcessed = true;
}
else {
++viter;
allVarnodesProcessed = false;
}
}
if (!allVarnodesProcessed)
allStorageProcessed = false;
}
if (allStorageProcessed) break;
}
data.clearLanedAccessMap();
data.setLanedRegGenerated();
return 0;
}
int4 ActionSegmentize::apply(Funcdata &data)
{
int4 numops = data.getArch()->userops.numSegmentOps();
if (numops==0) return 0;
if (localcount>0) return 0; // Only perform once
localcount = 1; // Mark as having performed once
vector<Varnode *> bindlist;
bindlist.push_back((Varnode *)0);
bindlist.push_back((Varnode *)0);
for(int4 i=0;i<numops;++i) {
SegmentOp *segdef = data.getArch()->userops.getSegmentOp(i);
if (segdef == (SegmentOp *)0) continue;
AddrSpace *spc = segdef->getSpace();
list<PcodeOp *>::const_iterator iter,enditer;
iter = data.beginOp(CPUI_CALLOTHER);
enditer = data.endOp(CPUI_CALLOTHER);
int4 uindex = segdef->getIndex();
while(iter != enditer) {
PcodeOp *segroot = *iter++;
if (segroot->isDead()) continue;
if (segroot->getIn(0)->getOffset() != uindex) continue;
if (!segdef->unify(data,segroot,bindlist)) {
ostringstream err;
err << "Segment op in wrong form at ";
segroot->getAddr().printRaw(err);
throw LowlevelError(err.str());
}
if (segdef->getNumVariableTerms()==1)
bindlist[0] = data.newConstant(4,0);
// Redefine the op as a segmentop
data.opSetOpcode(segroot,CPUI_SEGMENTOP);
data.opSetInput(segroot,data.newVarnodeSpace(spc),0);
data.opSetInput(segroot,bindlist[0],1);
data.opSetInput(segroot,bindlist[1],2);
for(int4 j=segroot->numInput()-1;j>2;--j) // Remove anything else
data.opRemoveInput(segroot,j);
count += 1;
}
}
return 0;
}
int4 ActionForceGoto::apply(Funcdata &data)
{
data.getOverride().applyForceGoto(data);
return 0;
}
int4 ActionConstbase::apply(Funcdata &data)
{
if (data.getBasicBlocks().getSize()==0) return 0; // No blocks
// Get start block, which is constructed to have nothing
// falling into it
BlockBasic *bb = (BlockBasic *)data.getBasicBlocks().getBlock(0);
int4 injectid = data.getFuncProto().getInjectUponEntry();
if (injectid >= 0) {
InjectPayload *payload = data.getArch()->pcodeinjectlib->getPayload(injectid);
data.doLiveInject(payload,bb->getStart(),bb,bb->beginOp());
}
const TrackedSet trackset( data.getArch()->context->getTrackedSet(data.getAddress()));
for(int4 i=0;i<trackset.size();++i) {
const TrackedContext &ctx(trackset[i]);
Address addr(ctx.loc.space,ctx.loc.offset);
PcodeOp *op = data.newOp(1,bb->getStart());
data.newVarnodeOut(ctx.loc.size,addr,op);
Varnode *vnin = data.newConstant(ctx.loc.size,ctx.val);
data.opSetOpcode(op,CPUI_COPY);
data.opSetInput(op,vnin,0);
data.opInsertBegin(op,bb);
}
return 0;
}
// int4 ActionCse::apply(Funcdata &data)
// {
// vector< pair<uintm,PcodeOp *> > list;
// vector<Varnode *> vlist;
// PcodeOp *op;
// list<PcodeOp *>::const_iterator iter;
// uintm hash;
// for(iter=data.op_alive_begin();iter!=data.op_alive_end();++iter) {
// op = *iter;
// hash = op->getCseHash();
// if (hash == 0) continue;
// list.push_back(pair<uintm,PcodeOp *>(hash,op));
// }
// if (list.empty()) return 0;
// cseEliminateList(data,list,vlist);
// while(!vlist.empty()) {
// count += 1; // Indicate that changes have been made
// list.clear();
// cse_build_fromvarnode(list,vlist);
// vlist.clear();
// cseEliminateList(data,list,vlist);
// }
// return 0;
// }
/// We are substituting either -out1- for -out2- OR -out2- for -out1-
/// Return true if we prefer substituting -out2- for -out1-
/// \param out1 is one output
/// \param out2 is the other output
/// \return preference
bool ActionMultiCse::preferredOutput(Varnode *out1,Varnode *out2)
{
// Prefer the output that is used in a CPUI_RETURN
list<PcodeOp *>::const_iterator iter,enditer;
enditer = out1->endDescend();
for(iter=out1->beginDescend();iter!=enditer;++iter) {
PcodeOp *op = *iter;
if (op->code() == CPUI_RETURN)
return false;
}
enditer = out2->endDescend();
for(iter=out2->beginDescend();iter!=enditer;++iter) {
PcodeOp *op = *iter;
if (op->code() == CPUI_RETURN)
return true;
}
// Prefer addrtied over register over unique
if (!out1->isAddrTied()) {
if (out2->isAddrTied())
return true;
else {
if (out1->getSpace()->getType()==IPTR_INTERNAL) {
if (out2->getSpace()->getType()!=IPTR_INTERNAL)
return true;
}
}
}
return false;
}
/// Find any matching CPUI_MULTIEQUAL that occurs before \b target that has \b in as an input.
/// Then test to see if the \b target and the recovered op are functionally equivalent.
/// \param bl is the parent block
/// \param target is the given target CPUI_MULTIEQUAL
/// \param in is the specific input Varnode
PcodeOp *ActionMultiCse::findMatch(BlockBasic *bl,PcodeOp *target,Varnode *in)
{
list<PcodeOp *>::iterator iter = bl->beginOp();
for(;;) {
PcodeOp *op = *iter;
++iter;
if (op == target) // Caught up with target, nothing else before it
break;
int4 i,numinput;
numinput = op->numInput();
for(i=0;i<numinput;++i) {
Varnode *vn = op->getIn(i);
if (vn->isWritten() && (vn->getDef()->code() == CPUI_COPY))
vn = vn->getDef()->getIn(0); // Allow for differences in copy propagation
if (vn == in) break;
}
if (i < numinput) {
int4 j;
Varnode *buf1[2];
Varnode *buf2[2];
for(j=0;j<numinput;++j) {
Varnode *in1 = op->getIn(j);
if (in1->isWritten() && (in1->getDef()->code() == CPUI_COPY))
in1 = in1->getDef()->getIn(0); // Allow for differences in copy propagation
Varnode *in2 = target->getIn(j);
if (in2->isWritten() && (in2->getDef()->code() == CPUI_COPY))
in2 = in2->getDef()->getIn(0);
if (in1 == in2) continue;
if (0!=functionalEqualityLevel(in1,in2,buf1,buf2))
break;
}
if (j==numinput) // We have found a redundancy
return op;
}
}
return (PcodeOp *)0;
}
/// Search for pairs of CPUI_MULTIEQUAL ops in \b bl that share an input.
/// If the pairs found are functionally equivalent, delete one of the two.
/// \param data is the function owning the block
/// \param bl is the specific basic block
/// return \b true if a CPUI_MULTIEQUAL was (successfully) deleted
bool ActionMultiCse::processBlock(Funcdata &data,BlockBasic *bl)
{
vector<Varnode *> vnlist;
PcodeOp *targetop = (PcodeOp *)0;
PcodeOp *pairop;
list<PcodeOp *>::iterator iter = bl->beginOp();
list<PcodeOp *>::iterator enditer = bl->endOp();
while(iter != enditer) {
PcodeOp *op = *iter;
++iter;
OpCode opc = op->code();
if (opc == CPUI_COPY) continue;
if (opc != CPUI_MULTIEQUAL) break;
int4 vnpos = vnlist.size();
int4 i;
int4 numinput = op->numInput();
for(i=0;i<numinput;++i) {
Varnode *vn = op->getIn(i);
if (vn->isWritten() && (vn->getDef()->code() == CPUI_COPY)) // Some copies may not propagate into MULTIEQUAL
vn = vn->getDef()->getIn(0); // Allow for differences in copy propagation
vnlist.push_back(vn);
if (vn->isMark()) { // If we've seen this varnode before
pairop = findMatch(bl,op,vn);
if (pairop != (PcodeOp *)0)
break;
}
}
if (i<numinput) {
targetop = op;
break;
}
for(i=vnpos;i<vnlist.size();++i)
vnlist[i]->setMark(); // Mark that we have seen this varnode
}
// Clear out any of the marks we put down
for(int4 i=0;i<vnlist.size();++i)
vnlist[i]->clearMark();
if (targetop != (PcodeOp *)0) {
Varnode *out1 = pairop->getOut();
Varnode *out2 = targetop->getOut();
if (preferredOutput(out1,out2)) {
data.totalReplace(out1,out2); // Replace pairop and out1 in favor of targetop and out2
data.opDestroy(pairop);
}
else {
data.totalReplace(out2,out1);
data.opDestroy(targetop);
}
count += 1; // Indicate that a change has taken place
return true;
}
return false;
}
int4 ActionMultiCse::apply(Funcdata &data)
{
const BlockGraph &bblocks( data.getBasicBlocks() );
int4 sz = bblocks.getSize();
for(int4 i=0;i<sz;++i) {
BlockBasic *bl = (BlockBasic *)bblocks.getBlock(i);
while(processBlock(data,bl)) {
}
}
return 0;
}
int4 ActionShadowVar::apply(Funcdata &data)
{
const BlockGraph &bblocks(data.getBasicBlocks());
BlockBasic *bl;
PcodeOp *op;
Varnode *vn;
vector<Varnode *> vnlist;
list<PcodeOp *> oplist;
uintb startoffset;
for(int4 i=0;i<bblocks.getSize();++i) {
vnlist.clear();
bl = (BlockBasic *)bblocks.getBlock(i);
// Iterator over all MULTIEQUALs in the block
// We have to check all ops in the first address
// We cannot stop at first non-MULTIEQUAL because
// other ops creep in because of multi_collapse
startoffset = bl->getStart().getOffset();
list<PcodeOp *>::iterator iter = bl->beginOp();
while(iter != bl->endOp()) {
op = *iter++;
if (op->getAddr().getOffset() != startoffset) break;
if (op->code() != CPUI_MULTIEQUAL) continue;
vn = op->getIn(0);
if (vn->isMark())
oplist.push_back(op);
else {
vn->setMark();
vnlist.push_back(vn);
}
}
for(int4 j=0;j<vnlist.size();++j)
vnlist[j]->clearMark();
}
list<PcodeOp *>::iterator oiter;
for(oiter=oplist.begin();oiter!=oplist.end();++oiter) {
op = *oiter;
PcodeOp *op2;
for(op2=op->previousOp();op2!=(PcodeOp *)0;op2=op2->previousOp()) {
if (op2->code() != CPUI_MULTIEQUAL) continue;
int4 i;
for(i=0;i<op->numInput();++i) // Check for match in each branch
if (op->getIn(i) != op2->getIn(i)) break;
if (i != op->numInput()) continue; // All branches did not match
vector<Varnode *> plist;
plist.push_back(op2->getOut());
data.opSetOpcode(op,CPUI_COPY);
data.opSetAllInput(op,plist);
count += 1;
}
}
return 0;
}
/// \brief Search for address space annotations in the path of a pointer constant.
///
/// From a constant, search forward in its data-flow either for a LOAD or STORE operation where we can
/// see the address space being accessed, or search for a pointer data-type with an address space attribute.
/// We make a limited traversal through the op reading the constant, through INT_ADD, INDIRECT, COPY,
/// and MULTIEQUAL until we hit a LOAD or STORE.
/// \param vn is the constant we are searching from
/// \param op is the PcodeOp reading the constant
/// \return the discovered AddrSpace or null
AddrSpace *ActionConstantPtr::searchForSpaceAttribute(Varnode *vn,PcodeOp *op)
{
for(int4 i=0;i<3;++i) {
Datatype *dt = vn->getType();
if (dt->getMetatype() == TYPE_PTR) {
AddrSpace *spc = ((TypePointer*)dt)->getSpace();
if (spc != (AddrSpace*)0 && spc->getAddrSize() == vn->getSize()) // If provided a pointer with space attribute
return spc; // use that
}
switch(op->code()) {
case CPUI_INT_ADD:
case CPUI_COPY:
case CPUI_INDIRECT:
case CPUI_MULTIEQUAL:
vn = op->getOut();
op = vn->loneDescend();
break;
case CPUI_LOAD:
return op->getIn(0)->getSpaceFromConst();
case CPUI_STORE:
if (op->getIn(1) == vn)
return op->getIn(0)->getSpaceFromConst();
return (AddrSpace *)0;
default:
return (AddrSpace *)0;
}
if (op == (PcodeOp *)0) break;
}
for(list<PcodeOp *>::const_iterator iter=vn->beginDescend();iter!=vn->endDescend();++iter) {
op = *iter;
OpCode opc = op->code();
if (opc == CPUI_LOAD)
return op->getIn(0)->getSpaceFromConst();
else if (opc == CPUI_STORE && op->getIn(1) == vn)
return op->getIn(0)->getSpaceFromConst();
}
return (AddrSpace *)0;
}
/// \brief Select the AddrSpace in which we infer with the given constant is a pointer
///
/// The constant must match the AddrSpace address size. If there is more than one possible match,
/// search for more information in the syntax tree.
/// \param vn is the given constant Varnode
/// \param op is the PcodeOp which uses the constant
/// \param spaceList is the list of address spaces to select from
/// \return the selected address space or null
AddrSpace *ActionConstantPtr::selectInferSpace(Varnode *vn,PcodeOp *op,const vector<AddrSpace *> &spaceList)
{
AddrSpace *resSpace = (AddrSpace *)0;