forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flow.cc
1391 lines (1253 loc) · 46.5 KB
/
flow.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 "flow.hh"
/// Prepare for tracing flow for a new function.
/// The Funcdata object and references to its internal containers must be explicitly given.
/// \param d is the new function to trace
/// \param o is the internal p-code container for the function
/// \param b is the internal basic block container
/// \param q is the internal container of call sites
FlowInfo::FlowInfo(Funcdata &d,PcodeOpBank &o,BlockGraph &b,vector<FuncCallSpecs *> &q) :
data(d), obank(o), bblocks(b), qlst(q),
baddr(d.getAddress().getSpace(),0),
eaddr(d.getAddress().getSpace(),~((uintb)0)),
minaddr(d.getAddress()),
maxaddr(d.getAddress())
{
glb = data.getArch();
flags = 0;
emitter.setFuncdata(&d);
inline_head = (Funcdata *)0;
inline_recursion = (set<Address> *)0;
insn_count = 0;
insn_max = ~((uint4)0);
flowoverride_present = data.getOverride().hasFlowOverride();
}
/// Prepare a new flow cloned from an existing flow.
/// Configuration from the existing flow is copied, but the actual PcodeOps must already be
/// cloned within the new function.
/// \param d is the new function that has been cloned
/// \param o is the internal p-code container for the function
/// \param b is the internal basic block container
/// \param q is the internal container of call sites
/// \param op2 is the existing flow
FlowInfo::FlowInfo(Funcdata &d,PcodeOpBank &o,BlockGraph &b,vector<FuncCallSpecs *> &q,const FlowInfo *op2) :
data(d), obank(o), bblocks(b), qlst(q),
baddr(op2->baddr),
eaddr(op2->eaddr),
minaddr(d.getAddress()),
maxaddr(d.getAddress())
{
glb = data.getArch();
flags = op2->flags;
emitter.setFuncdata(&d);
unprocessed = op2->unprocessed; // Clone the flow address information
addrlist = op2->addrlist;
visited = op2->visited;
inline_head = op2->inline_head;
if (inline_head != (Funcdata *)0) {
inline_base = op2->inline_base;
inline_recursion = &inline_base;
}
else
inline_recursion = (set<Address> *)0;
insn_count = op2->insn_count;
insn_max = op2->insn_max;
flowoverride_present = data.getOverride().hasFlowOverride();
}
void FlowInfo::clearProperties(void)
{
flags &= ~((uint4)(unimplemented_present|baddata_present|outofbounds_present));
insn_count = 0;
}
/// For efficiency, this method assumes the given op can actually fall-thru.
/// \param op is the given PcodeOp
/// \return the PcodeOp that fall-thru flow would reach (or NULL if there is no possible p-code op)
PcodeOp *FlowInfo::fallthruOp(PcodeOp *op) const
{
PcodeOp *retop;
list<PcodeOp *>::const_iterator iter = op->getInsertIter();
++iter;
if (iter != obank.endDead()) {
retop = *iter;
if (!retop->isInstructionStart()) // If within same instruction
return retop; // Then this is the fall thru
}
// Find address of instruction containing this op
map<Address,VisitStat>::const_iterator miter;
miter = visited.upper_bound(op->getAddr());
if (miter == visited.begin()) return (PcodeOp *)0;
--miter;
if ((*miter).first + (*miter).second.size <= op->getAddr())
return (PcodeOp *)0;
return target( (*miter).first + (*miter).second.size);
}
/// The first p-code op associated with the machine instruction at the
/// given address is returned. If the instruction generated no p-code,
/// an attempt is made to fall-thru to the next instruction.
/// If no p-code op is ultimately found, an exception is thrown.
/// \param addr is the given address of the instruction
/// \return the targetted p-code op
PcodeOp *FlowInfo::target(const Address &addr) const
{
map<Address,VisitStat>::const_iterator iter;
iter = visited.find(addr);
while(iter != visited.end()) {
const SeqNum &seq( (*iter).second.seqnum );
if (!seq.getAddr().isInvalid()) {
PcodeOp *retop = obank.findOp(seq);
if (retop != (PcodeOp *)0)
return retop;
break;
}
// Visit fall thru address in case of no-op
iter = visited.find( (*iter).first + (*iter).second.size );
}
ostringstream errmsg;
errmsg << "Could not find op at target address: (";
errmsg << addr.getSpace()->getName() << ',';
addr.printRaw(errmsg);
errmsg << ')';
throw LowlevelError(errmsg.str());
}
/// \brief Generate the target PcodeOp for a relative branch
///
/// Assuming the given op is a relative branch, find the existing target PcodeOp if the
/// branch is properly internal, or return the fall-thru address in \b res (which may not have
/// PcodeOps generated for it yet) if the relative branch is really a branch to the next instruction.
/// Otherwise an exception is thrown.
/// \param op is the given branching p-code op
/// \param res is a reference to the fall-thru address being passed back
/// \return the target PcodeOp or NULL if the fall-thru address is passed back instead
PcodeOp *FlowInfo::findRelTarget(PcodeOp *op,Address &res) const
{
const Address &addr(op->getIn(0)->getAddr());
uintm id = op->getTime() + addr.getOffset();
SeqNum seqnum(op->getAddr(),id);
PcodeOp *retop = obank.findOp(seqnum);
if (retop != (PcodeOp *)0) // Is this a "properly" internal branch
return retop;
// Now we check if the relative branch is really to the next instruction
SeqNum seqnum1(op->getAddr(),id-1);
retop = obank.findOp(seqnum1); // We go back one sequence number
if (retop != (PcodeOp *)0) {
// If the PcodeOp exists here then branch was indeed to next instruction
map<Address,VisitStat>::const_iterator miter;
miter = visited.upper_bound(retop->getAddr());
if (miter != visited.begin()) {
--miter;
res = (*miter).first + (*miter).second.size;
if (op->getAddr() < res)
return (PcodeOp *)0; // Indicate that res has the fallthru address
}
}
ostringstream errmsg;
errmsg << "Bad relative branch at instruction : (";
errmsg << op->getAddr().getSpace()->getName() << ',';
op->getAddr().printRaw(errmsg);
errmsg << ')';
throw LowlevelError(errmsg.str());
}
/// The \e code \e reference passed as the first parameter to the branch
/// is examined, and the p-code op it refers to is returned.
/// The reference may be a normal direct address or a relative offset.
/// If no target p-code can be found, an exception is thrown.
/// \param op is the given branch op
/// \return the targetted p-code op
PcodeOp *FlowInfo::branchTarget(PcodeOp *op) const
{
const Address &addr(op->getIn(0)->getAddr());
if (addr.isConstant()) { // This is a relative sequence number
Address res;
PcodeOp *retop = findRelTarget(op,res);
if (retop != (PcodeOp *)0)
return retop;
return target(res);
}
return target(addr); // Otherwise a normal address target
}
/// Check to see if the new target has been seen before. Otherwise
/// add it to the list of addresses that need to be processed.
/// Also check range bounds and update basic block information.
/// \param from is the PcodeOp issuing the branch
/// \param to is the target address of the branch
void FlowInfo::newAddress(PcodeOp *from,const Address &to)
{
if ((to < baddr)||(eaddr < to)) {
handleOutOfBounds(from->getAddr(),to);
unprocessed.push_back(to);
return;
}
if (seenInstruction(to)) { // If we have seen this address before
PcodeOp *op = target(to);
data.opMarkStartBasic(op);
return;
}
addrlist.push_back(to);
}
/// \brief Delete any remaining ops at the end of the instruction
///
/// (because they have been predetermined to be dead)
/// \param oiter is the point within the raw p-code list where deletion should start
void FlowInfo::deleteRemainingOps(list<PcodeOp *>::const_iterator oiter)
{
while(oiter != obank.endDead()) {
PcodeOp *op = *oiter;
++oiter;
data.opDestroyRaw(op);
}
}
/// \brief Analyze control-flow within p-code for a single instruction
///
/// Walk through the raw p-code (from the given iterator to the end of the list)
/// looking for control flow operations (BRANCH,CBRANCH,BRANCHIND,CALL,CALLIND,RETURN)
/// and add appropriate annotations (startbasic, callspecs, new addresses).
/// As it iterates through the p-code, the method maintains a reference to a boolean
/// indicating whether the current op is the start of a basic block. This value
/// persists across calls. The method also passes back a boolean value indicating whether
/// the instruction as a whole has fall-thru flow.
/// \param oiter is the given iterator starting the list of p-code ops
/// \param startbasic is the reference holding whether the current op starts a basic block
/// \param isfallthru passes back if the instruction has fall-thru flow
/// \param fc if the p-code is generated from an \e injection, this holds the reference to the injecting sub-function
/// \return the last processed PcodeOp (or NULL if there were no ops in the instruction)
PcodeOp *FlowInfo::xrefControlFlow(list<PcodeOp *>::const_iterator oiter,bool &startbasic,bool &isfallthru,FuncCallSpecs *fc)
{
PcodeOp *op = (PcodeOp *)0;
isfallthru = false;
uintm maxtime=0; // Deepest internal relative branch
while(oiter != obank.endDead()) {
op = *oiter++;
if (startbasic) {
data.opMarkStartBasic(op);
startbasic = false;
}
switch(op->code()) {
case CPUI_CBRANCH:
{
const Address &destaddr( op->getIn(0)->getAddr() );
if (destaddr.isConstant()) {
Address fallThruAddr;
PcodeOp *destop = findRelTarget(op,fallThruAddr);
if (destop != (PcodeOp *)0) {
data.opMarkStartBasic(destop); // Make sure the target op is a basic block start
uintm newtime = destop->getTime();
if (newtime > maxtime)
maxtime = newtime;
}
else
isfallthru = true; // Relative branch is to end of instruction
}
else
newAddress(op,destaddr); // Generate branch address
startbasic = true;
}
break;
case CPUI_BRANCH:
{
const Address &destaddr( op->getIn(0)->getAddr() );
if (destaddr.isConstant()) {
Address fallThruAddr;
PcodeOp *destop = findRelTarget(op,fallThruAddr);
if (destop != (PcodeOp *)0) {
data.opMarkStartBasic(destop); // Make sure the target op is a basic block start
uintm newtime = destop->getTime();
if (newtime > maxtime)
maxtime = newtime;
}
else
isfallthru = true; // Relative branch is to end of instruction
}
else
newAddress(op,destaddr); // Generate branch address
if (op->getTime() >= maxtime) {
deleteRemainingOps(oiter);
oiter = obank.endDead();
}
startbasic = true;
}
break;
case CPUI_BRANCHIND:
tablelist.push_back(op); // Put off trying to recover the table
if (op->getTime() >= maxtime) {
deleteRemainingOps(oiter);
oiter = obank.endDead();
}
startbasic = true;
break;
case CPUI_RETURN:
if (op->getTime() >= maxtime) {
deleteRemainingOps(oiter);
oiter = obank.endDead();
}
startbasic = true;
break;
case CPUI_CALL:
if (setupCallSpecs(op,fc))
--oiter; // Backup one op, to pickup halt
break;
case CPUI_CALLIND:
if (setupCallindSpecs(op,true,fc))
--oiter; // Backup one op, to pickup halt
break;
case CPUI_CALLOTHER:
{
InjectedUserOp *userop = dynamic_cast<InjectedUserOp *>(glb->userops.getOp(op->getIn(0)->getOffset()));
if (userop != (InjectedUserOp *)0)
injectlist.push_back(op);
break;
}
default:
break;
}
}
if (isfallthru) // We have seen an explicit relative branch to end of instruction
startbasic = true; // So we know next instruction starts a basicblock
else { // If we haven't seen a relative branch, calculate fallthru by looking at last op
if (op == (PcodeOp *)0)
isfallthru = true; // No ops at all, mean a fallthru
else {
switch(op->code()) {
case CPUI_BRANCH:
case CPUI_BRANCHIND:
case CPUI_RETURN:
break; // If the last instruction is a branch, then no fallthru
default:
isfallthru = true; // otherwise it is a fallthru
break;
}
}
}
return op;
}
/// \brief Generate p-code for a single machine instruction and process discovered flow information
///
/// P-code is generated (to the raw \e dead list in PcodeOpBank). Errors for unimplemented
/// instructions or inaccessible data are handled. The p-code is examined for control-flow,
/// and annotations are made. The set of visited instructions and the set of
/// addresses still needing to be processed are updated.
/// \param curaddr is the address of the instruction to process
/// \param startbasic indicates of the instruction starts a basic block and passes back whether the next instruction does
/// \return \b true if the processed instruction has a fall-thru flow
bool FlowInfo::processInstruction(const Address &curaddr,bool &startbasic)
{
bool emptyflag;
bool isfallthru = true;
// JumpTable *jt;
list<PcodeOp *>::const_iterator oiter;
int4 step;
uint4 flowoverride;
if (insn_count >= insn_max) {
if ((flags & error_toomanyinstructions)!=0)
throw LowlevelError("Flow exceeded maximum allowable instructions");
else {
step = 1;
artificialHalt(curaddr,PcodeOp::badinstruction);
data.warning("Too many instructions -- Truncating flow here",curaddr);
if (!hasTooManyInstructions()) {
flags |= toomanyinstructions_present;
data.warningHeader("Exceeded maximum allowable instructions: Some flow is truncated");
}
}
}
insn_count += 1;
if (obank.empty())
emptyflag = true;
else {
emptyflag = false;
oiter = obank.endDead();
--oiter;
}
if (flowoverride_present)
flowoverride = data.getOverride().getFlowOverride(curaddr);
else
flowoverride = Override::NONE;
try {
step = glb->translate->oneInstruction(emitter,curaddr); // Generate ops for instruction
}
catch(UnimplError &err) { // Instruction is unimplemented
if ((flags & ignore_unimplemented)!=0) {
step = err.instruction_length;
if (!hasUnimplemented()) {
flags |= unimplemented_present;
data.warningHeader("Control flow ignored unimplemented instructions");
}
}
else if ((flags & error_unimplemented)!=0)
throw err; // rethrow
else {
// Add infinite loop instruction
step = 1; // Pretend size 1
artificialHalt(curaddr,PcodeOp::unimplemented);
data.warning("Unimplemented instruction - Truncating control flow here",curaddr);
if (!hasUnimplemented()) {
flags |= unimplemented_present;
data.warningHeader("Control flow encountered unimplemented instructions");
}
}
}
catch(BadDataError &err) {
if ((flags & error_unimplemented)!=0)
throw err; // rethrow
else {
// Add infinite loop instruction
step = 1; // Pretend size 1
artificialHalt(curaddr,PcodeOp::badinstruction);
data.warning("Bad instruction - Truncating control flow here",curaddr);
if (!hasBadData()) {
flags |= baddata_present;
data.warningHeader("Control flow encountered bad instruction data");
}
}
}
VisitStat &stat(visited[curaddr]); // Mark that we visited this instruction
stat.size = step; // Record size of instruction
if (curaddr < minaddr) // Update minimum and maximum address
minaddr = curaddr;
if (maxaddr < curaddr+step) // Keep track of biggest and smallest address
maxaddr = curaddr+step;
if (emptyflag) // Make sure oiter points at first new op
oiter = obank.beginDead();
else
++oiter;
if (oiter != obank.endDead()) {
stat.seqnum = (*oiter)->getSeqNum();
data.opMarkStartInstruction(*oiter); // Mark the first op in the instruction
if (flowoverride != Override::NONE)
data.overrideFlow(curaddr,flowoverride);
xrefControlFlow(oiter,startbasic,isfallthru,(FuncCallSpecs *)0);
}
if (isfallthru)
addrlist.push_back(curaddr+step);
return isfallthru;
}
/// From the address at the top of the \b addrlist stack
/// Figure out how far we could follow fall-thru instructions
/// before hitting something we've already seen
/// \param bound passes back the first address encountered that we have already seen
/// \return \b false if the address has already been visited
bool FlowInfo::setFallthruBound(Address &bound)
{
map<Address,VisitStat>::const_iterator iter;
const Address &addr( addrlist.back() );
iter = visited.upper_bound(addr); // First range greater than addr
if (iter!=visited.begin()) {
--iter; // Last range less than or equal to us
if (addr == (*iter).first) { // If we have already visited this address
addrlist.pop_back(); // Throw it away
PcodeOp *op = target(addr); // But make sure the address
data.opMarkStartBasic(op); // starts a basic block
return false;
}
if (addr < (*iter).first + (*iter).second.size)
reinterpreted(addr);
++iter;
}
if (iter!=visited.end()) // Whats the maximum distance we can go
bound = (*iter).first;
else
bound = eaddr;
return true;
}
/// \brief Generate warning message or throw exception for given flow that is out of bounds
///
/// \param fromaddr is the source address of the flow (presumably in bounds)
/// \param toaddr is the given destination address that is out of bounds
void FlowInfo::handleOutOfBounds(const Address &fromaddr,const Address &toaddr)
{
if ((flags&ignore_outofbounds)==0) { // Should we throw an error for out of bounds
ostringstream errmsg;
errmsg << "Function flow out of bounds: ";
errmsg << fromaddr.getShortcut();
fromaddr.printRaw(errmsg);
errmsg << " flows to ";
errmsg << toaddr.getShortcut();
toaddr.printRaw(errmsg);
if ((flags&error_outofbounds)==0) {
data.warning(errmsg.str(),toaddr);
if (!hasOutOfBounds()) {
flags |= outofbounds_present;
data.warningHeader("Function flows out of bounds");
}
}
else
throw LowlevelError(errmsg.str());
}
}
/// The address at the top stack that still needs processing is popped.
/// P-code is generated for instructions starting at this address until
/// one no longer has fall-thru flow (or some other error occurs).
void FlowInfo::fallthru(void)
{
Address bound;
if (!setFallthruBound(bound)) return;
Address curaddr;
bool startbasic = true;
bool fallthruflag;
for(;;) {
curaddr = addrlist.back();
addrlist.pop_back();
fallthruflag = processInstruction(curaddr,startbasic);
if (!fallthruflag) break;
if (addrlist.empty()) break;
if (bound <= addrlist.back()) {
if (bound == eaddr) {
handleOutOfBounds(eaddr,addrlist.back());
unprocessed.push_back(addrlist.back());
addrlist.pop_back();
return;
}
if (bound == addrlist.back()) { // Hit the bound exactly
if (startbasic) {
PcodeOp *op = target(addrlist.back());
data.opMarkStartBasic(op);
}
addrlist.pop_back();
break;
}
if (!setFallthruBound(bound)) return; // Reset bound
}
}
}
/// An \b artificial \b halt, is a special form of RETURN op.
/// The op is annotated with the desired \e type of artificial halt.
/// - Bad instruction
/// - Unimplemented instruction
/// - Missing/truncated instruction
/// - (Previous) call that never returns
///
/// \param addr is the target address for the new p-code op
/// \param flag is the desired \e type
/// \return the new p-code op
PcodeOp *FlowInfo::artificialHalt(const Address &addr,uint4 flag)
{
PcodeOp *haltop = data.newOp(1,addr);
data.opSetOpcode(haltop,CPUI_RETURN);
data.opSetInput(haltop,data.newConstant(4,1),0);
if (flag != 0)
data.opMarkHalt(haltop,flag); // What kind of halt
return haltop;
}
/// A set of bytes is \b reinterpreted if there are at least two
/// different interpretations of the bytes as instructions.
/// \param addr is the address of a byte previously interpreted as (the interior of) an instruction
void FlowInfo::reinterpreted(const Address &addr)
{
map<Address,VisitStat>::const_iterator iter;
iter = visited.upper_bound(addr);
if (iter==visited.begin()) return; // Should never happen
--iter;
const Address &addr2( (*iter).first );
ostringstream s;
s << "Instruction at (" << addr.getSpace()->getName() << ',';
addr.printRaw(s);
s << ") overlaps instruction at (" << addr2.getSpace()->getName() << ',';
addr2.printRaw(s);
s << ')' << endl;
if ((flags & error_reinterpreted)!=0)
throw LowlevelError(s.str());
if ((flags & reinterpreted_present)==0) {
flags |= reinterpreted_present;
data.warningHeader(s.str());
}
}
/// \brief Check for modifications to flow at a call site given the recovered FuncCallSpecs
///
/// The sub-function may be in-lined or never return.
/// \param fspecs is the given call site
/// \return \b true if the sub-function never returns
bool FlowInfo::checkForFlowModification(FuncCallSpecs &fspecs)
{
if (fspecs.isInline())
injectlist.push_back(fspecs.getOp());
if (fspecs.isNoReturn()) {
PcodeOp *op = fspecs.getOp();
PcodeOp *haltop = artificialHalt(op->getAddr(),PcodeOp::noreturn);
data.opDeadInsertAfter(haltop,op);
if (!fspecs.isInline())
data.warning("Subroutine does not return",op->getAddr());
return true;
}
return false;
}
/// If there is an explicit target address for the given call site,
/// attempt to look up the function and adjust information in the FuncCallSpecs call site object.
/// \param fspecs is the call site object
void FlowInfo::queryCall(FuncCallSpecs &fspecs)
{
if (!fspecs.getEntryAddress().isInvalid()) { // If this is a direct call
Funcdata *otherfunc = data.getScopeLocal()->getParent()->queryFunction( fspecs.getEntryAddress() );
if (otherfunc != (Funcdata *)0) {
fspecs.setFuncdata(otherfunc); // Associate the symbol with the callsite
if (!fspecs.hasModel()) { // If the prototype was not overridden
fspecs.copyFlowEffects(otherfunc->getFuncProto()); // Take the symbols's prototype
// If the callsite is applying just the standard prototype from the symbol,
// this postpones the full copy of the prototype until ActionDefaultParams
// Which lets "last second" changes come in, between when the function is first walked and
// when it is finally decompiled
}
}
}
}
/// The new FuncCallSpecs object is created and initialized based on
/// the CALL op at the site and any matching function in the symbol table.
/// Any overriding prototype or control-flow is examined and applied.
/// \param op is the given CALL op
/// \param fc is non-NULL if \e injection is in progress and a cycle check needs to be made
/// \return \b true if it is discovered the sub-function never returns
bool FlowInfo::setupCallSpecs(PcodeOp *op,FuncCallSpecs *fc)
{
FuncCallSpecs *res;
res = new FuncCallSpecs(op);
data.opSetInput(op,data.newVarnodeCallSpecs(res),0);
qlst.push_back(res);
data.getOverride().applyPrototype(data,*res);
queryCall(*res);
if (fc != (FuncCallSpecs *)0) { // If we are already in the midst of an injection
if (fc->getEntryAddress() == res->getEntryAddress())
res->cancelInjectId(); // Don't allow recursion
}
return checkForFlowModification(*res);
}
/// \brief Set up the FuncCallSpecs object for a new indirect call site
///
/// The new FuncCallSpecs object is created and initialized based on
/// the CALLIND op at the site. Any overriding prototype or control-flow may be examined and applied.
/// \param op is the given CALLIND op
/// \param tryoverride is \b true is overrides should be applied for the call site
/// \param fc is non-NULL if \e injection is in progress and a cycle check needs to be made
/// \return \b true if it is discovered the sub-function never returns
bool FlowInfo::setupCallindSpecs(PcodeOp *op,bool tryoverride,FuncCallSpecs *fc)
{
FuncCallSpecs *res;
res = new FuncCallSpecs(op);
qlst.push_back(res);
if (tryoverride) {
data.getOverride().applyIndirect(data,*res);
data.getOverride().applyPrototype(data,*res);
}
queryCall(*res);
if (fc != (FuncCallSpecs *)0) {
if (fc->getEntryAddress() == res->getEntryAddress()) {
res->cancelInjectId();
res->setAddress(Address()); // Cancel any indirect override
}
}
if (!res->getEntryAddress().isInvalid()) { // If we are overridden to a direct call
// Change indirect pcode call into a normal pcode call
data.opSetOpcode(op,CPUI_CALL); // Set normal opcode
data.opSetInput(op,data.newVarnodeCallSpecs(res),0);
}
return checkForFlowModification(*res);
}
/// \param op is the BRANCHIND operation to convert
/// \param failuremode is a code indicating the type of failure when trying to recover the jump table
void FlowInfo::truncateIndirectJump(PcodeOp *op,int4 failuremode)
{
data.opSetOpcode(op,CPUI_CALLIND); // Turn jump into call
bool tryoverride = (failuremode == 2);
setupCallindSpecs(op,tryoverride,(FuncCallSpecs *)0);
data.getCallSpecs(op)->setBadJumpTable(true);
// Create an artificial return
PcodeOp *truncop = artificialHalt(op->getAddr(),0);
data.opDeadInsertAfter(truncop,op);
data.warning("Treating indirect jump as call",op->getAddr());
}
/// \brief Test if the given p-code op is a member of an array
///
/// \param array is the array of p-code ops to search
/// \param op is the given p-code op to search for
/// \return \b true if the op is a member of the array
bool FlowInfo::isInArray(vector<PcodeOp *> &array,PcodeOp *op)
{
for(int4 i=0;i<array.size();++i) {
if (array[i] == op) return true;
}
return false;
}
void FlowInfo::generateOps(void)
{
vector<PcodeOp *> notreached; // indirect ops that are not reachable
int4 notreachcnt = 0;
clearProperties();
addrlist.push_back(data.getAddress());
while(!addrlist.empty()) // Recovering as much as possible except jumptables
fallthru();
do {
bool collapsed_jumptable = false;
while(!tablelist.empty()) { // For each jumptable found
PcodeOp *op = tablelist.back();
tablelist.pop_back();
int4 failuremode;
JumpTable *jt = data.recoverJumpTable(op,this,failuremode); // Recover it
if (jt == (JumpTable *)0) { // Could not recover jumptable
if ((failuremode == 3) && (!tablelist.empty()) && (!isInArray(notreached,op))) {
// If the indirect op was not reachable with current flow AND there is more flow to generate,
// AND we haven't tried to recover this table before
notreached.push_back(op); // Save this op so we can try to recovery table again later
}
else if (!isFlowForInline()) // Unless this flow is being inlined for something else
truncateIndirectJump(op,failuremode); // Treat the indirect jump as a call
}
else {
int4 num = jt->numEntries();
for(int4 i=0;i<num;++i)
newAddress(op,jt->getAddressByIndex(i));
if (jt->isPossibleMultistage())
collapsed_jumptable = true;
while(!addrlist.empty()) // Try to fill in as much more as possible
fallthru();
}
}
checkContainedCall(); // Check for PIC constructions
if (collapsed_jumptable)
checkMultistageJumptables();
while(notreachcnt < notreached.size()) {
tablelist.push_back(notreached[notreachcnt]);
notreachcnt += 1;
}
if (hasInject())
injectPcode();
} while(!tablelist.empty()); // Inlining or multistage may have added new indirect branches
}
void FlowInfo::generateBlocks(void)
{
fillinBranchStubs();
collectEdges();
splitBasic(); // Split ops up into basic blocks
connectBasic(); // Generate edges between basic blocks
if (bblocks.getSize()!=0) {
FlowBlock *startblock = bblocks.getBlock(0);
if (startblock->sizeIn() != 0) { // Make sure the entry block has no incoming edges
// If it does we create a new entry block that flows into the old entry block
BlockBasic *newfront = bblocks.newBlockBasic(&data);
bblocks.addEdge(newfront,startblock);
bblocks.setStartBlock(newfront);
data.setBasicBlockRange(newfront, data.getAddress(), data.getAddress());
}
}
if (hasPossibleUnreachable())
data.removeUnreachableBlocks(false,true);
}
/// In the case where additional flow is truncated, run through the list of
/// pending addresses, and if they don't have a p-code generated for them,
/// add the Address to the \b unprocessed array.
void FlowInfo::findUnprocessed(void)
{
vector<Address>::iterator iter;
for(iter=addrlist.begin();iter!=addrlist.end();++iter) {
if (seenInstruction(*iter)) {
PcodeOp *op = target(*iter);
data.opMarkStartBasic(op);
}
else
unprocessed.push_back(*iter);
}
}
/// The list is also sorted
void FlowInfo::dedupUnprocessed(void)
{
if (unprocessed.empty()) return;
sort(unprocessed.begin(),unprocessed.end());
vector<Address>::iterator iter1,iter2;
iter1 = unprocessed.begin();
Address lastaddr = *iter1++;
iter2 = iter1;
while(iter1 != unprocessed.end()) {
if (*iter1==lastaddr)
iter1++;
else {
lastaddr = *iter1++;
*iter2++ = lastaddr;
}
}
unprocessed.erase(iter2,unprocessed.end());
}
/// A special form of RETURN instruction is generated for every address in
/// the \b unprocessed list.
void FlowInfo::fillinBranchStubs(void)
{
vector<Address>::iterator iter;
findUnprocessed();
dedupUnprocessed();
for(iter=unprocessed.begin();iter!=unprocessed.end();++iter) {
PcodeOp *op = artificialHalt(*iter,PcodeOp::missing);
data.opMarkStartBasic(op);
data.opMarkStartInstruction(op);
}
}
/// An edge is held as matching PcodeOp entries in \b block_edge1 and \b block_edge2.
/// Edges are generated for fall-thru to a p-code op marked as the start of a basic block
/// or for an explicit branch.
void FlowInfo::collectEdges(void)
{
list<PcodeOp *>::const_iterator iter,iterend,iter1,iter2;
PcodeOp *op,*targ_op;
JumpTable *jt;
bool nextstart;
int4 i,num;
if (bblocks.getSize() != 0)
throw RecovError("Basic blocks already calculated\n");
iter = obank.beginDead();
iterend = obank.endDead();
while(iter!=iterend) {
op = *iter++;
if (iter==iterend)
nextstart = true;
else
nextstart = (*iter)->isBlockStart();
switch(op->code()) {
case CPUI_BRANCH:
targ_op = branchTarget(op);
block_edge1.push_back(op);
// block_edge2.push_back(op->Input(0)->getAddr().Iop());
block_edge2.push_back(targ_op);
break;
case CPUI_BRANCHIND:
jt = data.findJumpTable(op);
if (jt == (JumpTable *)0) break;
// If we are in this routine and there is no table
// Then we must be doing partial flow analysis
// so assume there are no branches out
num = jt->numEntries();
for(i=0;i<num;++i) {
targ_op = target(jt->getAddressByIndex(i));
if (targ_op->isMark()) continue; // Already a link between these blocks
targ_op->setMark();
block_edge1.push_back(op);
block_edge2.push_back(targ_op);
}
iter1 = block_edge1.end(); // Clean up our marks
iter2 = block_edge2.end();
while(iter1 != block_edge1.begin()) {
--iter1;
--iter2;
if ((*iter1)==op)
(*iter2)->clearMark();
else
break;
}
break;
case CPUI_RETURN:
break;
case CPUI_CBRANCH:
targ_op = fallthruOp(op); // Put in fallthru edge
block_edge1.push_back(op);
block_edge2.push_back(targ_op);
targ_op = branchTarget(op);
block_edge1.push_back(op);
block_edge2.push_back(targ_op);
break;
default:
if (nextstart) { // Put in fallthru edge if new basic block
targ_op = fallthruOp(op);
block_edge1.push_back(op);
block_edge2.push_back(targ_op);
}
break;
}
}
}
/// PcodeOp objects are moved out of the PcodeOpBank \e dead list into their
/// assigned PcodeBlockBasic. Initial address ranges of instructions are recorded in the block.
/// PcodeBlockBasic objects are created based on p-code ops that have been
/// previously marked as \e start of basic block.
void FlowInfo::splitBasic(void)
{
PcodeOp *op;
BlockBasic *cur;
list<PcodeOp *>::const_iterator iter,iterend;
iter = obank.beginDead();
iterend = obank.endDead();
if (iter == iterend) return;
op = *iter++;
if (!op->isBlockStart())
throw LowlevelError("First op not marked as entry point");
cur = bblocks.newBlockBasic(&data);
data.opInsert(op,cur,cur->endOp());
bblocks.setStartBlock(cur);
Address start = op->getAddr();
Address stop = start;
while(iter != iterend) {
op = *iter++;
if (op->isBlockStart()) {
data.setBasicBlockRange(cur, start, stop);
cur = bblocks.newBlockBasic(&data); // Set up the next basic block
start = op->getSeqNum().getAddr();
stop = start;
}
else {
const Address &nextAddr( op->getAddr() );
if (stop < nextAddr)
stop = nextAddr;
}
data.opInsert(op,cur,cur->endOp());
}
data.setBasicBlockRange(cur, start, stop);
}
/// Directed edges between the PcodeBlockBasic objects are created based on the
/// previously collected p-code op pairs in \b block_edge1 and \b block_edge2
void FlowInfo::connectBasic(void)
{
PcodeOp *op,*targ_op;
BlockBasic *bs,*targ_bs;
list<PcodeOp *>::const_iterator iter,iter2;