-
Notifications
You must be signed in to change notification settings - Fork 49
/
database.cc
3428 lines (3071 loc) · 111 KB
/
database.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 "database.hh"
#include "funcdata.hh"
#include "crc32.hh"
#include <ctype.h>
namespace ghidra {
AttributeId ATTRIB_CAT = AttributeId("cat",61);
AttributeId ATTRIB_FIELD = AttributeId("field",62);
AttributeId ATTRIB_MERGE = AttributeId("merge",63);
AttributeId ATTRIB_SCOPEIDBYNAME = AttributeId("scopeidbyname",64);
AttributeId ATTRIB_VOLATILE = AttributeId("volatile",65);
ElementId ELEM_COLLISION = ElementId("collision",67);
ElementId ELEM_DB = ElementId("db",68);
ElementId ELEM_EQUATESYMBOL = ElementId("equatesymbol",69);
ElementId ELEM_EXTERNREFSYMBOL = ElementId("externrefsymbol",70);
ElementId ELEM_FACETSYMBOL = ElementId("facetsymbol",71);
ElementId ELEM_FUNCTIONSHELL = ElementId("functionshell",72);
ElementId ELEM_HASH = ElementId("hash",73);
ElementId ELEM_HOLE = ElementId("hole",74);
ElementId ELEM_LABELSYM = ElementId("labelsym",75);
ElementId ELEM_MAPSYM = ElementId("mapsym",76);
ElementId ELEM_PARENT = ElementId("parent",77);
ElementId ELEM_PROPERTY_CHANGEPOINT = ElementId("property_changepoint",78);
ElementId ELEM_RANGEEQUALSSYMBOLS = ElementId("rangeequalssymbols",79);
ElementId ELEM_SCOPE = ElementId("scope",80);
ElementId ELEM_SYMBOLLIST = ElementId("symbollist",81);
uint8 Symbol::ID_BASE = 0x4000000000000000L;
/// This SymbolEntry is unintegrated. An address or hash must be provided
/// either directly or via decode().
/// \param sym is the Symbol \b this will be a map for
SymbolEntry::SymbolEntry(Symbol *sym)
: symbol(sym)
{
extraflags = 0;
offset = 0;
hash = 0;
size = -1;
}
/// This is used specifically for \e dynamic Symbol objects, where the storage location
/// is attached to a temporary register or a constant. The main address field (\b addr)
/// is set to \e invalid, and the \b hash becomes the primary location information.
/// \param sym is the underlying Symbol
/// \param exfl are the Varnode flags associated with the storage location
/// \param h is the the hash
/// \param off if the offset into the Symbol for this (piece of) storage
/// \param sz is the size in bytes of this (piece of) storage
/// \param rnglist is the set of code addresses where \b this SymbolEntry represents the Symbol
SymbolEntry::SymbolEntry(Symbol *sym,uint4 exfl,uint8 h,int4 off,int4 sz,const RangeList &rnglist)
{
symbol = sym;
extraflags = exfl;
addr = Address();
hash = h;
offset = off;
size = sz;
uselimit = rnglist;
}
/// Establish the boundary offsets and fill in additional data
/// \param data contains the raw initialization data
/// \param a is the starting offset of the entry
/// \param b is the ending offset of the entry
SymbolEntry::SymbolEntry(const EntryInitData &data,uintb a,uintb b)
{
addr = Address(data.space,a);
size = (b-a)+1;
symbol = data.symbol;
extraflags = data.extraflags;
offset = data.offset;
uselimit = data.uselimit;
}
/// Get data used to sub-sort entries (in a rangemap) at the same address
/// \return the sub-sort object
SymbolEntry::subsorttype SymbolEntry::getSubsort(void) const
{
subsorttype res; // Minimal subsort
if ((symbol->getFlags()&Varnode::addrtied)==0) {
const Range *range = uselimit.getFirstRange();
if (range == (const Range *)0)
throw LowlevelError("Map entry with empty uselimit");
res.useindex = range->getSpace()->getIndex();
res.useoffset = range->getFirst();
}
return res;
}
/// This storage location may only hold the Symbol value for a limited portion of the code.
/// \param usepoint is the given code address to test
/// \return \b true if \b this storage is valid at the given address
bool SymbolEntry::inUse(const Address &usepoint) const
{
if (isAddrTied()) return true; // Valid throughout scope
if (usepoint.isInvalid()) return false;
return uselimit.inRange(usepoint,1);
}
Address SymbolEntry::getFirstUseAddress(void) const
{
const Range *rng = uselimit.getFirstRange();
if (rng == (const Range *)0)
return Address();
return rng->getFirstAddr();
}
/// If the Symbol associated with \b this is type-locked, change the given
/// Varnode's attached data-type to match the Symbol
/// \param vn is the Varnode to modify
/// \return true if the data-type was changed
bool SymbolEntry::updateType(Varnode *vn) const
{
if ((symbol->getFlags()&Varnode::typelock)!=0) { // Type will just get replaced if not locked
Datatype *dt = getSizedType(vn->getAddr(),vn->getSize());
if (dt != (Datatype *)0)
return vn->updateType(dt,true,true);
}
return false;
}
/// Return the data-type that matches the given size and address within \b this storage.
/// NULL is returned if there is no valid sub-type matching the size.
/// \param inaddr is the given address
/// \param sz is the given size (in bytes)
/// \return the matching data-type or NULL
Datatype *SymbolEntry::getSizedType(const Address &inaddr,int4 sz) const
{
int4 off;
if (isDynamic())
off = offset;
else
off = (int4)(inaddr.getOffset() - addr.getOffset()) + offset;
Datatype *cur = symbol->getType();
return symbol->getScope()->getArch()->types->getExactPiece(cur, off, sz);
}
/// Give a contained one-line description of \b this storage, suitable for a debug console
/// \param s is the output stream
void SymbolEntry::printEntry(ostream &s) const
{
s << symbol->getName() << " : ";
if (addr.isInvalid())
s << "<dynamic>";
else {
s << addr.getShortcut();
addr.printRaw(s);
}
s << ':' << dec << (uint4) symbol->getType()->getSize();
s << ' ';
symbol->getType()->printRaw(s);
s << " : ";
uselimit.printBounds(s);
}
/// This writes elements internal to the \<mapsym> element associated with the Symbol.
/// It encodes the address element (or the \<hash> element for dynamic symbols) and
/// a \<rangelist> element associated with the \b uselimit.
/// \param encoder is the stream encoder
void SymbolEntry::encode(Encoder &encoder) const
{
if (isPiece()) return; // Don't save a piece
if (addr.isInvalid()) {
encoder.openElement(ELEM_HASH);
encoder.writeUnsignedInteger(ATTRIB_VAL, hash);
encoder.closeElement(ELEM_HASH);
}
else
addr.encode(encoder);
uselimit.encode(encoder);
}
/// Parse either an \<addr> element for storage information or a \<hash> element
/// if the symbol is dynamic. Then parse the \b uselimit describing the valid
/// range of code addresses.
/// \param decoder is the stream decoder
/// \return the advanced iterator
void SymbolEntry::decode(Decoder &decoder)
{
uint4 elemId = decoder.peekElement();
if (elemId == ELEM_HASH) {
decoder.openElement();
hash = decoder.readUnsignedInteger(ATTRIB_VAL);
addr = Address();
decoder.closeElement(elemId);
}
else {
addr = Address::decode(decoder);
hash = 0;
}
uselimit.decode(decoder);
}
/// Examine the data-type to decide if the Symbol has the special property
/// called \b size_typelock, which indicates the \e size of the Symbol
/// is locked, but the data-type is not locked (and can float)
void Symbol::checkSizeTypeLock(void)
{
dispflags &= ~((uint4)size_typelock);
if (isTypeLocked() && (type->getMetatype() == TYPE_UNKNOWN))
dispflags |= size_typelock;
}
/// \param val is \b true if we are the "this" pointer
void Symbol::setThisPointer(bool val)
{
if (val)
dispflags |= is_this_ptr;
else
dispflags &= ~((uint4)is_this_ptr);
}
/// The name for a Symbol can be unspecified. See ScopeInternal::buildUndefinedName
/// \return \b true if the name of \b this is undefined
bool Symbol::isNameUndefined(void) const
{
return ((name.size()==15)&&(0==name.compare(0,7,"$$undef")));
}
/// If the given value is \b true, any Varnodes that map directly to \b this Symbol,
/// will not be speculatively merged with other Varnodes. (Required merges will still happen).
/// \param val is the given boolean value
void Symbol::setIsolated(bool val)
{
if (val) {
dispflags |= isolate;
flags |= Varnode::typelock; // Isolated Symbol must be typelocked
checkSizeTypeLock();
}
else
dispflags &= ~((uint4)isolate);
}
/// \return the first SymbolEntry
SymbolEntry *Symbol::getFirstWholeMap(void) const
{
if (mapentry.empty())
throw LowlevelError("No mapping for symbol: "+name);
return &(*mapentry[0]);
}
/// This method may return a \e partial entry, where the SymbolEntry is only holding
/// part of the whole Symbol.
/// \param addr is an address within the desired storage location of the Symbol
/// \return the first matching SymbolEntry
SymbolEntry *Symbol::getMapEntry(const Address &addr) const
{
SymbolEntry *res;
for(int4 i=0;i<mapentry.size();++i) {
res = &(*mapentry[i]);
const Address &entryaddr( res->getAddr() );
if (addr.getSpace() != entryaddr.getSpace()) continue;
if (addr.getOffset() < entryaddr.getOffset()) continue;
int4 diff = (int4) (addr.getOffset() - entryaddr.getOffset());
if (diff >= res->getSize()) continue;
return res;
}
// throw LowlevelError("No mapping at desired address for symbol: "+name);
return (SymbolEntry *)0;
}
/// Among all the SymbolEntrys that map \b this entire Symbol, calculate
/// the position of the given SymbolEntry within the list.
/// \param entry is the given SymbolEntry
/// \return its position within the list or -1 if it is not in the list
int4 Symbol::getMapEntryPosition(const SymbolEntry *entry) const
{
int4 pos = 0;
for(int4 i=0;i<mapentry.size();++i) {
const SymbolEntry *tmp = &(*mapentry[i]);
if (tmp == entry)
return pos;
if (entry->getSize() == type->getSize())
pos += 1;
}
return -1;
}
/// For a given context scope where \b this Symbol is used, determine how many elements of
/// the full namespace path need to be printed to correctly distinguish it.
/// A value of 0 means the base symbol name is visible and not overridden in the context scope.
/// A value of 1 means the base name may be overridden, but the parent scope name is not.
/// The minimal number of names that distinguishes the symbol name uniquely within the
/// use scope is returned.
/// \param useScope is the given scope where the symbol is being used
/// \return the number of (extra) names needed to distinguish the symbol
int4 Symbol::getResolutionDepth(const Scope *useScope) const
{
if (scope == useScope) return 0; // Symbol is in scope where it is used
if (useScope == (const Scope *)0) { // Treat null useScope as resolving the full path
const Scope *point = scope;
int4 count = 0;
while(point != (const Scope *)0) {
count += 1;
point = point->getParent();
}
return count-1; // Don't print global scope
}
if (depthScope == useScope)
return depthResolution;
depthScope = useScope;
const Scope *distinguishScope = scope->findDistinguishingScope(useScope);
depthResolution = 0;
string distinguishName;
const Scope *terminatingScope;
if (distinguishScope == (const Scope *)0) { // Symbol scope is ancestor of use scope
distinguishName = name;
terminatingScope = scope;
}
else {
distinguishName = distinguishScope->getName();
const Scope *currentScope = scope;
while(currentScope != distinguishScope) { // For any scope up to the distinguishing scope
depthResolution += 1; // Print its name
currentScope = currentScope->getParent();
}
depthResolution += 1; // Also print the distinguishing scope name
terminatingScope = distinguishScope->getParent();
}
if (useScope->isNameUsed(distinguishName,terminatingScope))
depthResolution += 1; // Name was overridden, we need one more distinguishing name
return depthResolution;
}
/// \param encoder is the stream encoder
void Symbol::encodeHeader(Encoder &encoder) const
{
encoder.writeString(ATTRIB_NAME, name);
encoder.writeUnsignedInteger(ATTRIB_ID, getId());
if ((flags&Varnode::namelock)!=0)
encoder.writeBool(ATTRIB_NAMELOCK, true);
if ((flags&Varnode::typelock)!=0)
encoder.writeBool(ATTRIB_TYPELOCK, true);
if ((flags&Varnode::readonly)!=0)
encoder.writeBool(ATTRIB_READONLY, true);
if ((flags&Varnode::volatil)!=0)
encoder.writeBool(ATTRIB_VOLATILE, true);
if ((flags&Varnode::indirectstorage)!=0)
encoder.writeBool(ATTRIB_INDIRECTSTORAGE, true);
if ((flags&Varnode::hiddenretparm)!=0)
encoder.writeBool(ATTRIB_HIDDENRETPARM, true);
if ((dispflags&isolate)!=0)
encoder.writeBool(ATTRIB_MERGE, false);
if ((dispflags&is_this_ptr)!=0)
encoder.writeBool(ATTRIB_THISPTR, true);
int4 format = getDisplayFormat();
if (format != 0) {
encoder.writeString(ATTRIB_FORMAT, Datatype::decodeIntegerFormat(format));
}
encoder.writeSignedInteger(ATTRIB_CAT, category);
if (category >= 0)
encoder.writeUnsignedInteger(ATTRIB_INDEX, catindex);
}
/// \param decoder is the stream decoder
void Symbol::decodeHeader(Decoder &decoder)
{
name.clear();
displayName.clear();
category = no_category;
symbolId = 0;
for(;;) {
uintb attribId = decoder.getNextAttributeId();
if (attribId == 0) break;
if (attribId == ATTRIB_CAT) {
category = decoder.readSignedInteger();
}
else if (attribId == ATTRIB_FORMAT) {
dispflags |= Datatype::encodeIntegerFormat(decoder.readString());
}
else if (attribId == ATTRIB_HIDDENRETPARM) {
if (decoder.readBool())
flags |= Varnode::hiddenretparm;
}
else if (attribId == ATTRIB_ID) {
symbolId = decoder.readUnsignedInteger();
if ((symbolId >> 56) == (ID_BASE >> 56))
symbolId = 0; // Don't keep old internal id's
}
else if (attribId == ATTRIB_INDIRECTSTORAGE) {
if (decoder.readBool())
flags |= Varnode::indirectstorage;
}
else if (attribId == ATTRIB_MERGE) {
if (!decoder.readBool()) {
dispflags |= isolate;
flags |= Varnode::typelock;
}
}
else if (attribId == ATTRIB_NAME)
name = decoder.readString();
else if (attribId == ATTRIB_NAMELOCK) {
if (decoder.readBool())
flags |= Varnode::namelock;
}
else if (attribId == ATTRIB_READONLY) {
if (decoder.readBool())
flags |= Varnode::readonly;
}
else if (attribId == ATTRIB_TYPELOCK) {
if (decoder.readBool())
flags |= Varnode::typelock;
}
else if (attribId == ATTRIB_THISPTR) {
if (decoder.readBool())
dispflags |= is_this_ptr;
}
else if (attribId == ATTRIB_VOLATILE) {
if (decoder.readBool())
flags |= Varnode::volatil;
}
else if (attribId == ATTRIB_LABEL) {
displayName = decoder.readString();
}
}
if (category == function_parameter) {
catindex = decoder.readUnsignedInteger(ATTRIB_INDEX);
}
else
catindex = 0;
if (displayName.size() == 0)
displayName = name;
}
/// Encode the data-type for the Symbol
/// \param encoder is the stream encoder
void Symbol::encodeBody(Encoder &encoder) const
{
type->encodeRef(encoder);
}
/// \param decoder is the stream decoder
void Symbol::decodeBody(Decoder &decoder)
{
type = scope->getArch()->types->decodeType(decoder);
checkSizeTypeLock();
}
/// \param encoder is the stream encoder
void Symbol::encode(Encoder &encoder) const
{
encoder.openElement(ELEM_SYMBOL);
encodeHeader(encoder);
encodeBody(encoder);
encoder.closeElement(ELEM_SYMBOL);
}
/// Parse a Symbol from the next element in the stream
/// \param decoder is the stream decoder
void Symbol::decode(Decoder &decoder)
{
uint4 elemId = decoder.openElement(ELEM_SYMBOL);
decodeHeader(decoder);
decodeBody(decoder);
decoder.closeElement(elemId);
}
/// Get the number of bytes consumed by a SymbolEntry representing \b this Symbol.
/// By default, this is the number of bytes consumed by the Symbol's data-type.
/// This gives the amount of leeway a search has when the address queried does not match
/// the exact address of the Symbol. With functions, the bytes consumed by a SymbolEntry
/// may not match the data-type size.
/// \return the number of bytes in a default SymbolEntry
int4 Symbol::getBytesConsumed(void) const
{
return type->getSize();
}
void FunctionSymbol::buildType(void)
{
TypeFactory *types = scope->getArch()->types;
type = types->getTypeCode();
flags |= Varnode::namelock | Varnode::typelock;
}
/// Build a function \e shell, made up of just the name of the function and
/// a placeholder data-type, without the underlying Funcdata object.
/// A SymbolEntry for a function has a small size starting at the entry address,
/// in order to deal with non-contiguous functions.
/// We need a size (slightly) larger than 1 to accommodate pointer constants that encode
/// extra information in the lower bit(s) of an otherwise aligned pointer.
/// If the encoding is not initially detected, it is interpreted
/// as a straight address that comes up 1 (or more) bytes off of the start of the function
/// In order to detect this, we need to lay down a slightly larger size than 1
/// \param sc is the Scope that will contain the new Symbol
/// \param nm is the name of the new Symbol
/// \param size is the number of bytes a SymbolEntry should consume
FunctionSymbol::FunctionSymbol(Scope *sc,const string &nm,int4 size)
: Symbol(sc)
{
fd = (Funcdata *)0;
consumeSize = size;
buildType();
name = nm;
displayName = nm;
}
FunctionSymbol::FunctionSymbol(Scope *sc,int4 size)
: Symbol(sc)
{
fd = (Funcdata *)0;
consumeSize = size;
buildType();
}
FunctionSymbol::~FunctionSymbol(void) {
if (fd != (Funcdata *)0)
delete fd;
}
Funcdata *FunctionSymbol::getFunction(void)
{
if (fd != (Funcdata *)0) return fd;
SymbolEntry *entry = getFirstWholeMap();
fd = new Funcdata(name,displayName,scope,entry->getAddr(),this);
return fd;
}
void FunctionSymbol::encode(Encoder &encoder) const
{
if (fd != (Funcdata *)0)
fd->encode(encoder,symbolId,false); // Save the function itself
else {
encoder.openElement(ELEM_FUNCTIONSHELL);
encoder.writeString(ATTRIB_NAME, name);
if (symbolId != 0)
encoder.writeUnsignedInteger(ATTRIB_ID, symbolId);
encoder.closeElement(ELEM_FUNCTIONSHELL);
}
}
void FunctionSymbol::decode(Decoder &decoder)
{
uint4 elemId = decoder.peekElement();
if (elemId == ELEM_FUNCTION) {
fd = new Funcdata("","",scope,Address(),this);
try {
symbolId = fd->decode(decoder);
} catch(RecovError &err) {
// Caused by a duplicate scope name. Preserve the address so we can find the original symbol
throw DuplicateFunctionError(fd->getAddress(),fd->getName());
}
name = fd->getName();
displayName = fd->getDisplayName();
if (consumeSize < fd->getSize()) {
if ((fd->getSize()>1)&&(fd->getSize() <= 8))
consumeSize = fd->getSize();
}
}
else { // functionshell
decoder.openElement();
symbolId = 0;
for(;;) {
uint4 attribId = decoder.getNextAttributeId();
if (attribId == 0) break;
if (attribId == ATTRIB_NAME)
name = decoder.readString();
else if (attribId == ATTRIB_ID) {
symbolId = decoder.readUnsignedInteger();
}
else if (attribId == ATTRIB_LABEL) {
displayName = decoder.readString();
}
}
decoder.closeElement(elemId);
}
}
/// Create a symbol either to associate a name with a constant or to force a display conversion
///
/// \param sc is the scope owning the new symbol
/// \param nm is the name of the equate (an empty string can be used for a convert)
/// \param format is the desired display conversion (0 for no conversion)
/// \param val is the constant value whose display is being altered
EquateSymbol::EquateSymbol(Scope *sc,const string &nm,uint4 format,uintb val)
: Symbol(sc, nm, (Datatype *)0)
{
value = val;
category = equate;
type = sc->getArch()->types->getBase(1,TYPE_UNKNOWN);
dispflags |= format;
}
/// An EquateSymbol should survive certain kinds of transforms during decompilation,
/// such as negation, twos-complementing, adding or subtracting 1.
/// Return \b true if the given value looks like a transform of this type relative
/// to the underlying value of \b this equate.
/// \param op2Value is the given value
/// \param size is the number of bytes of precision
/// \return \b true if it is a transformed form
bool EquateSymbol::isValueClose(uintb op2Value,int4 size) const
{
if (value == op2Value) return true;
uintb mask = calc_mask(size);
uintb maskValue = value & mask;
if (maskValue != value) { // If '1' bits are getting masked off
// Make sure only sign-extension is getting masked off
if (value != sign_extend(maskValue,size,sizeof(uintb)))
return false;
}
if (maskValue == (op2Value & mask)) return true;
if (maskValue == (~op2Value & mask)) return true;
if (maskValue == (-op2Value & mask)) return true;
if (maskValue == ((op2Value + 1) & mask)) return true;
if (maskValue == ((op2Value -1) & mask)) return true;
return false;
}
void EquateSymbol::encode(Encoder &encoder) const
{
encoder.openElement(ELEM_EQUATESYMBOL);
encodeHeader(encoder);
encoder.openElement(ELEM_VALUE);
encoder.writeUnsignedInteger(ATTRIB_CONTENT, value);
encoder.closeElement(ELEM_VALUE);
encoder.closeElement(ELEM_EQUATESYMBOL);
}
void EquateSymbol::decode(Decoder &decoder)
{
uint4 elemId = decoder.openElement(ELEM_EQUATESYMBOL);
decodeHeader(decoder);
uint4 subId = decoder.openElement(ELEM_VALUE);
value = decoder.readUnsignedInteger(ATTRIB_CONTENT);
decoder.closeElement(subId);
TypeFactory *types = scope->getArch()->types;
type = types->getBase(1,TYPE_UNKNOWN);
decoder.closeElement(elemId);
}
/// Create a symbol that forces a particular field of a union to propagate
///
/// \param sc is the scope owning the new symbol
/// \param nm is the name of the symbol
/// \param unionDt is the union data-type being forced
/// \param fldNum is the particular field to force (-1 indicates the whole union)
UnionFacetSymbol::UnionFacetSymbol(Scope *sc,const string &nm,Datatype *unionDt,int4 fldNum)
: Symbol(sc, nm, unionDt)
{
fieldNum = fldNum;
category = union_facet;
}
void UnionFacetSymbol::encode(Encoder &encoder) const
{
encoder.openElement(ELEM_FACETSYMBOL);
encodeHeader(encoder);
encoder.writeSignedInteger(ATTRIB_FIELD, fieldNum);
encodeBody(encoder);
encoder.closeElement(ELEM_FACETSYMBOL);
}
void UnionFacetSymbol::decode(Decoder &decoder)
{
uint4 elemId = decoder.openElement(ELEM_FACETSYMBOL);
decodeHeader(decoder);
fieldNum = decoder.readSignedInteger(ATTRIB_FIELD);
decodeBody(decoder);
decoder.closeElement(elemId);
Datatype *testType = type;
if (testType->getMetatype() == TYPE_PTR)
testType = ((TypePointer *)testType)->getPtrTo();
if (testType->getMetatype() != TYPE_UNION)
throw LowlevelError("<unionfacetsymbol> does not have a union type");
if (fieldNum < -1 || fieldNum >= testType->numDepend())
throw LowlevelError("<unionfacetsymbol> field attribute is out of bounds");
}
/// Label symbols don't really have a data-type, so we just put
/// a size 1 placeholder.
void LabSymbol::buildType(void)
{
type = scope->getArch()->types->getBase(1,TYPE_UNKNOWN);
}
/// \param sc is the Scope that will contain the new Symbol
/// \param nm is the name of the new Symbol
LabSymbol::LabSymbol(Scope *sc,const string &nm)
: Symbol(sc)
{
buildType();
name = nm;
displayName = nm;
}
/// \param sc is the Scope that will contain the new Symbol
LabSymbol::LabSymbol(Scope *sc)
: Symbol(sc)
{
buildType();
}
void LabSymbol::encode(Encoder &encoder) const
{
encoder.openElement(ELEM_LABELSYM);
encodeHeader(encoder); // We never set category
encoder.closeElement(ELEM_LABELSYM);
}
void LabSymbol::decode(Decoder &decoder)
{
uint4 elemId = decoder.openElement(ELEM_LABELSYM);
decodeHeader(decoder);
decoder.closeElement(elemId);
}
/// Build name, type, and flags based on the placeholder address
void ExternRefSymbol::buildNameType(void)
{
TypeFactory *typegrp = scope->getArch()->types;
type = typegrp->getTypeCode();
type = typegrp->getTypePointer(refaddr.getAddrSize(),type,refaddr.getSpace()->getWordSize());
if (name.size() == 0) { // If a name was not already provided
ostringstream s; // Give the reference a unique name
s << refaddr.getShortcut();
refaddr.printRaw(s);
name = s.str();
name += "_exref"; // Indicate this is an external reference variable
}
if (displayName.size() == 0)
displayName = name;
flags |= Varnode::externref | Varnode::typelock;
}
/// \param sc is the Scope containing the Symbol
/// \param ref is the placeholder address where the system will hold meta-data
/// \param nm is the name of the Symbol
ExternRefSymbol::ExternRefSymbol(Scope *sc,const Address &ref,const string &nm)
: Symbol(sc,nm,(Datatype *)0)
{
refaddr = ref;
buildNameType();
}
void ExternRefSymbol::encode(Encoder &encoder) const
{
encoder.openElement(ELEM_EXTERNREFSYMBOL);
encoder.writeString(ATTRIB_NAME, name);
refaddr.encode(encoder);
encoder.closeElement(ELEM_EXTERNREFSYMBOL);
}
void ExternRefSymbol::decode(Decoder &decoder)
{
uint4 elemId = decoder.openElement(ELEM_EXTERNREFSYMBOL);
name.clear(); // Name is empty
displayName.clear();
for(;;) {
uint4 attribId = decoder.getNextAttributeId();
if (attribId == 0) break;
if (attribId == ATTRIB_NAME) // Unless we see it explicitly
name = decoder.readString();
else if (attribId == ATTRIB_LABEL)
displayName = decoder.readString();
}
refaddr = Address::decode(decoder);
decoder.closeElement(elemId);
buildNameType();
}
/// The iterator is advanced by one
/// \return a reference to the (advanced) iterator
MapIterator &MapIterator::operator++(void) {
++curiter;
while((curmap!=map->end())&&(curiter==(*curmap)->end_list())) {
do {
++curmap;
} while((curmap!=map->end())&&((*curmap)==(EntryMap *)0));
if (curmap!=map->end())
curiter = (*curmap)->begin_list();
}
return *this;
}
/// The iterator is advanced by one
/// \param i is a dummy variable
/// \return a copy of the iterator before it was advanced
MapIterator MapIterator::operator++(int4 i) {
MapIterator tmp(*this);
++curiter;
while((curmap!=map->end())&&(curiter==(*curmap)->end_list())) {
do {
++curmap;
} while((curmap!=map->end())&&((*curmap)==(EntryMap *)0));
if (curmap!=map->end())
curiter = (*curmap)->begin_list();
}
return tmp;
}
/// Attach the child as an immediate sub-scope of \b this.
/// Take responsibility of the child's memory: the child will be freed when this is freed.
/// \param child is the Scope to make a child
void Scope::attachScope(Scope *child)
{
child->parent = this;
children[child->uniqueId] = child; // uniqueId is guaranteed to be unique by Database
}
/// The indicated child Scope is deleted
/// \param iter points to the Scope to delete
void Scope::detachScope(ScopeMap::iterator iter)
{
Scope *child = (*iter).second;
children.erase(iter);
delete child;
}
/// \brief Create a Scope id based on the scope's name and its parent's id
///
/// Create a globally unique id for a scope simply from its name.
/// \param baseId is the scope id of the parent scope
/// \param nm is the name of scope
/// \return the hash of the parent id and name
uint8 Scope::hashScopeName(uint8 baseId,const string &nm)
{
uint4 reg1 = (uint4)(baseId>>32);
uint4 reg2 = (uint4)baseId;
reg1 = crc_update(reg1, 0xa9);
reg2 = crc_update(reg2, reg1);
for(int4 i=0;i<nm.size();++i) {
uint4 val = nm[i];
reg1 = crc_update(reg1, val);
reg2 = crc_update(reg2, reg1);
}
uint8 res = reg1;
res = (res << 32) | reg2;
return res;
}
/// \brief Query for Symbols starting at a given address, which match a given \b usepoint
///
/// Searching starts at a first scope, continuing thru parents up to a second scope,
/// which is not queried. If a Scope \e controls the memory at that address, the Scope
/// object is returned. Additionally, if a symbol matching the criterion is found,
/// the matching SymbolEntry is passed back.
/// \param scope1 is the first Scope where searching starts
/// \param scope2 is the second Scope where searching ends
/// \param addr is the given address to search for
/// \param usepoint is the given point at which the memory is being accessed (can be an invalid address)
/// \param addrmatch is used to pass-back any matching SymbolEntry
/// \return the Scope owning the address or NULL if none found
const Scope *Scope::stackAddr(const Scope *scope1,
const Scope *scope2,
const Address &addr,
const Address &usepoint,
SymbolEntry **addrmatch)
{
SymbolEntry *entry;
if (addr.isConstant()) return (const Scope *)0;
while((scope1 != (const Scope *)0)&&(scope1 != scope2)) {
entry = scope1->findAddr(addr,usepoint);
if (entry != (SymbolEntry *)0) {
*addrmatch = entry;
return scope1;
}
if (scope1->inScope(addr,1,usepoint))
return scope1; // Discovery of new variable
scope1 = scope1->getParent();
}
return (const Scope *)0;
}
/// Query for a Symbol containing a given range which is accessed at a given \b usepoint
///
/// Searching starts at a first scope, continuing thru parents up to a second scope,
/// which is not queried. If a Scope \e controls the memory in the given range, the Scope
/// object is returned. If a known Symbol contains the range,
/// the matching SymbolEntry is passed back.
/// \param scope1 is the first Scope where searching starts
/// \param scope2 is the second Scope where searching ends
/// \param addr is the starting address of the given range
/// \param size is the number of bytes in the given range
/// \param usepoint is the point at which the memory is being accessed (can be an invalid address)
/// \param addrmatch is used to pass-back any matching SymbolEntry
/// \return the Scope owning the address or NULL if none found
const Scope *Scope::stackContainer(const Scope *scope1,
const Scope *scope2,
const Address &addr,int4 size,
const Address &usepoint,
SymbolEntry **addrmatch)
{
SymbolEntry *entry;
if (addr.isConstant()) return (const Scope *)0;
while((scope1 != (const Scope *)0)&&(scope1 != scope2)) {
entry = scope1->findContainer(addr,size,usepoint);
if (entry != (SymbolEntry *)0) {
*addrmatch = entry;
return scope1;
}
if (scope1->inScope(addr,size,usepoint))
return scope1; // Discovery of new variable
scope1 = scope1->getParent();
}
return (const Scope *)0;
}
/// Query for a Symbol which most closely matches a given range and \b usepoint
///
/// Searching starts at a first scope, continuing thru parents up to a second scope,
/// which is not queried. If a Scope \e controls the memory in the given range, the Scope
/// object is returned. Among symbols that overlap the given range, the SymbolEntry
/// which most closely matches the starting address and size is passed back.
/// \param scope1 is the first Scope where searching starts
/// \param scope2 is the second Scope where searching ends
/// \param addr is the starting address of the given range
/// \param size is the number of bytes in the given range
/// \param usepoint is the point at which the memory is being accessed (can be an invalid address)
/// \param addrmatch is used to pass-back any matching SymbolEntry
/// \return the Scope owning the address or NULL if none found
const Scope *Scope::stackClosestFit(const Scope *scope1,
const Scope *scope2,
const Address &addr,int4 size,
const Address &usepoint,
SymbolEntry **addrmatch)
{
SymbolEntry *entry;
if (addr.isConstant()) return (const Scope *)0;
while((scope1 != (const Scope *)0)&&(scope1 != scope2)) {
entry = scope1->findClosestFit(addr,size,usepoint);
if (entry != (SymbolEntry *)0) {
*addrmatch = entry;
return scope1;
}
if (scope1->inScope(addr,size,usepoint))
return scope1; // Discovery of new variable
scope1 = scope1->getParent();
}
return (const Scope *)0;
}
/// Query for a function Symbol starting at the given address
///
/// Searching starts at a first scope, continuing thru parents up to a second scope,