-
Notifications
You must be signed in to change notification settings - Fork 50
/
marshal.cc
1271 lines (1098 loc) · 34.1 KB
/
marshal.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 "marshal.hh"
#include "translate.hh"
namespace ghidra {
using namespace PackedFormat;
unordered_map<string,uint4> AttributeId::lookupAttributeId;
const int4 PackedDecode::BUFFER_SIZE = 1024;
const char XmlEncode::spaces[] = "\n ";
const int4 XmlEncode::MAX_SPACES = 24+1;
/// Access static vector of AttributeId objects that are registered during static initialization
/// The list itself is created once on the first call to this method.
/// \return a reference to the vector
vector<AttributeId *> &AttributeId::getList(void)
{
static vector<AttributeId *> thelist;
return thelist;
}
/// This constructor should only be invoked for static objects. It registers the attribute for inclusion
/// in the global hashtable.
/// \param nm is the name of the attribute
/// \param i is an id to associate with the attribute
/// \param scope is an id for the scope of this attribute
AttributeId::AttributeId(const string &nm,uint4 i,int4 scope)
: name(nm)
{
id = i;
if (scope == 0)
getList().push_back(this);
}
/// Fill the hashtable mapping attribute names to their id, from registered attribute objects
void AttributeId::initialize(void)
{
vector<AttributeId *> &thelist(getList());
for(int4 i=0;i<thelist.size();++i) {
AttributeId *attrib = thelist[i];
#ifdef CPUI_DEBUG
if (lookupAttributeId.find(attrib->name) != lookupAttributeId.end())
throw DecoderError(attrib->name + " attribute registered more than once");
#endif
lookupAttributeId[attrib->name] = attrib->id;
}
thelist.clear();
thelist.shrink_to_fit();
}
unordered_map<string,uint4> ElementId::lookupElementId;
/// Access static vector of ElementId objects that are registered during static initialization
/// The list itself is created once on the first call to this method.
/// \return a reference to the vector
vector<ElementId *> &ElementId::getList(void)
{
static vector<ElementId *> thelist;
return thelist;
}
/// This constructor should only be invoked for static objects. It registers the element for inclusion
/// in the global hashtable.
/// \param nm is the name of the element
/// \param i is an id to associate with the element
/// \param scope is an id for the scope of this element
ElementId::ElementId(const string &nm,uint4 i,int4 scope)
: name(nm)
{
id = i;
if (scope == 0)
getList().push_back(this);
}
/// Fill the hashtable mapping element names to their id, from registered element objects
void ElementId::initialize(void)
{
vector<ElementId *> &thelist(getList());
for(int4 i=0;i<thelist.size();++i) {
ElementId *elem = thelist[i];
#ifdef CPUI_DEBUG
if (lookupElementId.find(elem->name) != lookupElementId.end())
throw DecoderError(elem->name + " element registered more than once");
#endif
lookupElementId[elem->name] = elem->id;
}
thelist.clear();
thelist.shrink_to_fit();
}
XmlDecode::~XmlDecode(void)
{
if (document != (Document *)0)
delete document;
}
void XmlDecode::ingestStream(istream &s)
{
document = xml_tree(s);
rootElement = document->getRoot();
}
uint4 XmlDecode::peekElement(void)
{
const Element *el;
if (elStack.empty()) {
if (rootElement == (const Element *)0)
return 0;
el = rootElement;
}
else {
el = elStack.back();
List::const_iterator iter = iterStack.back();
if (iter == el->getChildren().end())
return 0;
el = *iter;
}
return ElementId::find(el->getName(),scope);
}
uint4 XmlDecode::openElement(void)
{
const Element *el;
if (elStack.empty()) {
if (rootElement == (const Element *)0)
return 0; // Document already traversed
el = rootElement;
rootElement = (const Element *)0; // Only open once
}
else {
el = elStack.back();
List::const_iterator iter = iterStack.back();
if (iter == el->getChildren().end())
return 0; // Element already fully traversed
el = *iter;
iterStack.back() = ++iter;
}
elStack.push_back(el);
iterStack.push_back(el->getChildren().begin());
attributeIndex = -1;
return ElementId::find(el->getName(),scope);
}
uint4 XmlDecode::openElement(const ElementId &elemId)
{
const Element *el;
if (elStack.empty()) {
if (rootElement == (const Element *)0)
throw DecoderError("Expecting <" + elemId.getName() + "> but reached end of document");
el = rootElement;
rootElement = (const Element *)0; // Only open document once
}
else {
el = elStack.back();
List::const_iterator iter = iterStack.back();
if (iter != el->getChildren().end()) {
el = *iter;
iterStack.back() = ++iter;
}
else
throw DecoderError("Expecting <" + elemId.getName() + "> but no remaining children in current element");
}
if (el->getName() != elemId.getName())
throw DecoderError("Expecting <" + elemId.getName() + "> but got <" + el->getName() + ">");
elStack.push_back(el);
iterStack.push_back(el->getChildren().begin());
attributeIndex = -1;
return elemId.getId();
}
void XmlDecode::closeElement(uint4 id)
{
#ifdef CPUI_DEBUG
const Element *el = elStack.back();
if (iterStack.back() != el->getChildren().end())
throw DecoderError("Closing element <" + el->getName() + "> with additional children");
if (ElementId::find(el->getName(), scope) != id)
throw DecoderError("Trying to close <" + el->getName() + "> with mismatching id");
#endif
elStack.pop_back();
iterStack.pop_back();
attributeIndex = 1000; // Cannot read any additional attributes
}
void XmlDecode::closeElementSkipping(uint4 id)
{
#ifdef CPUI_DEBUG
const Element *el = elStack.back();
if (ElementId::find(el->getName(), scope) != id)
throw DecoderError("Trying to close <" + el->getName() + "> with mismatching id");
#endif
elStack.pop_back();
iterStack.pop_back();
attributeIndex = 1000; // We could check that id matches current element
}
void XmlDecode::rewindAttributes(void)
{
attributeIndex = -1;
}
uint4 XmlDecode::getNextAttributeId(void)
{
const Element *el = elStack.back();
int4 nextIndex = attributeIndex + 1;
if (nextIndex < el->getNumAttributes()) {
attributeIndex = nextIndex;
return AttributeId::find(el->getAttributeName(attributeIndex),scope);
}
return 0;
}
uint4 XmlDecode::getIndexedAttributeId(const AttributeId &attribId)
{
const Element *el = elStack.back();
if (attributeIndex < 0 || attributeIndex >= el->getNumAttributes())
return ATTRIB_UNKNOWN.getId();
// For XML, the index is encoded directly in the attribute name
const string &attribName(el->getAttributeName(attributeIndex));
// Does the name start with desired attribute base name?
if (0 != attribName.compare(0,attribId.getName().size(),attribId.getName()))
return ATTRIB_UNKNOWN.getId();
uint4 val = 0;
istringstream s(attribName.substr(attribId.getName().size())); // Strip off the base name
s >> dec >> val; // Decode the remaining decimal integer (starting at 1)
if (val == 0)
throw LowlevelError("Bad indexed attribute: " + attribId.getName());
return attribId.getId() + (val-1);
}
/// \brief Find the attribute index, within the given element, for the given name
///
/// Run through the attributes of the element until we find the one matching the name,
/// or throw an exception otherwise.
/// \param el is the given element to search
/// \param attribName is the attribute name to search for
/// \return the matching attribute index
int4 XmlDecode::findMatchingAttribute(const Element *el,const string &attribName)
{
for(int4 i=0;i<el->getNumAttributes();++i) {
if (el->getAttributeName(i) == attribName)
return i;
}
throw DecoderError("Attribute missing: " + attribName);
}
bool XmlDecode::readBool(void)
{
const Element *el = elStack.back();
return xml_readbool(el->getAttributeValue(attributeIndex));
}
bool XmlDecode::readBool(const AttributeId &attribId)
{
const Element *el = elStack.back();
if (attribId == ATTRIB_CONTENT)
return xml_readbool(el->getContent());
int4 index = findMatchingAttribute(el, attribId.getName());
return xml_readbool(el->getAttributeValue(index));
}
intb XmlDecode::readSignedInteger(void)
{
const Element *el = elStack.back();
intb res = 0;
istringstream s2(el->getAttributeValue(attributeIndex));
s2.unsetf(ios::dec | ios::hex | ios::oct);
s2 >> res;
return res;
}
intb XmlDecode::readSignedInteger(const AttributeId &attribId)
{
const Element *el = elStack.back();
intb res = 0;
if (attribId == ATTRIB_CONTENT) {
istringstream s(el->getContent());
s.unsetf(ios::dec | ios::hex | ios::oct);
s >> res;
}
else {
int4 index = findMatchingAttribute(el, attribId.getName());
istringstream s(el->getAttributeValue(index));
s.unsetf(ios::dec | ios::hex | ios::oct);
s >> res;
}
return res;
}
intb XmlDecode::readSignedIntegerExpectString(const string &expect,intb expectval)
{
const Element *el = elStack.back();
const string &value( el->getAttributeValue(attributeIndex) );
if (value == expect)
return expectval;
istringstream s2(value);
s2.unsetf(ios::dec | ios::hex | ios::oct);
intb res = 0;
s2 >> res;
return res;
}
intb XmlDecode::readSignedIntegerExpectString(const AttributeId &attribId,const string &expect,intb expectval)
{
string value = readString(attribId);
if (value == expect)
return expectval;
istringstream s2(value);
s2.unsetf(ios::dec | ios::hex | ios::oct);
intb res = 0;
s2 >> res;
return res;
}
uintb XmlDecode::readUnsignedInteger(void)
{
const Element *el = elStack.back();
uintb res = 0;
istringstream s2(el->getAttributeValue(attributeIndex));
s2.unsetf(ios::dec | ios::hex | ios::oct);
s2 >> res;
return res;
}
uintb XmlDecode::readUnsignedInteger(const AttributeId &attribId)
{
const Element *el = elStack.back();
uintb res = 0;
if (attribId == ATTRIB_CONTENT) {
istringstream s(el->getContent());
s.unsetf(ios::dec | ios::hex | ios::oct);
s >> res;
}
else {
int4 index = findMatchingAttribute(el, attribId.getName());
istringstream s(el->getAttributeValue(index));
s.unsetf(ios::dec | ios::hex | ios::oct);
s >> res;
}
return res;
}
string XmlDecode::readString(void)
{
const Element *el = elStack.back();
return el->getAttributeValue(attributeIndex);
}
string XmlDecode::readString(const AttributeId &attribId)
{
const Element *el = elStack.back();
if (attribId == ATTRIB_CONTENT)
return el->getContent();
int4 index = findMatchingAttribute(el, attribId.getName());
return el->getAttributeValue(index);
}
AddrSpace *XmlDecode::readSpace(void)
{
const Element *el = elStack.back();
string nm = el->getAttributeValue(attributeIndex);
AddrSpace *res = spcManager->getSpaceByName(nm);
if (res == (AddrSpace *)0)
throw DecoderError("Unknown address space name: "+nm);
return res;
}
AddrSpace *XmlDecode::readSpace(const AttributeId &attribId)
{
const Element *el = elStack.back();
string nm;
if (attribId == ATTRIB_CONTENT) {
nm = el->getContent();
}
else {
int4 index = findMatchingAttribute(el, attribId.getName());
nm = el->getAttributeValue(index);
}
AddrSpace *res = spcManager->getSpaceByName(nm);
if (res == (AddrSpace *)0)
throw DecoderError("Unknown address space name: "+nm);
return res;
}
OpCode XmlDecode::readOpcode(void)
{
const Element *el = elStack.back();
string nm = el->getAttributeValue(attributeIndex);
OpCode opc = get_opcode(nm);
if (opc == (OpCode)0)
throw DecoderError("Bad encoded OpCode");
return opc;
}
OpCode XmlDecode::readOpcode(AttributeId &attribId)
{
const Element *el = elStack.back();
string nm;
if (attribId == ATTRIB_CONTENT) {
nm = el->getContent();
}
else {
int4 index = findMatchingAttribute(el, attribId.getName());
nm = el->getAttributeValue(index);
}
OpCode opc = get_opcode(nm);
if (opc == (OpCode)0)
throw DecoderError("Bad encoded OpCode");
return opc;
}
void XmlEncode::newLine(void)
{
if (!doFormatting)
return;
int numSpaces = depth * 2 + 1;
if (numSpaces > MAX_SPACES) {
numSpaces = MAX_SPACES;
}
outStream.write(spaces,numSpaces);
}
void XmlEncode::openElement(const ElementId &elemId)
{
if (tagStatus == tag_start)
outStream << '>';
else
tagStatus = tag_start;
newLine();
outStream << '<' << elemId.getName();
depth += 1;
}
void XmlEncode::closeElement(const ElementId &elemId)
{
depth -= 1;
if (tagStatus == tag_start) {
outStream << "/>";
tagStatus = tag_stop;
return;
}
if (tagStatus != tag_content)
newLine();
else
tagStatus = tag_stop;
outStream << "</" << elemId.getName() << '>';
}
void XmlEncode::writeBool(const AttributeId &attribId,bool val)
{
if (attribId == ATTRIB_CONTENT) { // Special id indicating, text value
if (tagStatus == tag_start) {
outStream << '>';
}
if (val)
outStream << "true";
else
outStream << "false";
tagStatus = tag_content;
return;
}
a_v_b(outStream, attribId.getName(), val);
}
void XmlEncode::writeSignedInteger(const AttributeId &attribId,intb val)
{
if (attribId == ATTRIB_CONTENT) { // Special id indicating, text value
if (tagStatus == tag_start) {
outStream << '>';
}
outStream << dec << val;
tagStatus = tag_content;
return;
}
a_v_i(outStream, attribId.getName(), val);
}
void XmlEncode::writeUnsignedInteger(const AttributeId &attribId,uintb val)
{
if (attribId == ATTRIB_CONTENT) { // Special id indicating, text value
if (tagStatus == tag_start) {
outStream << '>';
}
outStream << hex << "0x" << val;
tagStatus = tag_content;
return;
}
a_v_u(outStream, attribId.getName(), val);
}
void XmlEncode::writeString(const AttributeId &attribId,const string &val)
{
if (attribId == ATTRIB_CONTENT) { // Special id indicating, text value
if (tagStatus == tag_start) {
outStream << '>';
}
xml_escape(outStream, val.c_str());
tagStatus = tag_content;
return;
}
a_v(outStream,attribId.getName(),val);
}
void XmlEncode::writeStringIndexed(const AttributeId &attribId,uint4 index,const string &val)
{
outStream << ' ' << attribId.getName() << dec << index + 1;
outStream << "=\"";
xml_escape(outStream,val.c_str());
outStream << "\"";
}
void XmlEncode::writeSpace(const AttributeId &attribId,const AddrSpace *spc)
{
if (attribId == ATTRIB_CONTENT) { // Special id indicating, text value
if (tagStatus == tag_start) {
outStream << '>';
}
xml_escape(outStream, spc->getName().c_str());
tagStatus = tag_content;
return;
}
a_v(outStream,attribId.getName(),spc->getName());
}
void XmlEncode::writeOpcode(const AttributeId &attribId,OpCode opc)
{
const char *name = get_opname(opc);
if (attribId == ATTRIB_CONTENT) { // Special id indicating, text value
if (tagStatus == tag_start) {
outStream << '>';
}
outStream << name;
tagStatus = tag_content;
return;
}
outStream << ' ' << attribId.getName() << "=\"";
outStream << name;
outStream << "\"";
}
/// The integer is encoded, 7-bits per byte, starting with the most significant 7-bits.
/// The integer is decode from the \e current position, and the position is advanced.
/// \param len is the number of bytes to extract
uint8 PackedDecode::readInteger(int4 len)
{
uint8 res = 0;
while(len > 0) {
res <<= RAWDATA_BITSPERBYTE;
res |= (getNextByte(curPos) & RAWDATA_MASK);
len -= 1;
}
return res;
}
/// The \e current position is reset to the start of the current open element. Attributes are scanned
/// and skipped until the attribute matching the given id is found. The \e current position is set to the
/// start of the matching attribute, in preparation for one of the read*() methods.
/// If the id is not found an exception is thrown.
/// \param attribId is the attribute id to scan for.
void PackedDecode::findMatchingAttribute(const AttributeId &attribId)
{
curPos = startPos;
for(;;) {
uint1 header1 = getByte(curPos);
if ((header1 & HEADER_MASK) != ATTRIBUTE) break;
uint4 id = header1 & ELEMENTID_MASK;
if ((header1 & HEADEREXTEND_MASK) != 0) {
id <<= RAWDATA_BITSPERBYTE;
id |= (getBytePlus1(curPos) & RAWDATA_MASK);
}
if (attribId.getId() == id)
return; // Found it
skipAttribute();
}
throw DecoderError("Attribute " + attribId.getName() + " is not present");
}
/// The attribute at the \e current position is scanned enough to determine its length, and the position
/// is advanced to the following byte.
void PackedDecode::skipAttribute(void)
{
uint1 header1 = getNextByte(curPos); // Attribute header
if ((header1 & HEADEREXTEND_MASK) != 0)
getNextByte(curPos); // Extra byte for extended id
uint1 typeByte = getNextByte(curPos); // Type (and length) byte
uint1 attribType = typeByte >> TYPECODE_SHIFT;
if (attribType == TYPECODE_BOOLEAN || attribType == TYPECODE_SPECIALSPACE)
return; // has no additional data
uint4 length = readLengthCode(typeByte); // Length of data in bytes
if (attribType == TYPECODE_STRING) {
length = readInteger(length); // Read length field to get final length of string
}
advancePosition(curPos, length); // Skip -length- data
}
/// This assumes the header and \b type \b byte have been read. Decode type and length info and finish
/// skipping over the attribute so that the next call to getNextAttributeId() is on cut.
/// \param typeByte is the previously scanned type byte
void PackedDecode::skipAttributeRemaining(uint1 typeByte)
{
uint1 attribType = typeByte >> TYPECODE_SHIFT;
if (attribType == TYPECODE_BOOLEAN || attribType == TYPECODE_SPECIALSPACE)
return; // has no additional data
uint4 length = readLengthCode(typeByte); // Length of data in bytes
if (attribType == TYPECODE_STRING) {
length = readInteger(length); // Read length field to get final length of string
}
advancePosition(curPos, length); // Skip -length- data
}
/// Set decoder to beginning of the stream. Add padding to end of the stream.
/// \param bufPos is the number of bytes used by the last input buffer
void PackedDecode::endIngest(int4 bufPos)
{
endPos.seqIter = inStream.begin(); // Set position to beginning of stream
if (endPos.seqIter != inStream.end()) {
endPos.current = (*endPos.seqIter).start;
endPos.end = (*endPos.seqIter).end;
// Make sure there is at least one character after ingested buffer
if (bufPos == BUFFER_SIZE) {
// Last buffer was entirely filled
uint1 *endbuf = new uint1[1]; // Add one more buffer
inStream.emplace_back(endbuf,endbuf + 1);
bufPos = 0;
}
uint1 *buf = inStream.back().start;
buf[bufPos] = ELEMENT_END;
}
}
PackedDecode::~PackedDecode(void)
{
list<ByteChunk>::const_iterator iter;
for(iter=inStream.begin();iter!=inStream.end();++iter) {
delete [] (*iter).start;
}
}
void PackedDecode::ingestStream(istream &s)
{
int4 gcount = 0;
while(s.peek() > 0) {
uint1 *buf = allocateNextInputBuffer(1);
s.get((char *)buf,BUFFER_SIZE+1,'\0');
gcount = s.gcount();
}
endIngest(gcount);
}
uint4 PackedDecode::peekElement(void)
{
uint1 header1 = getByte(endPos);
if ((header1 & HEADER_MASK) != ELEMENT_START)
return 0;
uint4 id = header1 & ELEMENTID_MASK;
if ((header1 & HEADEREXTEND_MASK) != 0) {
id <<= RAWDATA_BITSPERBYTE;
id |= (getBytePlus1(endPos) & RAWDATA_MASK);
}
return id;
}
uint4 PackedDecode::openElement(void)
{
uint1 header1 = getByte(endPos);
if ((header1 & HEADER_MASK) != ELEMENT_START)
return 0;
getNextByte(endPos);
uint4 id = header1 & ELEMENTID_MASK;
if ((header1 & HEADEREXTEND_MASK) != 0) {
id <<= RAWDATA_BITSPERBYTE;
id |= (getNextByte(endPos) & RAWDATA_MASK);
}
startPos = endPos;
curPos = endPos;
header1 = getByte(curPos);
while((header1 & HEADER_MASK) == ATTRIBUTE) {
skipAttribute();
header1 = getByte(curPos);
}
endPos = curPos;
curPos = startPos;
attributeRead = true; // "Last attribute was read" is vacuously true
return id;
}
uint4 PackedDecode::openElement(const ElementId &elemId)
{
uint4 id = openElement();
if (id != elemId.getId()) {
if (id == 0)
throw DecoderError("Expecting <" + elemId.getName() + "> but did not scan an element");
throw DecoderError("Expecting <" + elemId.getName() + "> but id did not match");
}
return id;
}
void PackedDecode::closeElement(uint4 id)
{
uint1 header1 = getNextByte(endPos);
if ((header1 & HEADER_MASK) != ELEMENT_END)
throw DecoderError("Expecting element close");
uint4 closeId = header1 & ELEMENTID_MASK;
if ((header1 & HEADEREXTEND_MASK) != 0) {
closeId <<= RAWDATA_BITSPERBYTE;
closeId |= (getNextByte(endPos) & RAWDATA_MASK);
}
if (id != closeId)
throw DecoderError("Did not see expected closing element");
}
void PackedDecode::closeElementSkipping(uint4 id)
{
vector<uint4> idstack;
idstack.push_back(id);
do {
uint1 header1 = getByte(endPos) & HEADER_MASK;
if (header1 == ELEMENT_END) {
closeElement(idstack.back());
idstack.pop_back();
}
else if (header1 == ELEMENT_START) {
idstack.push_back(openElement());
}
else
throw DecoderError("Corrupt stream");
} while(!idstack.empty());
}
void PackedDecode::rewindAttributes(void)
{
curPos = startPos;
attributeRead = true;
}
uint4 PackedDecode::getNextAttributeId(void)
{
if (!attributeRead)
skipAttribute();
uint1 header1 = getByte(curPos);
if ((header1 & HEADER_MASK) != ATTRIBUTE)
return 0;
uint4 id = header1 & ELEMENTID_MASK;
if ((header1 & HEADEREXTEND_MASK) != 0) {
id <<= RAWDATA_BITSPERBYTE;
id |= (getBytePlus1(curPos) & RAWDATA_MASK);
}
attributeRead = false;
return id;
}
uint4 PackedDecode::getIndexedAttributeId(const AttributeId &attribId)
{
return ATTRIB_UNKNOWN.getId(); // PackedDecode never needs to reinterpret an attribute
}
bool PackedDecode::readBool(void)
{
uint1 header1 = getNextByte(curPos);
if ((header1 & HEADEREXTEND_MASK)!=0)
getNextByte(curPos);
uint1 typeByte = getNextByte(curPos);
attributeRead = true;
if ((typeByte >> TYPECODE_SHIFT) != TYPECODE_BOOLEAN)
throw DecoderError("Expecting boolean attribute");
return ((typeByte & LENGTHCODE_MASK) != 0);
}
bool PackedDecode::readBool(const AttributeId &attribId)
{
findMatchingAttribute(attribId);
bool res = readBool();
curPos = startPos;
return res;
}
intb PackedDecode::readSignedInteger(void)
{
uint1 header1 = getNextByte(curPos);
if ((header1 & HEADEREXTEND_MASK)!=0)
getNextByte(curPos);
uint1 typeByte = getNextByte(curPos);
uint4 typeCode = typeByte >> TYPECODE_SHIFT;
intb res;
if (typeCode == TYPECODE_SIGNEDINT_POSITIVE) {
res = readInteger(readLengthCode(typeByte));
}
else if (typeCode == TYPECODE_SIGNEDINT_NEGATIVE) {
res = readInteger(readLengthCode(typeByte));
res = -res;
}
else {
skipAttributeRemaining(typeByte);
attributeRead = true;
throw DecoderError("Expecting signed integer attribute");
}
attributeRead = true;
return res;
}
intb PackedDecode::readSignedInteger(const AttributeId &attribId)
{
findMatchingAttribute(attribId);
intb res = readSignedInteger();
curPos = startPos;
return res;
}
intb PackedDecode::readSignedIntegerExpectString(const string &expect,intb expectval)
{
intb res;
Position tmpPos = curPos;
uint1 header1 = getNextByte(tmpPos);
if ((header1 & HEADEREXTEND_MASK)!=0)
getNextByte(tmpPos);
uint1 typeByte = getNextByte(tmpPos);
uint4 typeCode = typeByte >> TYPECODE_SHIFT;
if (typeCode == TYPECODE_STRING) {
string val = readString();
if (val != expect) {
ostringstream s;
s << "Expecting string \"" << expect << "\" but read \"" << val << "\"";
throw DecoderError(s.str());
}
res = expectval;
}
else {
res = readSignedInteger();
}
return res;
}
intb PackedDecode::readSignedIntegerExpectString(const AttributeId &attribId,const string &expect,intb expectval)
{
findMatchingAttribute(attribId);
intb res = readSignedIntegerExpectString(expect,expectval);
curPos = startPos;
return res;
}
uintb PackedDecode::readUnsignedInteger(void)
{
uint1 header1 = getNextByte(curPos);
if ((header1 & HEADEREXTEND_MASK)!=0)
getNextByte(curPos);
uint1 typeByte = getNextByte(curPos);
uint4 typeCode = typeByte >> TYPECODE_SHIFT;
uintb res;
if (typeCode == TYPECODE_UNSIGNEDINT) {
res = readInteger(readLengthCode(typeByte));
}
else {
skipAttributeRemaining(typeByte);
attributeRead = true;
throw DecoderError("Expecting unsigned integer attribute");
}
attributeRead = true;
return res;
}
uintb PackedDecode::readUnsignedInteger(const AttributeId &attribId)
{
findMatchingAttribute(attribId);
uintb res = readUnsignedInteger();
curPos = startPos;
return res;
}
string PackedDecode::readString(void)
{
uint1 header1 = getNextByte(curPos);
if ((header1 & HEADEREXTEND_MASK)!=0)
getNextByte(curPos);
uint1 typeByte = getNextByte(curPos);
uint4 typeCode = typeByte >> TYPECODE_SHIFT;
if (typeCode != TYPECODE_STRING) {
skipAttributeRemaining(typeByte);
attributeRead = true;
throw DecoderError("Expecting string attribute");
}
int4 length = readLengthCode(typeByte);
length = readInteger(length);
attributeRead = true;
int4 curLen = curPos.end - curPos.current;
if (curLen >= length) {
string res((const char *)curPos.current,length);
advancePosition(curPos, length);
return res;
}
string res((const char *)curPos.current,curLen);
length -= curLen;
advancePosition(curPos, curLen);
while(length > 0) {
curLen = curPos.end - curPos.current;
if (curLen > length)
curLen = length;
res.append((const char *)curPos.current,curLen);
length -= curLen;
advancePosition(curPos, curLen);
}
return res;
}
string PackedDecode::readString(const AttributeId &attribId)
{
findMatchingAttribute(attribId);
string res = readString();
curPos = startPos;
return res;
}
AddrSpace *PackedDecode::readSpace(void)
{
uint1 header1 = getNextByte(curPos);