Verify sizes when trying to read a VBR
[oota-llvm.git] / lib / Bitcode / Reader / BitstreamReader.cpp
1 //===- BitstreamReader.cpp - BitstreamReader implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Bitcode/BitstreamReader.h"
11
12 using namespace llvm;
13
14 //===----------------------------------------------------------------------===//
15 //  BitstreamCursor implementation
16 //===----------------------------------------------------------------------===//
17
18 void BitstreamCursor::freeState() {
19   // Free all the Abbrevs.
20   CurAbbrevs.clear();
21
22   // Free all the Abbrevs in the block scope.
23   BlockScope.clear();
24 }
25
26 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
27 /// the block, and return true if the block has an error.
28 bool BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
29   // Save the current block's state on BlockScope.
30   BlockScope.push_back(Block(CurCodeSize));
31   BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
32
33   // Add the abbrevs specific to this block to the CurAbbrevs list.
34   if (const BitstreamReader::BlockInfo *Info =
35       BitStream->getBlockInfo(BlockID)) {
36     CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
37                       Info->Abbrevs.end());
38   }
39
40   // Get the codesize of this block.
41   CurCodeSize = ReadVBR(bitc::CodeLenWidth);
42   SkipToFourByteBoundary();
43   unsigned NumWords = Read(bitc::BlockSizeWidth);
44   if (NumWordsP) *NumWordsP = NumWords;
45
46   // Validate that this block is sane.
47   if (CurCodeSize == 0 || AtEndOfStream())
48     return true;
49
50   return false;
51 }
52
53 static uint64_t readAbbreviatedField(BitstreamCursor &Cursor,
54                                      const BitCodeAbbrevOp &Op) {
55   assert(!Op.isLiteral() && "Not to be used with literals!");
56
57   // Decode the value as we are commanded.
58   switch (Op.getEncoding()) {
59   case BitCodeAbbrevOp::Array:
60   case BitCodeAbbrevOp::Blob:
61     llvm_unreachable("Should not reach here");
62   case BitCodeAbbrevOp::Fixed:
63     return Cursor.Read((unsigned)Op.getEncodingData());
64   case BitCodeAbbrevOp::VBR:
65     if ((unsigned)Op.getEncodingData() > 64)
66       report_fatal_error("Invalid record");
67     return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
68   case BitCodeAbbrevOp::Char6:
69     return BitCodeAbbrevOp::DecodeChar6(Cursor.Read(6));
70   }
71   llvm_unreachable("invalid abbreviation encoding");
72 }
73
74 static void skipAbbreviatedField(BitstreamCursor &Cursor,
75                                  const BitCodeAbbrevOp &Op) {
76   assert(!Op.isLiteral() && "Not to be used with literals!");
77
78   // Decode the value as we are commanded.
79   switch (Op.getEncoding()) {
80   case BitCodeAbbrevOp::Array:
81   case BitCodeAbbrevOp::Blob:
82     llvm_unreachable("Should not reach here");
83   case BitCodeAbbrevOp::Fixed:
84     Cursor.Read((unsigned)Op.getEncodingData());
85     break;
86   case BitCodeAbbrevOp::VBR:
87     Cursor.ReadVBR64((unsigned)Op.getEncodingData());
88     break;
89   case BitCodeAbbrevOp::Char6:
90     Cursor.Read(6);
91     break;
92   }
93 }
94
95
96
97 /// skipRecord - Read the current record and discard it.
98 void BitstreamCursor::skipRecord(unsigned AbbrevID) {
99   // Skip unabbreviated records by reading past their entries.
100   if (AbbrevID == bitc::UNABBREV_RECORD) {
101     unsigned Code = ReadVBR(6);
102     (void)Code;
103     unsigned NumElts = ReadVBR(6);
104     for (unsigned i = 0; i != NumElts; ++i)
105       (void)ReadVBR64(6);
106     return;
107   }
108
109   const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
110
111   for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
112     const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
113     if (Op.isLiteral())
114       continue;
115
116     if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
117         Op.getEncoding() != BitCodeAbbrevOp::Blob) {
118       skipAbbreviatedField(*this, Op);
119       continue;
120     }
121
122     if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
123       // Array case.  Read the number of elements as a vbr6.
124       unsigned NumElts = ReadVBR(6);
125
126       // Get the element encoding.
127       assert(i+2 == e && "array op not second to last?");
128       const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
129
130       // Read all the elements.
131       for (; NumElts; --NumElts)
132         skipAbbreviatedField(*this, EltEnc);
133       continue;
134     }
135
136     assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
137     // Blob case.  Read the number of bytes as a vbr6.
138     unsigned NumElts = ReadVBR(6);
139     SkipToFourByteBoundary();  // 32-bit alignment
140
141     // Figure out where the end of this blob will be including tail padding.
142     size_t NewEnd = GetCurrentBitNo()+((NumElts+3)&~3)*8;
143
144     // If this would read off the end of the bitcode file, just set the
145     // record to empty and return.
146     if (!canSkipToPos(NewEnd/8)) {
147       NextChar = BitStream->getBitcodeBytes().getExtent();
148       break;
149     }
150
151     // Skip over the blob.
152     JumpToBit(NewEnd);
153   }
154 }
155
156 unsigned BitstreamCursor::readRecord(unsigned AbbrevID,
157                                      SmallVectorImpl<uint64_t> &Vals,
158                                      StringRef *Blob) {
159   if (AbbrevID == bitc::UNABBREV_RECORD) {
160     unsigned Code = ReadVBR(6);
161     unsigned NumElts = ReadVBR(6);
162     for (unsigned i = 0; i != NumElts; ++i)
163       Vals.push_back(ReadVBR64(6));
164     return Code;
165   }
166
167   const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
168
169   // Read the record code first.
170   assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?");
171   const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
172   unsigned Code;
173   if (CodeOp.isLiteral())
174     Code = CodeOp.getLiteralValue();
175   else {
176     if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
177         CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
178       report_fatal_error("Abbreviation starts with an Array or a Blob");
179     Code = readAbbreviatedField(*this, CodeOp);
180   }
181
182   for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
183     const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
184     if (Op.isLiteral()) {
185       Vals.push_back(Op.getLiteralValue());
186       continue;
187     }
188
189     if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
190         Op.getEncoding() != BitCodeAbbrevOp::Blob) {
191       Vals.push_back(readAbbreviatedField(*this, Op));
192       continue;
193     }
194
195     if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
196       // Array case.  Read the number of elements as a vbr6.
197       unsigned NumElts = ReadVBR(6);
198
199       // Get the element encoding.
200       assert(i+2 == e && "array op not second to last?");
201       const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
202
203       // Read all the elements.
204       for (; NumElts; --NumElts)
205         Vals.push_back(readAbbreviatedField(*this, EltEnc));
206       continue;
207     }
208
209     assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
210     // Blob case.  Read the number of bytes as a vbr6.
211     unsigned NumElts = ReadVBR(6);
212     SkipToFourByteBoundary();  // 32-bit alignment
213
214     // Figure out where the end of this blob will be including tail padding.
215     size_t CurBitPos = GetCurrentBitNo();
216     size_t NewEnd = CurBitPos+((NumElts+3)&~3)*8;
217
218     // If this would read off the end of the bitcode file, just set the
219     // record to empty and return.
220     if (!canSkipToPos(NewEnd/8)) {
221       Vals.append(NumElts, 0);
222       NextChar = BitStream->getBitcodeBytes().getExtent();
223       break;
224     }
225
226     // Otherwise, inform the streamer that we need these bytes in memory.
227     const char *Ptr = (const char*)
228       BitStream->getBitcodeBytes().getPointer(CurBitPos/8, NumElts);
229
230     // If we can return a reference to the data, do so to avoid copying it.
231     if (Blob) {
232       *Blob = StringRef(Ptr, NumElts);
233     } else {
234       // Otherwise, unpack into Vals with zero extension.
235       for (; NumElts; --NumElts)
236         Vals.push_back((unsigned char)*Ptr++);
237     }
238     // Skip over tail padding.
239     JumpToBit(NewEnd);
240   }
241
242   return Code;
243 }
244
245
246 void BitstreamCursor::ReadAbbrevRecord() {
247   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
248   unsigned NumOpInfo = ReadVBR(5);
249   for (unsigned i = 0; i != NumOpInfo; ++i) {
250     bool IsLiteral = Read(1);
251     if (IsLiteral) {
252       Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
253       continue;
254     }
255
256     BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
257     if (BitCodeAbbrevOp::hasEncodingData(E)) {
258       uint64_t Data = ReadVBR64(5);
259
260       // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
261       // and vbr(0) as a literal zero.  This is decoded the same way, and avoids
262       // a slow path in Read() to have to handle reading zero bits.
263       if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
264           Data == 0) {
265         Abbv->Add(BitCodeAbbrevOp(0));
266         continue;
267       }
268
269       Abbv->Add(BitCodeAbbrevOp(E, Data));
270     } else
271       Abbv->Add(BitCodeAbbrevOp(E));
272   }
273   CurAbbrevs.push_back(Abbv);
274 }
275
276 bool BitstreamCursor::ReadBlockInfoBlock() {
277   // If this is the second stream to get to the block info block, skip it.
278   if (BitStream->hasBlockInfoRecords())
279     return SkipBlock();
280
281   if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
282
283   SmallVector<uint64_t, 64> Record;
284   BitstreamReader::BlockInfo *CurBlockInfo = nullptr;
285
286   // Read all the records for this module.
287   while (1) {
288     BitstreamEntry Entry = advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs);
289
290     switch (Entry.Kind) {
291     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
292     case llvm::BitstreamEntry::Error:
293       return true;
294     case llvm::BitstreamEntry::EndBlock:
295       return false;
296     case llvm::BitstreamEntry::Record:
297       // The interesting case.
298       break;
299     }
300
301     // Read abbrev records, associate them with CurBID.
302     if (Entry.ID == bitc::DEFINE_ABBREV) {
303       if (!CurBlockInfo) return true;
304       ReadAbbrevRecord();
305
306       // ReadAbbrevRecord installs the abbrev in CurAbbrevs.  Move it to the
307       // appropriate BlockInfo.
308       CurBlockInfo->Abbrevs.push_back(std::move(CurAbbrevs.back()));
309       CurAbbrevs.pop_back();
310       continue;
311     }
312
313     // Read a record.
314     Record.clear();
315     switch (readRecord(Entry.ID, Record)) {
316       default: break;  // Default behavior, ignore unknown content.
317       case bitc::BLOCKINFO_CODE_SETBID:
318         if (Record.size() < 1) return true;
319         CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
320         break;
321       case bitc::BLOCKINFO_CODE_BLOCKNAME: {
322         if (!CurBlockInfo) return true;
323         if (BitStream->isIgnoringBlockInfoNames()) break;  // Ignore name.
324         std::string Name;
325         for (unsigned i = 0, e = Record.size(); i != e; ++i)
326           Name += (char)Record[i];
327         CurBlockInfo->Name = Name;
328         break;
329       }
330       case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
331         if (!CurBlockInfo) return true;
332         if (BitStream->isIgnoringBlockInfoNames()) break;  // Ignore name.
333         std::string Name;
334         for (unsigned i = 1, e = Record.size(); i != e; ++i)
335           Name += (char)Record[i];
336         CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
337                                                            Name));
338         break;
339       }
340     }
341   }
342 }
343