forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heritage.cc
2435 lines (2254 loc) · 86.4 KB
/
heritage.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 "heritage.hh"
#include "funcdata.hh"
#include "prefersplit.hh"
/// Update disjoint cover making sure (addr,size) is contained in a single element
/// and return iterator to this element. Pass back \b intersect value:
/// - 0 if the only intersection is with range from the same pass
/// - 1 if there is a partial intersection with something old
/// - 2 if the range is contained in an old range
/// \param addr is the starting address of the range to add
/// \param size is the number of bytes in the range
/// \param pass is the pass number when the range was heritaged
/// \param intersect is a reference for passing back the intersect code
/// \return the iterator to the map element containing the added range
LocationMap::iterator LocationMap::add(Address addr,int4 size,int4 pass,int4 &intersect)
{
iterator iter = themap.lower_bound(addr);
if (iter != themap.begin())
--iter;
if ((iter!=themap.end())&&(-1 == addr.overlap(0,(*iter).first,(*iter).second.size)))
++iter;
int4 where=0;
intersect = 0;
if ((iter!=themap.end())&&(-1!=(where=addr.overlap(0,(*iter).first,(*iter).second.size)))) {
if (where+size<=(*iter).second.size) {
intersect = ((*iter).second.pass < pass) ? 2 : 0; // Completely contained in previous element
return iter;
}
addr = (*iter).first;
size = where+size;
if ((*iter).second.pass < pass)
intersect = 1; // Partial overlap with old element
themap.erase(iter++);
}
while((iter!=themap.end())&&(-1!=(where=(*iter).first.overlap(0,addr,size)))) {
if (where+(*iter).second.size>size)
size = where+(*iter).second.size;
if ((*iter).second.pass < pass)
intersect = 1;
themap.erase(iter++);
}
iter = themap.insert(pair<Address,SizePass>( addr, SizePass() )).first;
(*iter).second.size = size;
(*iter).second.pass = pass;
return iter;
}
/// If the given address was heritaged, return (the iterator to) the SizeMap entry
/// describing the associated range and when it was heritaged.
/// \param addr is the given address
/// \return the iterator to the SizeMap entry or the end iterator is the address is unheritaged
LocationMap::iterator LocationMap::find(Address addr)
{
iterator iter = themap.upper_bound(addr); // First range after address
if (iter == themap.begin()) return themap.end();
--iter; // First range before or equal to address
if (-1!=addr.overlap(0,(*iter).first,(*iter).second.size))
return iter;
return themap.end();
}
/// Return the pass number when the given address was heritaged, or -1 if it was not heritaged
/// \param addr is the given address
/// \return the pass number of -1
int4 LocationMap::findPass(Address addr) const
{
map<Address,SizePass>::const_iterator iter = themap.upper_bound(addr); // First range after address
if (iter == themap.begin()) return -1;
--iter; // First range before or equal to address
if (-1!=addr.overlap(0,(*iter).first,(*iter).second.size))
return (*iter).second.pass;
return -1;
}
/// Any basic blocks currently in \b this queue are removed. Space is
/// reserved for a new set of prioritized stacks.
/// \param maxdepth is the number of stacks to allocate
void PriorityQueue::reset(int4 maxdepth)
{
if ((curdepth==-1)&&(maxdepth==queue.size()-1)) return; // Already reset
queue.clear();
queue.resize(maxdepth+1);
curdepth = -1;
}
/// The block is pushed onto the stack of the given priority.
/// \param bl is the block being added to the queue
/// \param depth is the priority to associate with the block
void PriorityQueue::insert(FlowBlock *bl,int4 depth)
{
queue[depth].push_back(bl);
if (depth > curdepth)
curdepth = depth;
}
/// The block at the top of the highest priority non-empty stack is popped
/// and returned. This will always return a block. It shouldn't be called if the
/// queue is empty.
/// \return the highest priority block
FlowBlock *PriorityQueue::extract(void)
{
FlowBlock *res = queue[curdepth].back();
queue[curdepth].pop_back();
while(queue[curdepth].empty()) {
curdepth -= 1;
if (curdepth <0) break;
}
return res;
}
/// Instantiate the heritage manager for a particular function.
/// \param data is the function
Heritage::Heritage(Funcdata *data)
{
fd = data;
pass = 0;
maxdepth = -1;
}
void Heritage::clearInfoList(void)
{
vector<HeritageInfo>::iterator iter;
for(iter=infolist.begin();iter!=infolist.end();++iter)
(*iter).reset();
}
/// \brief Collect free reads, writes, and inputs in the given address range
///
/// \param addr is the starting address of the range
/// \param size is the number of bytes in the range
/// \param read will hold any read Varnodes in the range
/// \param write will hold any written Varnodes
/// \param input will hold any input Varnodes
/// \return the maximum size of a write
int4 Heritage::collect(Address addr,int4 size,
vector<Varnode *> &read,vector<Varnode *> &write,
vector<Varnode *> &input) const
{
Varnode *vn;
VarnodeLocSet::const_iterator viter = fd->beginLoc(addr);
VarnodeLocSet::const_iterator enditer;
uintb start = addr.getOffset();
addr = addr + size;
if (addr.getOffset() < start) { // Wraparound
Address tmp(addr.getSpace(),addr.getSpace()->getHighest());
enditer = fd->endLoc(tmp);
}
else
enditer = fd->beginLoc(addr);
int4 maxsize = 0;
while( viter != enditer ) {
vn = *viter;
if (!vn->isWriteMask()) {
if (vn->isWritten()) {
if (vn->getSize() > maxsize) // Look for maximum write size
maxsize = vn->getSize();
write.push_back(vn);
}
else if ((!vn->isHeritageKnown())&&(!vn->hasNoDescend()))
read.push_back(vn);
else if (vn->isInput())
input.push_back(vn);
}
++viter;
}
return maxsize;
}
/// \brief Determine if the address range is affected by the given call p-code op
///
/// We assume the op is CALL, CALLIND, CALLOTHER, or NEW and that its
/// output overlaps the given address range. We look up any effect
/// the op might have on the address range.
/// \param addr is the starting address of the range
/// \param size is the number of bytes in the range
/// \param op is the given \e call p-code op
/// \return \b true, unless the range is unaffected by the op
bool Heritage::callOpIndirectEffect(const Address &addr,int4 size,PcodeOp *op) const
{
if ((op->code() == CPUI_CALL)||(op->code() == CPUI_CALLIND)) {
// We should be able to get the callspec
FuncCallSpecs *fc = fd->getCallSpecs(op);
if (fc == (FuncCallSpecs *)0) return true; // Assume indirect effect
return (fc->hasEffectTranslate(addr,size) != EffectRecord::unaffected);
}
// If we reach here, this is a CALLOTHER, NEW
// We assume these do not have effects on -fd- variables except for op->getOut().
return false;
}
/// \brief Normalize the size of a read Varnode, prior to heritage
///
/// Given a Varnode being read that does not match the (larger) size
/// of the address range currently being linked, create a Varnode of
/// the correct size and define the original Varnode as a SUBPIECE.
/// \param vn is the given too small Varnode
/// \param addr is the start of the (larger) range
/// \param size is the number of bytes in the range
/// \return the new larger Varnode
Varnode *Heritage::normalizeReadSize(Varnode *vn,const Address &addr,int4 size)
{
int4 overlap;
Varnode *vn1,*vn2;
PcodeOp *op,*newop;
list<PcodeOp *>::const_iterator oiter = vn->beginDescend();
op = *oiter++;
if (oiter != vn->endDescend())
throw LowlevelError("Free varnode with multiple reads");
newop = fd->newOp(2,op->getAddr());
fd->opSetOpcode(newop,CPUI_SUBPIECE);
vn1 = fd->newVarnode(size,addr);
overlap = vn->overlap(addr,size);
vn2 = fd->newConstant(addr.getAddrSize(),(uintb)overlap);
fd->opSetInput(newop,vn1,0);
fd->opSetInput(newop,vn2,1);
fd->opSetOutput(newop,vn); // Old vn is no longer a free read
newop->getOut()->setWriteMask();
fd->opInsertBefore(newop,op);
return vn1; // But we have new free read of uniform size
}
/// \brief Normalize the size of a written Varnode, prior to heritage
///
/// Given a Varnode that is written that does not match the (larger) size
/// of the address range currently being linked, create the missing
/// pieces in the range and concatenate everything into a new Varnode
/// of the correct size.
///
/// One or more Varnode pieces are created depending
/// on how the original Varnode overlaps the given range. An expression
/// is created using PIECE ops resulting in a final Varnode.
/// \param vn is the given too small Varnode
/// \param addr is the start of the (larger) range
/// \param size is the number of bytes in the range
/// \return the newly created final Varnode
Varnode *Heritage::normalizeWriteSize(Varnode *vn,const Address &addr,int4 size)
{
int4 overlap;
int4 mostsigsize;
PcodeOp *op,*newop;
Varnode *mostvn,*leastvn,*big,*bigout,*midvn;
mostvn = (Varnode *)0;
op = vn->getDef();
overlap = vn->overlap(addr,size);
mostsigsize = size-(overlap+vn->getSize());
if (mostsigsize != 0) {
Address pieceaddr;
if (addr.isBigEndian())
pieceaddr = addr;
else
pieceaddr = addr + (overlap+vn->getSize());
if (op->isCall() && callOpIndirectEffect(pieceaddr,mostsigsize,op)) { // Unless CALL definitely has no effect on piece
newop = fd->newIndirectCreation(op,pieceaddr,mostsigsize,false); // Don't create a new big read if write is from a CALL
mostvn = newop->getOut();
}
else {
newop = fd->newOp(2,op->getAddr());
mostvn = fd->newVarnodeOut(mostsigsize,pieceaddr,newop);
big = fd->newVarnode(size,addr); // The new read
big->setActiveHeritage();
fd->opSetOpcode(newop,CPUI_SUBPIECE);
fd->opSetInput(newop,big,0);
fd->opSetInput(newop,fd->newConstant(addr.getAddrSize(),(uintb)overlap+vn->getSize()),1);
fd->opInsertBefore(newop,op);
}
}
if (overlap != 0) {
Address pieceaddr;
if (addr.isBigEndian())
pieceaddr = addr + (size-overlap);
else
pieceaddr = addr;
if (op->isCall() && callOpIndirectEffect(pieceaddr,overlap,op)) { // Unless CALL definitely has no effect on piece
newop = fd->newIndirectCreation(op,pieceaddr,overlap,false); // Don't create a new big read if write is from a CALL
leastvn = newop->getOut();
}
else {
newop = fd->newOp(2,op->getAddr());
leastvn = fd->newVarnodeOut(overlap,pieceaddr,newop);
big = fd->newVarnode(size,addr); // The new read
big->setActiveHeritage();
fd->opSetOpcode(newop,CPUI_SUBPIECE);
fd->opSetInput(newop,big,0);
fd->opSetInput(newop,fd->newConstant(addr.getAddrSize(),0),1);
fd->opInsertBefore(newop,op);
}
}
if (overlap !=0 ) {
newop = fd->newOp(2,op->getAddr());
if (addr.isBigEndian())
midvn = fd->newVarnodeOut(overlap+vn->getSize(),vn->getAddr(),newop);
else
midvn = fd->newVarnodeOut(overlap+vn->getSize(),addr,newop);
fd->opSetOpcode(newop,CPUI_PIECE);
fd->opSetInput(newop,vn,0); // Most significant part
fd->opSetInput(newop,leastvn,1); // Least sig
fd->opInsertAfter(newop,op);
}
else
midvn = vn;
if (mostsigsize != 0) {
newop = fd->newOp(2,op->getAddr());
bigout = fd->newVarnodeOut(size,addr,newop);
fd->opSetOpcode(newop,CPUI_PIECE);
fd->opSetInput(newop,mostvn,0);
fd->opSetInput(newop,midvn,1);
fd->opInsertAfter(newop,midvn->getDef());
}
else
bigout = midvn;
vn->setWriteMask();
return bigout; // Replace small write with big write
}
/// \brief Concatenate a list of Varnodes together at the given location
///
/// There must be at least 2 Varnodes in list, they must be in order
/// from most to least significant. The Varnodes in the list become
/// inputs to a single expression of PIECE ops resulting in a
/// final specified Varnode
/// \param vnlist is the list of Varnodes to concatenate
/// \param insertop is the point where the expression should be inserted (before)
/// \param finalvn is the final specified output Varnode of the expression
/// \return the final unified Varnode
Varnode *Heritage::concatPieces(const vector<Varnode *> &vnlist,PcodeOp *insertop,Varnode *finalvn)
{
Varnode *preexist = vnlist[0];
bool isbigendian = preexist->getAddr().isBigEndian();
Address opaddress;
BlockBasic *bl;
list<PcodeOp *>::iterator insertiter;
if (insertop == (PcodeOp *)0) { // Insert at the beginning
bl = (BlockBasic *)fd->getBasicBlocks().getStartBlock();
insertiter = bl->beginOp();
opaddress = fd->getAddress();
}
else {
bl = insertop->getParent();
insertiter = insertop->getBasicIter();
opaddress = insertop->getAddr();
}
for(uint4 i=1;i<vnlist.size();++i) {
Varnode *vn = vnlist[i];
PcodeOp *newop = fd->newOp(2,opaddress);
fd->opSetOpcode(newop,CPUI_PIECE);
Varnode *newvn;
if (i==vnlist.size()-1) {
newvn = finalvn;
fd->opSetOutput(newop,newvn);
}
else
newvn = fd->newUniqueOut(preexist->getSize()+vn->getSize(),newop);
if (isbigendian) {
fd->opSetInput(newop,preexist,0); // Most sig part
fd->opSetInput(newop,vn,1); // Least sig part
}
else {
fd->opSetInput(newop,vn,0);
fd->opSetInput(newop,preexist,1);
}
fd->opInsert(newop,bl,insertiter);
preexist = newvn;
}
return preexist;
}
/// \brief Build a set of Varnode piece expression at the given location
///
/// Given a list of small Varnodes and the address range they are a piece of,
/// construct a SUBPIECE op that defines each piece. The truncation parameters
/// are calculated based on the overlap of the piece with the whole range,
/// and a single input Varnode is used for all SUBPIECE ops.
/// \param vnlist is the list of piece Varnodes
/// \param insertop is the point where the op expressions are inserted (before)
/// \param addr is the first address of the whole range
/// \param size is the number of bytes in the whole range
/// \param startvn is designated input Varnode
void Heritage::splitPieces(const vector<Varnode *> &vnlist,PcodeOp *insertop,
const Address &addr,int4 size,Varnode *startvn)
{
Address opaddress;
uintb baseoff;
bool isbigendian;
BlockBasic *bl;
list<PcodeOp *>::iterator insertiter;
isbigendian = addr.isBigEndian();
if (isbigendian)
baseoff = addr.getOffset() + size;
else
baseoff = addr.getOffset();
if (insertop == (PcodeOp *)0) {
bl = (BlockBasic *)fd->getBasicBlocks().getStartBlock();
insertiter = bl->beginOp();
opaddress = fd->getAddress();
}
else {
bl = insertop->getParent();
insertiter = insertop->getBasicIter();
++insertiter; // Insert AFTER the write
opaddress = insertop->getAddr();
}
for(uint4 i=0;i<vnlist.size();++i) {
Varnode *vn = vnlist[i];
PcodeOp *newop = fd->newOp(2,opaddress);
fd->opSetOpcode(newop,CPUI_SUBPIECE);
uintb diff;
if (isbigendian)
diff = baseoff - (vn->getOffset() + vn->getSize());
else
diff = vn->getOffset() - baseoff;
fd->opSetInput(newop,startvn,0);
fd->opSetInput(newop,fd->newConstant(4,diff),1);
fd->opSetOutput(newop,vn);
fd->opInsert(newop,bl,insertiter);
}
}
/// \brief Find the last PcodeOps that write to specific addresses that flow to specific sites
///
/// Given a set of sites for which data-flow needs to be preserved at a specific address, find
/// the \e last ops that write to the address such that data flows to the site
/// only through \e artificial COPYs and MULTIEQUALs. A COPY/MULTIEQUAL is artificial if all
/// of its input and output Varnodes have the same storage address. The specific sites are
/// presented as artificial COPY ops. The final set of ops that are not artificial will all
/// have an output Varnode that matches the specific address of a COPY sink and will need to
/// be marked address forcing. The original set of COPY sinks will be extended to all artificial
/// COPY/MULTIEQUALs encountered. Every PcodeOp encountered will have its mark set.
/// \param copySinks is the list of sinks that we are trying to find flow to
/// \param forces is the final list of address forcing PcodeOps
void Heritage::findAddressForces(vector<PcodeOp *> ©Sinks,vector<PcodeOp *> &forces)
{
// Mark the sinks
for(int4 i=0;i<copySinks.size();++i) {
PcodeOp *op = copySinks[i];
op->setMark();
}
// Mark everything back-reachable from a sink, trimming at non-artificial ops
int4 pos = 0;
while(pos < copySinks.size()) {
PcodeOp *op = copySinks[pos];
Address addr = op->getOut()->getAddr(); // Address being flowed to
pos += 1;
int4 maxIn = op->numInput();
for(int4 i=0;i<maxIn;++i) {
Varnode *vn = op->getIn(i);
if (!vn->isWritten()) continue;
if (vn->isAddrForce()) continue; // Already marked address forced
PcodeOp *newOp = vn->getDef();
if (newOp->isMark()) continue; // Already visited this op
newOp->setMark();
OpCode opc = newOp->code();
bool isArtificial = false;
if (opc == CPUI_COPY || opc == CPUI_MULTIEQUAL) {
isArtificial = true;
int4 maxInNew = newOp->numInput();
for(int4 j=0;j<maxInNew;++j) {
Varnode *inVn = newOp->getIn(j);
if (addr != inVn->getAddr()) {
isArtificial = false;
break;
}
}
}
else if (opc == CPUI_INDIRECT && newOp->isIndirectStore()) {
// An INDIRECT can be considered artificial if it is caused by a STORE
Varnode *inVn = newOp->getIn(0);
if (addr == inVn->getAddr())
isArtificial = true;
}
if (isArtificial)
copySinks.push_back(newOp);
else
forces.push_back(newOp);
}
}
}
/// \brief Eliminate a COPY sink preserving its data-flow
///
/// Given a COPY from a storage location to itself, propagate the input Varnode
/// version of the storage location to all the ops reading the output Varnode, so
/// the output no longer has any descendants. Then eliminate the COPY.
/// \param op is the given COPY sink
void Heritage::propagateCopyAway(PcodeOp *op)
{
Varnode *inVn = op->getIn(0);
while(inVn->isWritten()) { // Follow any COPY chain to earliest input
PcodeOp *nextOp = inVn->getDef();
if (nextOp->code() != CPUI_COPY) break;
Varnode *nextIn = nextOp->getIn(0);
if (nextIn->getAddr() != inVn->getAddr()) break;
inVn = nextIn;
}
fd->totalReplace(op->getOut(),inVn);
fd->opDestroy(op);
}
/// \brief Mark the boundary of artificial ops introduced by load guards
///
/// Having just completed renaming, run through all new COPY sinks from load guards
/// and mark boundary Varnodes (Varnodes whose data-flow along all paths traverses only
/// COPY/INDIRECT/MULTIEQUAL ops and hits a load guard). This lets dead code removal
/// run forward from the boundary while still preserving the address force on the load guard.
void Heritage::handleNewLoadCopies(void)
{
if (loadCopyOps.empty()) return;
vector<PcodeOp *> forces;
int4 copySinkSize = loadCopyOps.size();
findAddressForces(loadCopyOps, forces);
if (!forces.empty()) {
RangeList loadRanges;
for(list<LoadGuard>::const_iterator iter=loadGuard.begin();iter!=loadGuard.end();++iter) {
const LoadGuard &guard( *iter );
loadRanges.insertRange(guard.spc, guard.minimumOffset, guard.maximumOffset);
}
// Mark everything on the boundary as address forced to prevent dead-code removal
for(int4 i=0;i<forces.size();++i) {
PcodeOp *op = forces[i];
Varnode *vn = op->getOut();
if (loadRanges.inRange(vn->getAddr(), 1)) // If we are within one of the guarded ranges
vn->setAddrForce(); // then consider the output address forced
op->clearMark();
}
}
// Eliminate or propagate away original COPY sinks
for(int4 i=0;i<copySinkSize;++i) {
PcodeOp *op = loadCopyOps[i];
propagateCopyAway(op); // Make sure load guard COPYs no longer exist
}
// Clear marks on remaining artificial COPYs
for(int4 i=copySinkSize;i<loadCopyOps.size();++i) {
PcodeOp *op = loadCopyOps[i];
op->clearMark();
}
loadCopyOps.clear(); // We have handled all the load guard COPY ops
}
/// Make some determination of the range of possible values for a LOAD based
/// an partial value set analysis. This can sometimes get
/// - minimumOffset - otherwise the original constant pulled with the LOAD is used
/// - step - the partial analysis shows step and direction
/// - maximumOffset - in rare cases
///
/// isAnalyzed is set to \b true, if full range analysis is not needed
/// \param valueSet is the calculated value set as seen by the LOAD operation
void LoadGuard::establishRange(const ValueSetRead &valueSet)
{
const CircleRange &range( valueSet.getRange() );
uintb rangeSize = range.getSize();
uintb size;
if (range.isEmpty()) {
minimumOffset = pointerBase;
size = 0x1000;
}
else if (range.isFull() || rangeSize > 0xffffff) {
minimumOffset = pointerBase;
size = 0x1000;
analysisState = 1; // Don't bother doing more analysis
}
else {
step = (rangeSize == 3) ? range.getStep() : 0; // Check for consistent step
size = 0x1000;
if (valueSet.isLeftStable()) {
minimumOffset = range.getMin();
}
else if (valueSet.isRightStable()) {
if (pointerBase < range.getEnd()) {
minimumOffset = pointerBase;
size = (range.getEnd() - pointerBase);
}
else {
minimumOffset = range.getMin();
size = rangeSize * range.getStep();
}
}
else
minimumOffset = pointerBase;
}
uintb max = spc->getHighest();
if (minimumOffset > max) {
minimumOffset = max;
maximumOffset = minimumOffset; // Something is seriously wrong
}
else {
uintb maxSize = (max - minimumOffset) + 1;
if (size > maxSize)
size = maxSize;
maximumOffset = minimumOffset + size -1;
}
}
void LoadGuard::finalizeRange(const ValueSetRead &valueSet)
{
analysisState = 1; // In all cases the settings determined here are final
const CircleRange &range( valueSet.getRange() );
uintb rangeSize = range.getSize();
if (rangeSize == 0x100 || rangeSize == 0x10000) {
// These sizes likely result from the storage size of the index
if (step == 0) // If we didn't see signs of iteration
rangeSize = 0; // don't use this range
}
if (rangeSize > 1 && rangeSize < 0xffffff) { // Did we converge to something reasonable
analysisState = 2; // Mark that we got a definitive result
if (rangeSize > 2)
step = range.getStep();
minimumOffset = range.getMin();
maximumOffset = (range.getEnd() - 1) & range.getMask(); // NOTE: Don't subtract a whole step
if (maximumOffset < minimumOffset) { // Values extend into what is usually stack parameters
maximumOffset = spc->getHighest();
analysisState = 1; // Remove the lock as we have likely overflowed
}
}
if (minimumOffset > spc->getHighest())
minimumOffset = spc->getHighest();
if (maximumOffset > spc->getHighest())
maximumOffset = spc->getHighest();
}
/// Check if the address falls within the range defined by \b this
/// \param addr is the given address
/// \return \b true if the address is contained
bool LoadGuard::isGuarded(const Address &addr) const
{
if (addr.getSpace() != spc) return false;
if (addr.getOffset() < minimumOffset) return false;
if (addr.getOffset() > maximumOffset) return false;
return true;
}
/// \brief Make final determination of what range new LoadGuards are protecting
///
/// Actual LOAD operations are guarded with an initial version of the LoadGuard record.
/// Now that heritage has completed, a full analysis of each LOAD is conducted, using
/// value set analysis, to reach a conclusion about what range of stack values the
/// LOAD might actually alias. All new LoadGuard records are updated with the analysis,
/// which then informs handling of LOAD COPYs and possible later heritage passes.
void Heritage::analyzeNewLoadGuards(void)
{
bool nothingToDo = true;
if (!loadGuard.empty()) {
if (loadGuard.back().analysisState == 0) // Check if unanalyzed
nothingToDo = false;
}
if (!storeGuard.empty()) {
if (storeGuard.back().analysisState == 0)
nothingToDo = false;
}
if (nothingToDo) return;
vector<Varnode *> sinks;
vector<PcodeOp *> reads;
list<LoadGuard>::iterator loadIter = loadGuard.end();
while(loadIter != loadGuard.begin()) {
--loadIter;
LoadGuard &guard( *loadIter );
if (guard.analysisState != 0) break;
reads.push_back(guard.op);
sinks.push_back(guard.op->getIn(1)); // The CPUI_LOAD pointer
}
list<LoadGuard>::iterator storeIter = storeGuard.end();
while(storeIter != storeGuard.begin()) {
--storeIter;
LoadGuard &guard( *storeIter );
if (guard.analysisState != 0) break;
reads.push_back(guard.op);
sinks.push_back(guard.op->getIn(1)); // The CPUI_STORE pointer
}
AddrSpace *stackSpc = fd->getArch()->getStackSpace();
Varnode *stackReg = (Varnode *)0;
if (stackSpc != (AddrSpace *)0 && stackSpc->numSpacebase() > 0)
stackReg = fd->findSpacebaseInput(stackSpc);
ValueSetSolver vsSolver;
vsSolver.establishValueSets(sinks, reads, stackReg, false);
WidenerNone widener;
vsSolver.solve(10000,widener);
list<LoadGuard>::iterator iter;
bool runFullAnalysis = false;
for(iter=loadIter;iter!=loadGuard.end(); ++iter) {
LoadGuard &guard( *iter );
guard.establishRange(vsSolver.getValueSetRead(guard.op->getSeqNum()));
if (guard.analysisState == 0)
runFullAnalysis = true;
}
for(iter=storeIter;iter!=storeGuard.end(); ++iter) {
LoadGuard &guard( *iter );
guard.establishRange(vsSolver.getValueSetRead(guard.op->getSeqNum()));
if (guard.analysisState == 0)
runFullAnalysis = true;
}
if (runFullAnalysis) {
WidenerFull fullWidener;
vsSolver.solve(10000, fullWidener);
for (iter = loadIter; iter != loadGuard.end(); ++iter) {
LoadGuard &guard(*iter);
guard.finalizeRange(vsSolver.getValueSetRead(guard.op->getSeqNum()));
}
for (iter = storeIter; iter != storeGuard.end(); ++iter) {
LoadGuard &guard(*iter);
guard.finalizeRange(vsSolver.getValueSetRead(guard.op->getSeqNum()));
}
}
}
/// \brief Generate a guard record given an indexed LOAD into a stack space
///
/// Record the LOAD op and the (likely) range of addresses in the stack space that
/// might be loaded from.
/// \param node is the path element containing the constructed Address
/// \param op is the LOAD PcodeOp
/// \param spc is the stack space
void Heritage::generateLoadGuard(StackNode &node,PcodeOp *op,AddrSpace *spc)
{
if (!op->usesSpacebasePtr()) {
loadGuard.push_back(LoadGuard());
loadGuard.back().set(op,spc,node.offset);
fd->opMarkSpacebasePtr(op);
}
}
/// \brief Generate a guard record given an indexed STORE to a stack space
///
/// Record the STORE op and the (likely) range of addresses in the stack space that
/// might be stored to.
/// \param node is the path element containing the constructed Address
/// \param op is the STORE PcodeOp
/// \param spc is the stack space
void Heritage::generateStoreGuard(StackNode &node,PcodeOp *op,AddrSpace *spc)
{
if (!op->usesSpacebasePtr()) {
storeGuard.push_back(LoadGuard());
storeGuard.back().set(op,spc,node.offset);
fd->opMarkSpacebasePtr(op);
}
}
/// \brief Identify any CPUI_STORE ops that use a free pointer from a given address space
///
/// When performing heritage for stack Varnodes, data-flow around a STORE with a
/// free pointer must be guarded (with an INDIRECT) to be safe. This routine collects
/// and marks the STORE ops that trigger this guard.
/// \param spc is the given address space
/// \param freeStores will hold the list of STOREs if any
/// \return \b true if there are any new STOREs needing a guard
bool Heritage::protectFreeStores(AddrSpace *spc,vector<PcodeOp *> &freeStores)
{
list<PcodeOp *>::const_iterator iter = fd->beginOp(CPUI_STORE);
list<PcodeOp *>::const_iterator enditer = fd->endOp(CPUI_STORE);
bool hasNew = false;
while(iter != enditer) {
PcodeOp *op = *iter;
++iter;
if (op->isDead()) continue;
Varnode *vn = op->getIn(1);
if (vn->isWritten()) {
PcodeOp *copyOp = vn->getDef();
if (copyOp->code() == CPUI_COPY)
vn = copyOp->getIn(0);
}
if (vn->isFree() && vn->getSpace() == spc) {
fd->opMarkSpacebasePtr(op); // Mark op as spacebase STORE, even though we're not sure
freeStores.push_back(op);
hasNew = true;
}
}
return hasNew;
}
/// \brief Trace input stack-pointer to any indexed loads
///
/// Look for expressions of the form val = *(SP(i) + vn + \#c), where the base stack
/// pointer has an (optional) constant added to it and a non-constant index, then a
/// value is loaded from the resulting address. The LOAD operations are added to the list
/// of ops that potentially need to be guarded during a heritage pass. The routine can
/// checks for STOREs where the data-flow path hasn't been completed yet and returns
/// \b true if they exist, passing back a list of those that might use a pointer to the stack.
/// \param spc is the particular address space with a stackpointer (into it)
/// \param freeStores will hold the list of any STOREs that need follow-up analysis
/// \param checkFreeStores is \b true if the routine should check for free STOREs
/// \return \b true if there are incomplete STOREs
bool Heritage::discoverIndexedStackPointers(AddrSpace *spc,vector<PcodeOp *> &freeStores,bool checkFreeStores)
{
// We need to be careful of exponential ladders, so we mark Varnodes independently of
// the depth first path we are traversing.
vector<Varnode *> markedVn;
vector<StackNode> path;
bool unknownStackStorage = false;
for(int4 i=0;i<spc->numSpacebase();++i) {
const VarnodeData &stackPointer(spc->getSpacebase(i));
Varnode *spInput = fd->findVarnodeInput(stackPointer.size, stackPointer.getAddr());
if (spInput == (Varnode *)0) continue;
path.push_back(StackNode(spInput,0,0));
while(!path.empty()) {
StackNode &curNode(path.back());
if (curNode.iter == curNode.vn->endDescend()) {
path.pop_back();
continue;
}
PcodeOp *op = *curNode.iter;
++curNode.iter;
Varnode *outVn = op->getOut();
if (outVn != (Varnode *)0 && outVn->isMark()) continue; // Don't revisit Varnodes
switch(op->code()) {
case CPUI_INT_ADD:
{
Varnode *otherVn = op->getIn(1-op->getSlot(curNode.vn));
if (otherVn->isConstant()) {
uintb newOffset = spc->wrapOffset(curNode.offset + otherVn->getOffset());
StackNode nextNode(outVn,newOffset,curNode.traversals);
if (nextNode.iter != nextNode.vn->endDescend()) {
outVn->setMark();
path.push_back(nextNode);
markedVn.push_back(outVn);
}
else if (outVn->getSpace()->getType() == IPTR_SPACEBASE)
unknownStackStorage = true;
}
else {
StackNode nextNode(outVn,curNode.offset,curNode.traversals | StackNode::nonconstant_index);
if (nextNode.iter != nextNode.vn->endDescend()) {
outVn->setMark();
path.push_back(nextNode);
markedVn.push_back(outVn);
}
else if (outVn->getSpace()->getType() == IPTR_SPACEBASE)
unknownStackStorage = true;
}
break;
}
case CPUI_INDIRECT:
case CPUI_COPY:
{
StackNode nextNode(outVn,curNode.offset,curNode.traversals);
if (nextNode.iter != nextNode.vn->endDescend()) {
outVn->setMark();
path.push_back(nextNode);
markedVn.push_back(outVn);
}
else if (outVn->getSpace()->getType() == IPTR_SPACEBASE)
unknownStackStorage = true;
break;
}
case CPUI_MULTIEQUAL:
{
StackNode nextNode(outVn,curNode.offset,curNode.traversals | StackNode::multiequal);
if (nextNode.iter != nextNode.vn->endDescend()) {
outVn->setMark();
path.push_back(nextNode);
markedVn.push_back(outVn);
}
else if (outVn->getSpace()->getType() == IPTR_SPACEBASE)
unknownStackStorage = true;
break;
}
case CPUI_LOAD:
{
// Note that if ANY path has one of the traversals (non-constant ADD or MULTIEQUAL), then
// THIS path must have one of the traversals, because the only other acceptable path elements
// (INDIRECT/COPY/constant ADD) have only one path through.
if (curNode.traversals != 0) {
generateLoadGuard(curNode,op,spc);
}
break;
}
case CPUI_STORE:
{
if (curNode.traversals != 0) {
generateStoreGuard(curNode, op, spc);
}
break;
}
default:
break;
}
}
}
for(int4 i=0;i<markedVn.size();++i)
markedVn[i]->clearMark();
if (unknownStackStorage && checkFreeStores)
return protectFreeStores(spc, freeStores);
return false;
}
/// \brief Revisit STOREs with free pointers now that a heritage pass has completed
///
/// We regenerate STORE LoadGuard records then cross-reference with STOREs that were
/// originally free to see if they actually needed a LoadGaurd. If not, the STORE
/// is unmarked and INDIRECTs it has caused are removed.
/// \param spc is the address space being guarded
/// \param freeStores is the list of STOREs that were marked as free
void Heritage::reprocessFreeStores(AddrSpace *spc,vector<PcodeOp *> &freeStores)
{
for(int4 i=0;i<freeStores.size();++i)
fd->opClearSpacebasePtr(freeStores[i]);
discoverIndexedStackPointers(spc, freeStores, false);
for(int4 i=0;i<freeStores.size();++i) {
PcodeOp *op = freeStores[i];
// If the STORE now is marked as using a spacebase ptr, then it was appropriately
// marked to begin with, and we don't need to clean anything up
if (op->usesSpacebasePtr()) continue;
// If not the STORE may have triggered INDIRECTs that are unnecessary
PcodeOp *indOp = op->previousOp();
while(indOp != (PcodeOp *)0) {
if (indOp->code() != CPUI_INDIRECT) break;
Varnode *iopVn = indOp->getIn(1);
if (iopVn->getSpace()->getType()!=IPTR_IOP) break;
if (op != PcodeOp::getOpFromConst(iopVn->getAddr())) break;
PcodeOp *nextOp = indOp->previousOp();
if (indOp->getOut()->getSpace() == spc) {
fd->totalReplace(indOp->getOut(),indOp->getIn(0));
fd->opDestroy(indOp); // Get rid of the INDIRECT
}
indOp = nextOp;
}
}
}
/// \brief Normalize p-code ops so that phi-node placement and renaming works
///
/// The traditional phi-node placement and renaming algorithms don't expect
/// variable pairs where there is partial overlap. For the given address range,
/// we make all the free Varnode sizes look uniform by adding PIECE and SUBPIECE
/// ops. We also add INDIRECT ops, so that we can ignore indirect effects
/// of LOAD/STORE/CALL ops.
/// \param addr is the starting address of the given range
/// \param size is the number of bytes in the given range
/// \param read is the set of Varnode values reading from the range
/// \param write is the set of written Varnodes in the range
/// \param inputvars is the set of Varnodes in the range already marked as input
void Heritage::guard(const Address &addr,int4 size,vector<Varnode *> &read,vector<Varnode *> &write,
vector<Varnode *> &inputvars)
{
uint4 flags;
Varnode *vn;
vector<Varnode *>::iterator iter;
bool guardneeded = true;
for(iter=read.begin();iter!=read.end();++iter) {
vn = *iter;
if (vn->getSize() < size)
*iter = vn = normalizeReadSize(vn,addr,size);
vn->setActiveHeritage();
}
for(iter=write.begin();iter!=write.end();++iter) {