forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fspec.cc
5870 lines (5296 loc) · 201 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"
namespace ghidra {
AttributeId ATTRIB_CUSTOM = AttributeId("custom",114);
AttributeId ATTRIB_DOTDOTDOT = AttributeId("dotdotdot",115);
AttributeId ATTRIB_EXTENSION = AttributeId("extension",116);
AttributeId ATTRIB_HASTHIS = AttributeId("hasthis",117);
AttributeId ATTRIB_INLINE = AttributeId("inline",118);
AttributeId ATTRIB_KILLEDBYCALL = AttributeId("killedbycall",119);
AttributeId ATTRIB_MAXSIZE = AttributeId("maxsize",120);
AttributeId ATTRIB_MINSIZE = AttributeId("minsize",121);
AttributeId ATTRIB_MODELLOCK = AttributeId("modellock",122);
AttributeId ATTRIB_NORETURN = AttributeId("noreturn",123);
AttributeId ATTRIB_POINTERMAX = AttributeId("pointermax",124);
AttributeId ATTRIB_SEPARATEFLOAT = AttributeId("separatefloat",125);
AttributeId ATTRIB_STACKSHIFT = AttributeId("stackshift",126);
AttributeId ATTRIB_STRATEGY = AttributeId("strategy",127);
AttributeId ATTRIB_THISBEFORERETPOINTER = AttributeId("thisbeforeretpointer",128);
AttributeId ATTRIB_VOIDLOCK = AttributeId("voidlock",129);
ElementId ELEM_GROUP = ElementId("group",160);
ElementId ELEM_INTERNALLIST = ElementId("internallist",161);
ElementId ELEM_KILLEDBYCALL = ElementId("killedbycall",162);
ElementId ELEM_LIKELYTRASH = ElementId("likelytrash",163);
ElementId ELEM_LOCALRANGE = ElementId("localrange",164);
ElementId ELEM_MODEL = ElementId("model",165);
ElementId ELEM_PARAM = ElementId("param",166);
ElementId ELEM_PARAMRANGE = ElementId("paramrange",167);
ElementId ELEM_PENTRY = ElementId("pentry",168);
ElementId ELEM_PROTOTYPE = ElementId("prototype",169);
ElementId ELEM_RESOLVEPROTOTYPE = ElementId("resolveprototype",170);
ElementId ELEM_RETPARAM = ElementId("retparam",171);
ElementId ELEM_RETURNSYM = ElementId("returnsym",172);
ElementId ELEM_UNAFFECTED = ElementId("unaffected",173);
ElementId ELEM_INTERNAL_STORAGE = ElementId("internal_storage",286);
/// \brief Find a ParamEntry matching the given storage Varnode
///
/// Search through the list backward.
/// \param entryList is the list of ParamEntry to search through
/// \param vn is the storage to search for
/// \return the matching ParamEntry or null
const ParamEntry *ParamEntry::findEntryByStorage(const list<ParamEntry> &entryList,const VarnodeData &vn)
{
list<ParamEntry>::const_reverse_iterator iter = entryList.rbegin();
for(;iter!=entryList.rend();++iter) {
const ParamEntry &entry(*iter);
if (entry.spaceid == vn.space && entry.addressbase == vn.offset && entry.size == vn.size) {
return &entry;
}
}
return (const ParamEntry *)0;
}
/// Check previous ParamEntry, if it exists, and compare storage class.
/// If it is different, this is the first, and its flag gets set.
/// \param curList is the list of previous ParamEntry
void ParamEntry::resolveFirst(list<ParamEntry> &curList)
{
list<ParamEntry>::const_iterator iter = curList.end();
--iter;
if (iter == curList.begin()) {
flags |= first_storage;
return;
}
--iter;
if (type != (*iter).type) {
flags |= first_storage;
}
}
/// If the ParamEntry is initialized with a \e join address, cache the join record and
/// adjust the group and groupsize based on the ParamEntrys being overlapped
/// \param curList is the current list of ParamEntry
void ParamEntry::resolveJoin(list<ParamEntry> &curList)
{
if (spaceid->getType() != IPTR_JOIN) {
joinrec = (JoinRecord *)0;
return;
}
joinrec = spaceid->getManager()->findJoin(addressbase);
groupSet.clear();
for(int4 i=0;i<joinrec->numPieces();++i) {
const ParamEntry *entry = findEntryByStorage(curList, joinrec->getPiece(i));
if (entry != (const ParamEntry *)0) {
groupSet.insert(groupSet.end(),entry->groupSet.begin(),entry->groupSet.end());
// For output <pentry>, if the most signifigant part overlaps with an earlier <pentry>
// the least signifigant part is marked for extra checks, and vice versa.
flags |= (i==0) ? extracheck_low : extracheck_high;
}
}
if (groupSet.empty())
throw LowlevelError("<pentry> join must overlap at least one previous entry");
sort(groupSet.begin(),groupSet.end());
flags |= overlapping;
}
/// Search for overlaps of \b this with any previous entry. If an overlap is discovered,
/// verify the form is correct for the different ParamEntry to share \e group slots and
/// reassign \b this group.
/// \param curList is the list of previous entries
void ParamEntry::resolveOverlap(list<ParamEntry> &curList)
{
if (joinrec != (JoinRecord *)0)
return; // Overlaps with join records dealt with in resolveJoin
vector<int4> overlapSet;
list<ParamEntry>::const_iterator iter,enditer;
Address addr(spaceid,addressbase);
enditer = curList.end();
--enditer; // The last entry is \b this ParamEntry
for(iter=curList.begin();iter!=enditer;++iter) {
const ParamEntry &entry(*iter);
if (!entry.intersects(addr, size)) continue;
if (contains(entry)) { // If this contains the intersecting entry
if (entry.isOverlap()) continue; // Don't count resources (already counted overlapped entry)
overlapSet.insert(overlapSet.end(),entry.groupSet.begin(),entry.groupSet.end());
// For output <pentry>, if the most signifigant part overlaps with an earlier <pentry>
// the least signifigant part is marked for extra checks, and vice versa.
if (addressbase == entry.addressbase)
flags |= spaceid->isBigEndian() ? extracheck_low : extracheck_high;
else
flags |= spaceid->isBigEndian() ? extracheck_high : extracheck_low;
}
else
throw LowlevelError("Illegal overlap of <pentry> in compiler spec");
}
if (overlapSet.empty()) return; // No overlaps
sort(overlapSet.begin(),overlapSet.end());
groupSet = overlapSet;
flags |= overlapping;
}
/// \param op2 is the other entry to compare
/// \return \b true if the group sets associated with each ParamEntry intersect at all
bool ParamEntry::groupOverlap(const ParamEntry &op2) const
{
int4 i = 0;
int4 j = 0;
int4 valThis = groupSet[i];
int4 valOther = op2.groupSet[j];
while(valThis != valOther) {
if (valThis < valOther) {
i += 1;
if (i >= groupSet.size()) return false;
valThis = groupSet[i];
}
else {
j += 1;
if (j >= op2.groupSet.size()) return false;
valOther = op2.groupSet[j];
}
}
return true;
}
/// This entry must properly contain the other memory range, and
/// the entry properties must be compatible. A \e join ParamEntry can
/// subsume another \e join ParamEntry, but we expect the addressbase to be identical.
/// \param op2 is the given entry to compare with \b this
/// \return \b true if the given entry is subsumed
bool ParamEntry::subsumesDefinition(const ParamEntry &op2) const
{
if ((type!=TYPECLASS_GENERAL)&&(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;
}
/// We assume a \e join ParamEntry cannot be contained by a single contiguous memory range.
/// \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);
}
/// If \b this a a \e join, each piece is tested for intersection.
/// Otherwise, \b this, considered as a single memory, is tested for intersection.
/// \param addr is the starting address of the given memory range to test against
/// \param sz is the number of bytes in the given memory range
/// \return \b true if there is any kind of intersection
bool ParamEntry::intersects(const Address &addr,int4 sz) const
{
uintb rangeend;
if (joinrec != (JoinRecord *)0) {
rangeend = addr.getOffset() + sz - 1;
for(int4 i=0;i<joinrec->numPieces();++i) {
const VarnodeData &vdata( joinrec->getPiece(i) );
if (addr.getSpace() != vdata.space) continue;
uintb vdataend = vdata.offset + vdata.size - 1;
if (addr.getOffset() < vdata.offset && rangeend < vdataend)
continue;
if (addr.getOffset() > vdata.offset && rangeend > vdataend)
continue;
return true;
}
}
if (spaceid != addr.getSpace()) return false;
rangeend = addr.getOffset() + sz - 1;
uintb thisend = addressbase + size - 1;
if (addr.getOffset() < addressbase && rangeend < thisend)
return false;
if (addr.getOffset() > addressbase && rangeend > thisend)
return false;
return true;
}
/// 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;
}
/// Test that \b this, as one or more memory ranges, contains the other ParamEntry's memory range.
/// A \e join ParamEntry cannot be contained by another entry, but it can contain an entry in one
/// of its pieces.
/// \param op2 is the given ParamEntry to test for containment
/// \return \b true if the given ParamEntry is contained
bool ParamEntry::contains(const ParamEntry &op2) const
{
if (op2.joinrec != (JoinRecord *)0) return false; // Assume a join entry cannot be contained
if (joinrec == (JoinRecord *)0) {
Address addr(spaceid,addressbase);
return op2.containedBy(addr, size);
}
for(int4 i=0;i<joinrec->numPieces();++i) {
const VarnodeData &vdata(joinrec->getPiece(i));
Address addr = vdata.getAddr();
if (op2.containedBy(addr,vdata.size))
return true;
}
return false;
}
/// \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 = groupSet[0];
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 = groupSet.back();
}
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
/// \param typeAlign is the required byte alignment for the parameter
/// \return the address of the new parameter (or an invalid address)
Address ParamEntry::getAddrBySlot(int4 &slotnum,int4 sz,int4 typeAlign) 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 {
if (typeAlign > alignment) {
int4 tmp = (slotnum * alignment) % typeAlign;
if (tmp != 0)
slotnum += (typeAlign - tmp) / alignment; // Waste slots to achieve typeAlign
}
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 Decode a \<pentry> element into \b this object
///
/// \param decoder is the stream decoder
/// \param normalstack is \b true if the parameters should be allocated from the front of the range
/// \param grouped is \b true if \b this will be grouped with other entries
/// \param curList is the list of ParamEntry defined up to this point
void ParamEntry::decode(Decoder &decoder,bool normalstack,bool grouped,list<ParamEntry> &curList)
{
flags = 0;
type = TYPECLASS_GENERAL;
size = minsize = -1; // Must be filled in
alignment = 0; // default
numslots = 1;
uint4 elemId = decoder.openElement(ELEM_PENTRY);
for(;;) {
uint4 attribId = decoder.getNextAttributeId();
if (attribId == 0) break;
if (attribId == ATTRIB_MINSIZE) {
minsize = decoder.readSignedInteger();
}
else if (attribId == ATTRIB_SIZE) { // old style
alignment = decoder.readSignedInteger();
}
else if (attribId == ATTRIB_ALIGN) { // new style
alignment = decoder.readSignedInteger();
}
else if (attribId == ATTRIB_MAXSIZE) {
size = decoder.readSignedInteger();
}
else if (attribId == ATTRIB_STORAGE || attribId == ATTRIB_METATYPE)
type = string2typeclass(decoder.readString());
else if (attribId == ATTRIB_EXTENSION) {
flags &= ~((uint4)(smallsize_zext | smallsize_sext | smallsize_inttype));
string ext = decoder.readString();
if (ext == "sign")
flags |= smallsize_sext;
else if (ext == "zero")
flags |= smallsize_zext;
else if (ext == "inttype")
flags |= smallsize_inttype;
else if (ext == "float")
flags |= smallsize_floatext;
else if (ext != "none")
throw LowlevelError("Bad extension attribute");
}
else
throw LowlevelError("Unknown <pentry> attribute");
}
if ((size==-1)||(minsize==-1))
throw LowlevelError("ParamEntry not fully specified");
if (alignment == size)
alignment = 0;
Address addr;
addr = Address::decode(decoder);
decoder.closeElement(elemId);
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");
}
}
if (grouped)
flags |= is_grouped;
resolveFirst(curList);
resolveJoin(curList);
resolveOverlap(curList);
}
/// Entries within a group must be distinguishable by size or by type.
/// Throw an exception if the entries aren't distinguishable
/// \param entry1 is the first ParamEntry to compare
/// \param entry2 is the second ParamEntry to compare
void ParamEntry::orderWithinGroup(const ParamEntry &entry1,const ParamEntry &entry2)
{
if (entry2.minsize > entry1.size || entry1.minsize > entry2.size)
return;
if (entry1.type != entry2.type) {
if (entry1.type == TYPECLASS_GENERAL) {
throw LowlevelError("<pentry> tags with a specific type must come before the general type");
}
return;
}
throw LowlevelError("<pentry> tags within a group must be distinguished by size or type");
}
ParamListStandard::ParamListStandard(const ParamListStandard &op2)
{
numgroup = op2.numgroup;
entry = op2.entry;
spacebase = op2.spacebase;
maxdelay = op2.maxdelay;
thisbeforeret = op2.thisbeforeret;
resourceStart = op2.resourceStart;
for(list<ModelRule>::const_iterator iter=op2.modelRules.begin();iter!=op2.modelRules.end();++iter) {
modelRules.emplace_back(*iter,&op2);
}
populateResolver();
}
ParamListStandard::~ParamListStandard(void)
{
for(int4 i=0;i<resolverMap.size();++i) {
ParamEntryResolver *resolver = resolverMap[i];
if (resolver != (ParamEntryResolver *)0)
delete resolver;
}
}
/// The entry must have a unique group.
/// If no matching entry is found, the \b end iterator is returned.
/// \param type is the storage class
/// \return the first matching iterator
list<ParamEntry>::const_iterator ParamListStandard::getFirstIter(type_class type) const
{
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
const ParamEntry &curEntry( *iter );
if (curEntry.getType() == type && curEntry.getAllGroups().size() == 1)
return iter;
}
return iter;
}
/// If the stack entry is not present, null is returned
/// \return the stack entry or null
const ParamEntry *ParamListStandard::getStackEntry(void) const
{
list<ParamEntry>::const_iterator iter = entry.end();
if (iter != entry.begin()) {
--iter; // Stack entry necessarily must be the last entry
const ParamEntry &curEntry( *iter );
if (!curEntry.isExclusion() && curEntry.getSpace()->getType() == IPTR_SPACEBASE) {
return &(*iter);
}
}
return (const ParamEntry *)0;
}
/// 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
/// \param just is \b true if the search enforces a justified match
/// \return the pointer to the matching ParamEntry or null if no match exists
const ParamEntry *ParamListStandard::findEntry(const Address &loc,int4 size,bool just) 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 (!just || 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 ParamEntry::no_containment;
ParamEntryResolver *resolver = resolverMap[index];
if (resolver == (ParamEntryResolver *)0)
return ParamEntry::no_containment;
pair<ParamEntryResolver::const_iterator,ParamEntryResolver::const_iterator> iterpair;
iterpair = resolver->find(loc.getOffset());
bool resContains = false;
bool resContainedBy = false;
while(iterpair.first != iterpair.second) {
const ParamEntry *testEntry = (*iterpair.first).getParamEntry();
int4 off = testEntry->justifiedContain(loc, size);
if (off == 0)
return ParamEntry::contains_justified;
else if (off > 0)
resContains = true;
if (testEntry->isExclusion() && testEntry->containedBy(loc, size))
resContainedBy = true;
++iterpair.first;
}
if (resContains) return ParamEntry::contains_unjustified;
if (resContainedBy) return ParamEntry::contained_by;
if (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->isExclusion() && testEntry->containedBy(loc, size)) {
return ParamEntry::contained_by;
}
++iterpair.first;
}
}
return ParamEntry::no_containment;
}
/// \brief Assign storage for given parameter class, using the fallback assignment algorithm
///
/// Given a resource list, a 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.
/// If an Address can be assigned to the parameter, it and other details are passed back in the
/// ParameterPieces object and the \e success code is returned. Otherwise, the \e fail code is returned.
/// \param resource is the resource list to allocate from
/// \param tp is the data-type of the parameter
/// \param matchExact is \b false if TYPECLASS_GENERAL is considered a match for any storage class
/// \param status is an array marking how many \e slots have already been consumed in a group
/// \param param will hold the address of the newly assigned parameter
/// \return either \e success or \e fail
uint4 ParamListStandard::assignAddressFallback(type_class resource,Datatype *tp,bool matchExact,
vector<int4> &status,ParameterPieces ¶m) 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 (resource != curEntry.getType()) {
if (matchExact || curEntry.getType() != TYPECLASS_GENERAL)
continue; // Wrong type
}
param.addr = curEntry.getAddrBySlot(status[grp],tp->getAlignSize(),tp->getAlignment());
if (param.addr.isInvalid()) continue; // If -tp- doesn't fit an invalid address is returned
if (curEntry.isExclusion()) {
const vector<int4> &groupSet(curEntry.getAllGroups());
for(int4 j=0;j<groupSet.size();++j) // For an exclusion entry
status[groupSet[j]] = -1; // some number of groups are taken up
}
param.type = tp;
param.flags = 0;
return AssignAction::success;
}
return AssignAction::fail; // Unable to make an assignment
}
/// \brief Fill in the Address and other details for the given parameter
///
/// Attempt to apply a ModelRule first. If these do not succeed, use the fallback assignment algorithm.
/// \param dt is the data-type assigned to the parameter
/// \param proto is the description of the function prototype
/// \param pos is the position of the parameter to assign (pos=-1 for output, pos >=0 for input)
/// \param tlist is the data-type factory for (possibly) transforming the parameter's data-type
/// \param status is the consumed resource status array
/// \param res is parameter description to be filled in
/// \return the response code
uint4 ParamListStandard::assignAddress(Datatype *dt,const PrototypePieces &proto,int4 pos,TypeFactory &tlist,
vector<int4> &status,ParameterPieces &res) const
{
for(list<ModelRule>::const_iterator iter=modelRules.begin();iter!=modelRules.end();++iter) {
uint4 responseCode = (*iter).assignAddress(dt, proto, pos, tlist, status, res);
if (responseCode != AssignAction::fail)
return responseCode;
}
type_class store = metatype2typeclass(dt->getMetatype());
return assignAddressFallback(store,dt,false,status,res);
}
void ParamListStandard::assignMap(const PrototypePieces &proto,TypeFactory &typefactory,vector<ParameterPieces> &res) const
{
vector<int4> status(numgroup,0);
if (res.size() == 2) { // Check for hidden parameters defined by the output list
Datatype *dt = res.back().type;
type_class store;
if ((res.back().flags & ParameterPieces::hiddenretparm) != 0)
store = TYPECLASS_HIDDENRET;
else
store = metatype2typeclass(dt->getMetatype());
// Reserve first param for hidden return pointer
if (assignAddressFallback(store,dt,false,status,res.back()) == AssignAction::fail)
throw ParamUnassignedError("Cannot assign parameter address for " + res.back().type->getName());
res.back().flags |= ParameterPieces::hiddenretparm;
}
for(int4 i=0;i<proto.intypes.size();++i) {
res.emplace_back();
Datatype *dt = proto.intypes[i];
uint4 responseCode = assignAddress(dt,proto,i,typefactory,status,res.back());
if (responseCode == AssignAction::fail || responseCode == AssignAction::no_assignment)
throw ParamUnassignedError("Cannot assign parameter address for " + dt->getName());
}
}
/// From among the ParamEntrys matching the given \e group, return the one that best matches
/// the given \e metatype attribute. If there are no ParamEntrys in the group, null is returned.
/// \param grp is the given \e group number
/// \param prefType is the preferred \e storage \e class attribute to match
const ParamEntry *ParamListStandard::selectUnreferenceEntry(int4 grp,type_class prefType) const
{
int4 bestScore = -1;
const ParamEntry *bestEntry = (const ParamEntry *)0;
list<ParamEntry>::const_iterator iter;
for(iter=entry.begin();iter!=entry.end();++iter) {
const ParamEntry *curEntry = &(*iter);
if (curEntry->getGroup() != grp) continue;
int4 curScore;
if (curEntry->getType() == prefType)
curScore = 2;
else if (prefType == TYPECLASS_GENERAL)
curScore = 1;
else
curScore = 0;
if (curScore > bestScore) {
bestScore = curScore;
bestEntry = curEntry;
}
}
return bestEntry;
}
/// 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
int4 floatCount = 0;
int4 intCount = 0;
for(int4 i=0;i<active->getNumTrials();++i) {
ParamTrial ¶mtrial(active->getTrial(i));
const ParamEntry *entrySlot = findEntry(paramtrial.getAddress(),paramtrial.getSize(),true);
// 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 (paramtrial.isActive()) {
if (entrySlot->getType() == TYPECLASS_FLOAT)
floatCount += 1;
else
intCount += 1;
}
// 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 representative 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) {
curentry = selectUnreferenceEntry(i, (floatCount > intCount) ? TYPECLASS_FLOAT : TYPECLASS_GENERAL);
if (curentry == (const ParamEntry *)0)
continue;
int4 sz = curentry->isExclusion() ? curentry->getSize() : curentry->getAlign();
int4 nextslot = 0;
Address addr = curentry->getAddrBySlot(nextslot,sz,1);
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(),1);
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 trials in each resource sections
///
/// The trials must already be mapped, which should put them in group order. The sections
/// split at the groups given by \b resourceStart. We pass back the starting index for
/// each range of trials.
/// \param active is the given set of parameter trials
/// \param trialStart will hold the starting index for each range of trials
void ParamListStandard::separateSections(ParamActive *active,vector<int4> &trialStart) const
{
int4 numtrials = active->getNumTrials();
int4 currentTrial = 0;
int4 nextGroup = resourceStart[1];
int4 nextSection = 2;
trialStart.push_back(currentTrial);
for(;currentTrial<numtrials;++currentTrial) {
ParamTrial &curtrial(active->getTrial(currentTrial));
if (curtrial.getEntry()==(const ParamEntry *)0) continue;
if (curtrial.getEntry()->getGroup() >= nextGroup) {
if (nextSection > resourceStart.size())
throw LowlevelError("Missing next resource start");
nextGroup = resourceStart[nextSection];
nextSection += 1;
trialStart.push_back(currentTrial);
}
}
trialStart.push_back(numtrials);
}
/// \brief Mark all the trials within the indicated groups as \e not \e used, except for one specified index
///
/// Only one trial within an exclusion group can have active use, mark all others as unused.
/// \param active is the set of trials, which must be sorted on group
/// \param activeTrial is the index of the trial whose groups are to be considered active
/// \param trialStart is the index of the first trial to mark
void ParamListStandard::markGroupNoUse(ParamActive *active,int4 activeTrial,int4 trialStart)
{
int4 numTrials = active->getNumTrials();
const ParamEntry *activeEntry = active->getTrial(activeTrial).getEntry();
for(int4 i=trialStart;i<numTrials;++i) { // Mark entries intersecting the group set as definitely not used
if (i == activeTrial) continue; // The trial NOT to mark
ParamTrial &othertrial(active->getTrial(i));
if (othertrial.isDefinitelyNotUsed()) continue;
if (!othertrial.getEntry()->groupOverlap(*activeEntry)) break;
othertrial.markNoUse();
}
}
/// \brief From among multiple \e inactive trials, select the most likely to be active and mark others as not used
///
/// There can be at most one \e inactive trial in an exclusion group for the fill algorithms to work.
/// Score all the trials and pick the one that is the most likely to actually be an active param.
/// Mark all the others as definitely not used.
/// \param active is the sorted set of trials
/// \param group is the group number
/// \param groupStart is the index of the first trial in the group
/// \param prefType is a preferred entry to type to use in scoring
void ParamListStandard::markBestInactive(ParamActive *active,int4 group,int4 groupStart,type_class prefType)
{
int4 numTrials = active->getNumTrials();
int4 bestTrial = -1;
int4 bestScore = -1;
for(int4 i=groupStart;i<numTrials;++i) {
ParamTrial &trial(active->getTrial(i));
if (trial.isDefinitelyNotUsed()) continue;
const ParamEntry *entry = trial.getEntry();
int4 grp = entry->getGroup();
if (grp != group) break;
if (entry->getAllGroups().size() > 1) continue; // Covering multiple slots automatically give low score
int4 score = 0;
if (trial.hasAncestorRealistic()) {
score += 5;
if (trial.hasAncestorSolid())
score += 5;
}
if (entry->getType() == prefType)
score += 1;
if (score > bestScore) {
bestScore = score;
bestTrial = i;
}
}
if (bestTrial >= 0)