forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fspec.cc
4943 lines (4453 loc) · 165 KB
/
fspec.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 "fspec.hh"
#include "funcdata.hh"
void ParamEntry::resolveJoin(void)
{
if (spaceid->getType() == IPTR_JOIN)
joinrec = spaceid->getManager()->findJoin(addressbase);
else
joinrec = (JoinRecord *)0;
}
/// \brief Construct entry from components
///
/// \param t is the data-type class (TYPE_UNKNOWN or TYPE_FLOAT)
/// \param grp is the group id
/// \param grpsize is the number of consecutive groups occupied
/// \param loc is the starting address of the memory range
/// \param sz is the number of bytes in the range
/// \param mnsz is the smallest size of a logical value
/// \param align is the alignment (0 means the memory range will hold one parameter exclusively)
/// \param normalstack is \b true if parameters are allocated from the front of the range
ParamEntry::ParamEntry(type_metatype t,int4 grp,int4 grpsize,const Address &loc,int4 sz,int4 mnsz,int4 align,bool normalstack)
{
flags = 0;
type = t;
group = grp;
groupsize = grpsize;
spaceid = loc.getSpace();
addressbase = loc.getOffset();
size = sz;
minsize = mnsz;
alignment = align;
if (alignment != 0)
numslots = size / alignment;
else
numslots = 1;
if (!normalstack)
flags |= reverse_stack;
resolveJoin();
}
/// This entry must properly contain the other memory range, and
/// the entry properties must be compatible.
/// \param op2 is the other entry to compare with \b this
/// \return \b true if the other entry is contained
bool ParamEntry::contains(const ParamEntry &op2) const
{
if ((type!=TYPE_UNKNOWN)&&(op2.type != type)) return false;
if (spaceid != op2.spaceid) return false;
if (op2.addressbase < addressbase) return false;
if ((op2.addressbase+op2.size-1) > (addressbase+size-1)) return false;
if (alignment != op2.alignment) return false;
return true;
}
/// \param addr is the starting address of the potential containing range
/// \param sz is the number of bytes in the range
/// \return \b true if the entire ParamEntry fits inside the range
bool ParamEntry::containedBy(const Address &addr,int4 sz) const
{
if (spaceid != addr.getSpace()) return false;
if (addressbase < addr.getOffset()) return false;
uintb entryoff = addressbase + size-1;
uintb rangeoff = addr.getOffset() + sz-1;
return (entryoff <= rangeoff);
}
/// Check if the given memory range is contained in \b this.
/// If it is contained, return the endian aware offset of the containment.
/// I.e. if the least significant byte of the given range falls on the least significant
/// byte of the \b this, return 0. If it intersects the second least significant, return 1, etc.
/// \param addr is the starting address of the given memory range
/// \param sz is the size of the given memory range in bytes
/// \return the endian aware alignment or -1 if the given range isn't contained
int4 ParamEntry::justifiedContain(const Address &addr,int4 sz) const
{
if (joinrec != (JoinRecord *)0) {
int4 res = 0;
for(int4 i=joinrec->numPieces()-1;i>=0;--i) { // Move from least significant to most
const VarnodeData &vdata(joinrec->getPiece(i));
int4 cur = vdata.getAddr().justifiedContain(vdata.size,addr,sz,false);
if (cur<0)
res += vdata.size; // We skipped this many less significant bytes
else {
return res + cur;
}
}
return -1; // Not contained at all
}
if (alignment==0) {
// Ordinary endian containment
Address entry(spaceid,addressbase);
return entry.justifiedContain(size,addr,sz,((flags&force_left_justify)!=0));
}
if (spaceid != addr.getSpace()) return -1;
uintb startaddr = addr.getOffset();
if (startaddr < addressbase) return -1;
uintb endaddr = startaddr + sz - 1;
if (endaddr < startaddr) return -1; // Don't allow wrap around
if (endaddr > (addressbase+size-1)) return -1;
startaddr -= addressbase;
endaddr -= addressbase;
if (!isLeftJustified()) { // For right justified (big endian), endaddr must be aligned
int4 res = (int4)((endaddr+1) % alignment);
if (res==0) return 0;
return (alignment-res);
}
return (int4)(startaddr % alignment);
}
/// \brief Calculate the containing memory range
///
/// Pass back the VarnodeData (space,offset,size) of the parameter that would contain
/// the given memory range. If \b this contains the range and is \e exclusive, just
/// pass back \b this memory range. Otherwise the passed back range will depend on
/// alignment.
/// \param addr is the starting address of the given range
/// \param sz is the size of the given range in bytes
/// \param res is the reference to VarnodeData that will be passed back
/// \return \b true if the given range is contained at all
bool ParamEntry::getContainer(const Address &addr,int4 sz,VarnodeData &res) const
{
Address endaddr = addr + (sz-1);
if (joinrec != (JoinRecord *)0) {
for(int4 i=joinrec->numPieces()-1;i>=0;--i) { // Move from least significant to most
const VarnodeData &vdata(joinrec->getPiece(i));
if ((addr.overlap(0,vdata.getAddr(),vdata.size) >=0)&&
(endaddr.overlap(0,vdata.getAddr(),vdata.size)>=0)) {
res = vdata;
return true;
}
}
return false; // Not contained at all
}
Address entry(spaceid,addressbase);
if (addr.overlap(0,entry,size)<0) return false;
if (endaddr.overlap(0,entry,size)<0) return false;
if (alignment==0) {
// Ordinary endian containment
res.space = spaceid;
res.offset = addressbase;
res.size = size;
return true;
}
uintb al = (addr.getOffset() - addressbase) % alignment;
res.space = spaceid;
res.offset = addr.getOffset() - al;
res.size = (int4)(endaddr.getOffset()-res.offset) + 1;
int4 al2 = res.size % alignment;
if (al2 != 0)
res.size += (alignment - al2); // Bump up size to nearest alignment
return true;
}
/// \brief Calculate the type of \e extension to expect for the given logical value
///
/// Return:
/// - CPUI_COPY if no extensions are assumed for small values in this container
/// - CPUI_INT_SEXT indicates a sign extension
/// - CPUI_INT_ZEXT indicates a zero extension
/// - CPUI_PIECE indicates an integer extension based on type of parameter
///
/// (A CPUI_FLOAT2FLOAT=float extension is handled by heritage and JoinRecord)
/// If returning an extension operator, pass back the container being extended.
/// \param addr is the starting address of the logical value
/// \param sz is the size of the logical value in bytes
/// \param res will hold the passed back containing range
/// \return the type of extension
OpCode ParamEntry::assumedExtension(const Address &addr,int4 sz,VarnodeData &res) const
{
if ((flags & (smallsize_zext|smallsize_sext|smallsize_inttype))==0) return CPUI_COPY;
if (alignment != 0) {
if (sz >= alignment)
return CPUI_COPY;
}
else if (sz >= size)
return CPUI_COPY;
if (joinrec != (JoinRecord *)0) return CPUI_COPY;
if (justifiedContain(addr,sz)!=0) return CPUI_COPY; // (addr,sz) is not justified properly to allow an extension
if (alignment == 0) { // If exclusion, take up the whole entry
res.space = spaceid;
res.offset = addressbase;
res.size = size;
}
else { // Otherwise take up whole alignment
res.space = spaceid;
int4 alignAdjust = (addr.getOffset() - addressbase) % alignment;
res.offset = addr.getOffset() - alignAdjust;
res.size = alignment;
}
if ((flags & smallsize_zext)!=0)
return CPUI_INT_ZEXT;
if ((flags & smallsize_inttype)!=0)
return CPUI_PIECE;
return CPUI_INT_SEXT;
}
/// \brief Calculate the \e slot occupied by a specific address
///
/// For \e non-exclusive entries, the memory range can be divided up into
/// \b slots, which are chunks that take up a full alignment. I.e. for an entry with
/// alignment 4, slot 0 is bytes 0-3 of the range, slot 1 is bytes 4-7, etc.
/// Assuming the given address is contained in \b this entry, and we \b skip ahead a number of bytes,
/// return the \e slot associated with that byte.
/// NOTE: its important that the given address has already been checked for containment.
/// \param addr is the given address
/// \param skip is the number of bytes to skip ahead
/// \return the slot index
int4 ParamEntry::getSlot(const Address &addr,int4 skip) const
{
int4 res = group;
if (alignment != 0) {
uintb diff = addr.getOffset() + skip - addressbase;
int4 baseslot = (int4)diff / alignment;
if (isReverseStack())
res += (numslots -1) - baseslot;
else
res += baseslot;
}
else if (skip != 0) {
res += (groupsize-1);
}
return res;
}
/// \brief Calculate the storage address assigned when allocating a parameter of a given size
///
/// Assume \b slotnum slots have already been assigned and increment \b slotnum
/// by the number of slots used.
/// Return an invalid address if the size is too small or if there are not enough slots left.
/// \param slotnum is a reference to used slots (which will be updated)
/// \param sz is the size of the parameter to allocated
/// \return the address of the new parameter (or an invalid address)
Address ParamEntry::getAddrBySlot(int4 &slotnum,int4 sz) const
{
Address res; // Start with an invalid result
int4 spaceused;
if (sz < minsize) return res;
if (alignment == 0) { // If not an aligned entry (allowing multiple slots)
if (slotnum != 0) return res; // Can only allocate slot 0
if (sz > size) return res; // Check on maximum size
res = Address(spaceid,addressbase); // Get base address of the slot
spaceused = size;
if (((flags & smallsize_floatext)!=0)&&(sz != size)) { // Do we have an implied floating-point extension
AddrSpaceManager *manager = spaceid->getManager();
res = manager->constructFloatExtensionAddress(res,size,sz);
return res;
}
}
else {
int4 slotsused = sz / alignment; // How many slots does a -sz- byte object need
if ( (sz % alignment) != 0)
slotsused += 1;
if (slotnum + slotsused > numslots) // Check if there are enough slots left
return res;
spaceused = slotsused * alignment;
int4 index;
if (isReverseStack()) {
index = numslots;
index -= slotnum;
index -= slotsused;
}
else
index = slotnum;
res = Address(spaceid, addressbase + index * alignment);
slotnum += slotsused; // Inform caller of number of slots used
}
if (!isLeftJustified()) // Adjust for right justified (big endian)
res = res + (spaceused - sz);
return res;
}
/// \brief Restore the entry from an XML stream
///
/// \param el is the root \<pentry> element
/// \param manage is a manager to resolve address space references
/// \param normalstack is \b true if the parameters should be allocated from the front of the range
void ParamEntry::restoreXml(const Element *el,const AddrSpaceManager *manage,bool normalstack)
{
flags = 0;
type = TYPE_UNKNOWN;
size = minsize = -1; // Must be filled in
alignment = 0; // default
numslots = 1;
groupsize = 1; // default
int4 num = el->getNumAttributes();
for(int4 i=0;i<num;++i) {
const string &attrname( el->getAttributeName(i) );
if (attrname=="minsize") {
istringstream i1(el->getAttributeValue(i));
i1.unsetf(ios::dec | ios::hex | ios::oct);
i1 >> minsize;
}
else if (attrname == "size") { // old style
istringstream i2(el->getAttributeValue(i));
i2.unsetf(ios::dec | ios::hex | ios::oct);
i2 >> alignment;
}
else if (attrname == "align") { // new style
istringstream i4(el->getAttributeValue(i));
i4.unsetf(ios::dec | ios::hex | ios::oct);
i4 >> alignment;
}
else if (attrname == "maxsize") {
istringstream i3(el->getAttributeValue(i));
i3.unsetf(ios::dec | ios::hex | ios::oct);
i3 >> size;
}
else if (attrname == "metatype")
type = string2metatype(el->getAttributeValue(i));
else if (attrname == "group") { // Override the group
istringstream i5(el->getAttributeValue(i));
i5.unsetf(ios::dec | ios::hex | ios::oct);
i5 >> group;
}
else if (attrname == "groupsize") {
istringstream i6(el->getAttributeValue(i));
i6.unsetf(ios::dec | ios::hex | ios::oct);
i6 >> groupsize;
}
else if (attrname == "extension") {
flags &= ~((uint4)(smallsize_zext | smallsize_sext | smallsize_inttype));
if (el->getAttributeValue(i) == "sign")
flags |= smallsize_sext;
else if (el->getAttributeValue(i) == "zero")
flags |= smallsize_zext;
else if (el->getAttributeValue(i) == "inttype")
flags |= smallsize_inttype;
else if (el->getAttributeValue(i) == "float")
flags |= smallsize_floatext;
else if (el->getAttributeValue(i) != "none")
throw LowlevelError("Bad extension attribute");
}
else
throw LowlevelError("Unknown ParamEntry attribute: "+attrname);
}
if ((size==-1)||(minsize==-1))
throw LowlevelError("ParamEntry not fully specified");
if (alignment == size)
alignment = 0;
Address addr;
addr = Address::restoreXml( *el->getChildren().begin(),manage);
spaceid = addr.getSpace();
addressbase = addr.getOffset();
if (alignment != 0) {
// if ((addressbase % alignment) != 0)
// throw LowlevelError("Stack <pentry> address must match alignment");
numslots = size / alignment;
}
if (spaceid->isReverseJustified()) {
if (spaceid->isBigEndian())
flags |= force_left_justify;
else
throw LowlevelError("No support for right justification in little endian encoding");
}
if (!normalstack) {
flags |= reverse_stack;
if (alignment != 0) {
if ((size % alignment) != 0)
throw LowlevelError("For positive stack growth, <pentry> size must match alignment");
}
}
resolveJoin();
}
/// \brief Check if \b this entry represents a \e joined parameter and requires extra scrutiny
///
/// Return value parameter lists allow overlapping entries if one of the overlapping entries
/// is a \e joined parameter. In this case the return value recovery logic needs to know
/// what portion(s) of the joined parameter are overlapped. This method sets flags on \b this
/// to indicate the overlap.
/// \param entry is the full parameter list to check for overlaps with \b this
void ParamEntry::extraChecks(list<ParamEntry> &entry)
{
if (joinrec == (JoinRecord *)0) return; // Nothing to do if not multiprecision
if (joinrec->numPieces() != 2) return;
const VarnodeData &highPiece(joinrec->getPiece(0));
bool seenOnce = false;
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) { // Search for high piece, used as whole/low in another entry
AddrSpace *spc = (*iter).getSpace();
uintb off = (*iter).getBase();
int4 sz = (*iter).getSize();
if ((highPiece.offset == off)&&(highPiece.space == spc)&&(highPiece.size == sz)) {
if (seenOnce) throw LowlevelError("Extra check hits twice");
seenOnce = true;
flags |= extracheck_low; // If found, we must do extra checks on the low
}
}
if (!seenOnce)
flags |= extracheck_high; // The default is to do extra checks on the high
}
ParamListStandard::ParamListStandard(const ParamListStandard &op2)
{
numgroup = op2.numgroup;
entry = op2.entry;
spacebase = op2.spacebase;
maxdelay = op2.maxdelay;
pointermax = op2.pointermax;
thisbeforeret = op2.thisbeforeret;
nonfloatgroup = op2.nonfloatgroup;
populateResolver();
}
ParamListStandard::~ParamListStandard(void)
{
for(int4 i=0;i<resolverMap.size();++i) {
ParamEntryResolver *resolver = resolverMap[i];
if (resolver != (ParamEntryResolver *)0)
delete resolver;
}
}
/// Find the (first) entry containing the given memory range
/// \param loc is the starting address of the range
/// \param size is the number of bytes in the range
/// \return the pointer to the matching ParamEntry or null if no match exists
const ParamEntry *ParamListStandard::findEntry(const Address &loc,int4 size) const
{
int4 index = loc.getSpace()->getIndex();
if (index >= resolverMap.size())
return (const ParamEntry *)0;
ParamEntryResolver *resolver = resolverMap[index];
if (resolver == (ParamEntryResolver *)0)
return (const ParamEntry *)0;
pair<ParamEntryResolver::const_iterator,ParamEntryResolver::const_iterator> res;
res = resolver->find(loc.getOffset());
while(res.first != res.second) {
const ParamEntry *testEntry = (*res.first).getParamEntry();
++res.first;
if (testEntry->getMinSize() > size) continue;
if (testEntry->justifiedContain(loc,size)==0) // Make sure the range is properly justified in entry
return testEntry;
}
return (const ParamEntry *)0;
}
int4 ParamListStandard::characterizeAsParam(const Address &loc,int4 size) const
{
int4 index = loc.getSpace()->getIndex();
if (index >= resolverMap.size())
return 0;
ParamEntryResolver *resolver = resolverMap[index];
if (resolver == (ParamEntryResolver *)0)
return 0;
pair<ParamEntryResolver::const_iterator,ParamEntryResolver::const_iterator> iterpair;
iterpair = resolver->find(loc.getOffset());
int4 res = 0;
while(iterpair.first != iterpair.second) {
const ParamEntry *testEntry = (*iterpair.first).getParamEntry();
if (testEntry->getMinSize() <= size && testEntry->justifiedContain(loc, size)==0)
return 1;
if (testEntry->containedBy(loc, size))
res = 2;
++iterpair.first;
}
if (res != 2 && iterpair.first != resolver->end()) {
iterpair.second = resolver->find_end(loc.getOffset() + (size-1));
while(iterpair.first != iterpair.second) {
const ParamEntry *testEntry = (*iterpair.first).getParamEntry();
if (testEntry->containedBy(loc, size)) {
res = 2;
break;
}
++iterpair.first;
}
}
return res;
}
/// Given the next data-type and the status of previously allocated slots,
/// select the storage location for the parameter. The status array is
/// indexed by \e group: a positive value indicates how many \e slots have been allocated
/// from that group, and a -1 indicates the group/resource is fully consumed.
/// \param tp is the data-type of the next parameter
/// \param status is an array marking how many \e slots have already been consumed in a group
/// \return the newly assigned address for the parameter
Address ParamListStandard::assignAddress(const Datatype *tp,vector<int4> &status) const
{
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
const ParamEntry &curEntry( *iter );
int4 grp = curEntry.getGroup();
if (status[grp]<0) continue;
if ((curEntry.getType() != TYPE_UNKNOWN)&&
tp->getMetatype() != curEntry.getType())
continue; // Wrong type
Address res = curEntry.getAddrBySlot(status[grp],tp->getSize());
if (res.isInvalid()) continue; // If -tp- doesn't fit an invalid address is returned
if (curEntry.isExclusion()) {
int4 maxgrp = grp + curEntry.getGroupSize();
for(int4 j=grp;j<maxgrp;++j) // For an exclusion entry
status[j] = -1; // some number of groups are taken up
}
return res;
}
return Address(); // Return invalid address to indicated we could not assign anything
}
void ParamListStandard::assignMap(const vector<Datatype *> &proto,bool isinput,TypeFactory &typefactory,
vector<ParameterPieces> &res) const
{
vector<int4> status(numgroup,0);
if (isinput) {
if (res.size()==2) { // Check for hidden parameters defined by the output list
res.back().addr = assignAddress(res.back().type,status); // Reserve first param for hidden ret value
res.back().flags |= Varnode::hiddenretparm;
if (res.back().addr.isInvalid())
throw ParamUnassignedError("Cannot assign parameter address for " + res.back().type->getName());
}
for(int4 i=1;i<proto.size();++i) {
res.push_back(ParameterPieces());
if ((pointermax != 0)&&(proto[i]->getSize() > pointermax)) { // Datatype is too big
// Assume datatype is stored elsewhere and only the pointer is passed
AddrSpace *spc = spacebase;
if (spc == (AddrSpace *)0)
spc = typefactory.getArch()->getDefaultSpace();
int4 pointersize = spc->getAddrSize();
int4 wordsize = spc->getWordSize();
Datatype *pointertp = typefactory.getTypePointerAbsolute(pointersize,proto[i],wordsize);
res.back().addr = assignAddress(pointertp,status);
res.back().type = pointertp;
res.back().flags = Varnode::indirectstorage;
}
else
res.back().addr = assignAddress(proto[i],status);
if (res.back().addr.isInvalid())
throw ParamUnassignedError("Cannot assign parameter address for " + proto[i]->getName());
res.back().type = proto[i];
res.back().flags = 0;
}
}
else {
res.push_back(ParameterPieces());
if (proto[0]->getMetatype() != TYPE_VOID) {
res.back().addr = assignAddress(proto[0],status);
if (res.back().addr.isInvalid())
throw ParamUnassignedError("Cannot assign parameter address for " + proto[0]->getName());
}
res.back().type = proto[0];
res.back().flags = 0;
}
}
/// Given a set of \b trials (putative Varnode parameters) as ParamTrial objects,
/// associate each trial with a model ParamEntry within \b this list. Trials for
/// for which there are no matching entries are marked as unused. Any holes
/// in the resource list are filled with \e unreferenced trials. The trial list is sorted.
/// \param active is the set of \b trials to map and organize
void ParamListStandard::buildTrialMap(ParamActive *active) const
{
vector<const ParamEntry *> hitlist; // List of groups for which we have a representative
bool seenfloattrial = false;
bool seeninttrial = false;
for(int4 i=0;i<active->getNumTrials();++i) {
ParamTrial ¶mtrial(active->getTrial(i));
const ParamEntry *entrySlot = findEntry(paramtrial.getAddress(),paramtrial.getSize());
// Note: if a trial is "definitely not used" but there is a matching entry,
// we still include it in the map
if (entrySlot == (const ParamEntry *)0)
paramtrial.markNoUse();
else {
paramtrial.setEntry( entrySlot, 0 ); // Keep track of entry recovered for this trial
if (entrySlot->getType() == TYPE_FLOAT)
seenfloattrial = true;
else
seeninttrial = true;
// Make sure we list that the entries group is marked
int4 grp = entrySlot->getGroup();
while(hitlist.size() <= grp)
hitlist.push_back((const ParamEntry *)0);
const ParamEntry *lastentry = hitlist[grp];
if (lastentry == (const ParamEntry *)0)
hitlist[grp] = entrySlot; // This is the first hit for this group
}
}
// Created unreferenced (unref) ParamTrial for any group that we don't have a representive for
// if that group occurs before one where we do have a representative
for(int4 i=0;i<hitlist.size();++i) {
const ParamEntry *curentry = hitlist[i];
if (curentry == (const ParamEntry *)0) {
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
curentry = &(*iter);
if (curentry->getGroup() == i) break; // Find first entry of the missing group
}
if ((!seenfloattrial)&&(curentry->getType()==TYPE_FLOAT))
continue; // Don't fill in unreferenced floats if we haven't seen any floats
if ((!seeninttrial)&&(curentry->getType()!=TYPE_FLOAT))
continue; // Don't fill in unreferenced int if all we have seen is floats
int4 sz = curentry->isExclusion() ? curentry->getSize() : curentry->getAlign();
int4 nextslot = 0;
Address addr = curentry->getAddrBySlot(nextslot,sz);
int4 trialpos = active->getNumTrials();
active->registerTrial(addr,sz);
ParamTrial ¶mtrial(active->getTrial(trialpos));
paramtrial.markUnref();
paramtrial.setEntry(curentry,0);
}
else if (!curentry->isExclusion()) {
// For non-exclusion groups, we need to create a secondary hitlist to find holes within the group
vector<int4> slotlist;
for(int4 j=0;j<active->getNumTrials();++j) {
ParamTrial ¶mtrial(active->getTrial(j));
if (paramtrial.getEntry() != curentry) continue;
int4 slot = curentry->getSlot(paramtrial.getAddress(),0) - curentry->getGroup();
int4 endslot = curentry->getSlot(paramtrial.getAddress(),paramtrial.getSize()-1) - curentry->getGroup();
if (endslot < slot) { // With reverse stacks, the ending address may be in an earlier slot
int4 tmp = slot;
slot = endslot;
endslot = tmp;
}
while(slotlist.size() <= endslot)
slotlist.push_back(0);
while(slot<=endslot) {
slotlist[slot] = 1;
slot += 1;
}
}
for(int4 j=0;j<slotlist.size();++j) {
if (slotlist[j] == 0) {
int4 nextslot = j; // Make copy of j, so that getAddrBySlot can change it
Address addr = curentry->getAddrBySlot(nextslot,curentry->getAlign());
int4 trialpos = active->getNumTrials();
active->registerTrial(addr,curentry->getAlign());
ParamTrial ¶mtrial(active->getTrial(trialpos));
paramtrial.markUnref();
paramtrial.setEntry(curentry,0);
}
}
}
}
active->sortTrials();
}
/// \brief Calculate the range of floating-point entries within a given set of parameter \e trials
///
/// The trials must already be mapped, which should put floating-point entries first.
/// This method calculates the range of floating-point entries and the range of general purpose
/// entries and passes them back.
/// \param active is the given set of parameter trials
/// \param floatstart will pass back the index of the first floating-point trial
/// \param floatstop will pass back the index (+1) of the last floating-point trial
/// \param start will pass back the index of the first general purpose trial
/// \param stop will pass back the index (+1) of the last general purpose trial
void ParamListStandard::separateFloat(ParamActive *active,int4 &floatstart,int4 &floatstop,int4 &start,int4 &stop) const
{
int4 numtrials = active->getNumTrials();
int4 i=0;
for(;i<numtrials;++i) {
ParamTrial &curtrial(active->getTrial(i));
if (curtrial.getEntry()==(const ParamEntry *)0) continue;
if (curtrial.getEntry()->getType()!=TYPE_FLOAT) break;
}
floatstart = 0;
floatstop = i;
start = i;
stop = numtrials;
}
/// \brief Enforce exclusion rules for the given set of parameter trials
///
/// If there are more than one active trials in a single group,
/// and if that group is an exclusion group, mark all but the first trial to \e inactive.
/// \param active is the set of trials
void ParamListStandard::forceExclusionGroup(ParamActive *active) const
{
int4 curupper = -1;
bool exclusion = false;
int4 numtrials = active->getNumTrials();
for(int4 i=0;i<numtrials;++i) {
ParamTrial &curtrial(active->getTrial(i));
if (curtrial.isActive()) {
int4 grp = curtrial.getEntry()->getGroup();
exclusion = curtrial.getEntry()->isExclusion();
if (grp <= curupper) { // If curtrial's group falls below highest group where we have seen an active
if (exclusion)
curtrial.markInactive(); // mark inactive if it is an exclusion group
}
else
curupper = grp + curtrial.getEntry()->getGroupSize() - 1; // This entry covers some number of groups
}
}
}
/// \brief Mark every trial above the first "definitely not used" as \e inactive.
///
/// Inspection and marking only occurs within an indicated range of trials,
/// allowing floating-point and general purpose resources to be treated separately.
/// \param active is the set of trials, which must already be ordered
/// \param start is the index of the first trial in the range to consider
/// \param stop is the index (+1) of the last trial in the range to consider
void ParamListStandard::forceNoUse(ParamActive *active, int4 start, int4 stop) const
{
bool seendefnouse = false;
int4 curgroup = -1;
bool exclusion = false;
bool alldefnouse = false;
for (int4 i = start; i < stop; ++i) {
ParamTrial &curtrial(active->getTrial(i));
if (curtrial.getEntry() == (const ParamEntry *) 0)
continue; // Already marked as not used
int4 grp = curtrial.getEntry()->getGroup();
exclusion = curtrial.getEntry()->isExclusion();
if ((grp <= curgroup) && exclusion) {// If in the same exclusion group
if (!curtrial.isDefinitelyNotUsed()) // A single element that might be used
alldefnouse = false; // means that the whole group might be used
}
else { // First trial in a new group (or next element in same non-exclusion group)
if (alldefnouse) // If all in the last group were defnotused
seendefnouse = true;// then force everything afterword to be defnotused
alldefnouse = curtrial.isDefinitelyNotUsed();
curgroup = grp + curtrial.getEntry()->getGroupSize() - 1;
}
if (seendefnouse)
curtrial.markInactive();
}
}
/// \brief Enforce rules about chains of inactive slots.
///
/// If there is a chain of slots whose length is greater than \b maxchain,
/// where all trials are \e inactive, mark trials in any later slot as \e inactive.
/// Mark any \e inactive trials before this (that aren't in a maximal chain)
/// as active. Inspection and marking is restricted to a given range of trials
/// to facilitate separate analysis of floating-point and general-purpose resources.
/// \param active is the set of trials, which must be sorted
/// \param maxchain is the maximum number of \e inactive trials to allow in a chain
/// \param start is the first index in the range of trials to consider
/// \param stop is the last index (+1) in the range of trials to consider
void ParamListStandard::forceInactiveChain(ParamActive *active,int4 maxchain,int4 start,int4 stop) const
{
bool seenchain = false;
int4 chainlength = 0;
int4 max = -1;
for(int4 i=start;i<stop;++i) {
ParamTrial &trial(active->getTrial(i));
if (trial.getEntry() == (const ParamEntry *)0) continue; // Already know not used
if (!trial.isActive()) {
if (trial.isUnref()&&active->isRecoverSubcall()) {
// If there is no reference to the trial within the function, the only real possibility
// is that a register is an input to the calling function and it is being reused (immediately)
// to pass the input into the called function. This really can't happen on the stack because
// the stack relative caller offset and callee offset are different
if (trial.getAddress().getSpace()->getType() == IPTR_SPACEBASE) // So if the parameter is on the stack
seenchain = true; // Mark that we have already seen an inactive chain
}
if (i==start) {
if (trial.getEntry()->getType() == TYPE_FLOAT)
chainlength += (active->getTrial(0).slotGroup()+1);
else
chainlength += (trial.slotGroup() - nonfloatgroup + 1);
}
else
chainlength += trial.slotGroup() - active->getTrial(i-1).slotGroup();
if (chainlength > maxchain)
seenchain = true;
}
else {
chainlength = 0;
if (!seenchain)
max = i;
}
if (seenchain)
trial.markInactive();
}
for(int4 i=start;i<=max;++i) { // Across the range of active trials, fill in "holes" of inactive trials
ParamTrial &trial(active->getTrial(i));
if (trial.isDefinitelyNotUsed()) continue;
if (!trial.isActive())
trial.markActive();
}
}
void ParamListStandard::calcDelay(void)
{
maxdelay = 0;
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
int4 delay = (*iter).getSpace()->getDelay();
if (delay > maxdelay)
maxdelay = delay;
}
}
/// Enter all the ParamEntry objects into an interval map (based on address space)
void ParamListStandard::populateResolver(void)
{
int4 maxid = -1;
list<ParamEntry>::iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
int4 id = (*iter).getSpace()->getIndex();
if (id > maxid)
maxid = id;
}
resolverMap.resize(maxid+1, (ParamEntryResolver *)0);
int4 position = 0;
for(iter=entry.begin();iter!=entry.end();++iter) {
ParamEntry *paramEntry = &(*iter);
int4 spaceId = paramEntry->getSpace()->getIndex();
ParamEntryResolver *resolver = resolverMap[spaceId];
if (resolver == (ParamEntryResolver *)0) {
resolver = new ParamEntryResolver();
resolverMap[spaceId] = resolver;
}
uintb first = paramEntry->getBase();
uintb last = first + (paramEntry->getSize() - 1);
ParamEntryResolver::inittype initData(position,paramEntry);
position += 1;
resolver->insert(initData,first,last);
}
}
void ParamListStandard::fillinMap(ParamActive *active) const
{
if (active->getNumTrials() == 0) return; // No trials to check
buildTrialMap(active); // Associate varnodes with sorted list of parameter locations
forceExclusionGroup(active);
int4 floatstart,floatstop,start,stop;
separateFloat(active,floatstart,floatstop,start,stop);
forceNoUse(active,floatstart,floatstop);
forceNoUse(active,start,stop); // Definitely not used -- overrides active
forceInactiveChain(active,2,floatstart,floatstop); // Chains of inactivity override later actives
forceInactiveChain(active,2,start,stop);
// Mark every active trial as used
for(int4 i=0;i<active->getNumTrials();++i) {
ParamTrial ¶mtrial(active->getTrial(i));
if (paramtrial.isActive())
paramtrial.markUsed();
}
}
bool ParamListStandard::checkJoin(const Address &hiaddr,int4 hisize,const Address &loaddr,int4 losize) const
{
const ParamEntry *entryHi = findEntry(hiaddr,hisize);
if (entryHi == (const ParamEntry *)0) return false;
const ParamEntry *entryLo = findEntry(loaddr,losize);
if (entryLo == (const ParamEntry *)0) return false;
if (entryHi->getGroup() == entryLo->getGroup()) {
if (entryHi->isExclusion()||entryLo->isExclusion()) return false;
if (!hiaddr.isContiguous(hisize,loaddr,losize)) return false;
if (((hiaddr.getOffset() - entryHi->getBase()) % entryHi->getAlign()) != 0) return false;
if (((loaddr.getOffset() - entryLo->getBase()) % entryLo->getAlign()) != 0) return false;
return true;
}
else {
int4 sizesum = hisize + losize;
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
if ((*iter).getSize() < sizesum) continue;
if ((*iter).justifiedContain(loaddr,losize)!=0) continue;
if ((*iter).justifiedContain(hiaddr,hisize)!=losize) continue;
return true;
}
}
return false;
}
bool ParamListStandard::checkSplit(const Address &loc,int4 size,int4 splitpoint) const
{
Address loc2 = loc + splitpoint;
int4 size2 = size - splitpoint;
const ParamEntry *entryNum = findEntry(loc,splitpoint);
if (entryNum == (const ParamEntry *)0) return false;
entryNum = findEntry(loc2,size2);
if (entryNum == (const ParamEntry *)0) return false;
return true;
}
bool ParamListStandard::possibleParam(const Address &loc,int4 size) const
{
return ((const ParamEntry *)0 != findEntry(loc,size));
}
bool ParamListStandard::possibleParamWithSlot(const Address &loc,int4 size,int4 &slot,int4 &slotsize) const
{
const ParamEntry *entryNum = findEntry(loc,size);
if (entryNum == (const ParamEntry *)0) return false;
slot = entryNum->getSlot(loc,0);
if (entryNum->isExclusion()) {
slotsize = entryNum->getGroupSize();
}
else {
slotsize = ((size-1) / entryNum->getAlign()) + 1;
}
return true;
}
bool ParamListStandard::getBiggestContainedParam(const Address &loc,int4 size,VarnodeData &res) const
{
int4 index = loc.getSpace()->getIndex();
if (index >= resolverMap.size())
return false;
ParamEntryResolver *resolver = resolverMap[index];
if (resolver == (ParamEntryResolver *)0)
return false;
const ParamEntry *maxEntry = (const ParamEntry *)0;
ParamEntryResolver::const_iterator iter = resolver->find_begin(loc.getOffset());
ParamEntryResolver::const_iterator enditer = resolver->find_end(loc.getOffset() + (size-1));
while(iter != enditer) {
const ParamEntry *testEntry = (*iter).getParamEntry();
++iter;
if (testEntry->containedBy(loc, size)) {
if (maxEntry == (const ParamEntry *)0)
maxEntry = testEntry;
else if (testEntry->getSize() > maxEntry->getSize())
maxEntry = testEntry;
}
}
if (!maxEntry->isExclusion())
return false;
if (maxEntry != (const ParamEntry *)0) {
res.space = maxEntry->getSpace();
res.offset = maxEntry->getBase();
res.size = maxEntry->getSize();
return true;
}
return false;
}
bool ParamListStandard::unjustifiedContainer(const Address &loc,int4 size,VarnodeData &res) const
{
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
if ((*iter).getMinSize() > size) continue;
int4 just = (*iter).justifiedContain(loc,size);
if (just < 0) continue;
if (just == 0) return false;
(*iter).getContainer(loc,size,res);
return true;
}
return false;
}
OpCode ParamListStandard::assumedExtension(const Address &addr,int4 size,VarnodeData &res) const
{
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
if ((*iter).getMinSize() > size) continue;