1 //===- MappedBlockStream.cpp - Reads stream data from an MSF file ---------===//
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/DebugInfo/MSF/MappedBlockStream.h"
11 
12 #include "llvm/DebugInfo/MSF/IMSFFile.h"
13 #include "llvm/DebugInfo/MSF/MSFCommon.h"
14 #include "llvm/DebugInfo/MSF/MSFStreamLayout.h"
15 #include "llvm/Support/BinaryStreamError.h"
16 
17 using namespace llvm;
18 using namespace llvm::msf;
19 
20 namespace {
21 template <typename Base> class MappedBlockStreamImpl : public Base {
22 public:
23   template <typename... Args>
24   MappedBlockStreamImpl(Args &&... Params)
25       : Base(std::forward<Args>(Params)...) {}
26 };
27 }
28 
29 static void initializeFpmStreamLayout(const MSFLayout &Layout,
30                                       MSFStreamLayout &FpmLayout) {
31   uint32_t NumFpmIntervals = msf::getNumFpmIntervals(Layout);
32   support::ulittle32_t FpmBlock = Layout.SB->FreeBlockMapBlock;
33   assert(FpmBlock == 1 || FpmBlock == 2);
34   while (NumFpmIntervals > 0) {
35     FpmLayout.Blocks.push_back(FpmBlock);
36     FpmBlock += msf::getFpmIntervalLength(Layout);
37     --NumFpmIntervals;
38   }
39   FpmLayout.Length = msf::getFullFpmByteSize(Layout);
40 }
41 
42 typedef std::pair<uint32_t, uint32_t> Interval;
43 static Interval intersect(const Interval &I1, const Interval &I2) {
44   return std::make_pair(std::max(I1.first, I2.first),
45                         std::min(I1.second, I2.second));
46 }
47 
48 MappedBlockStream::MappedBlockStream(uint32_t BlockSize,
49                                      const MSFStreamLayout &Layout,
50                                      BinaryStreamRef MsfData)
51     : BlockSize(BlockSize), StreamLayout(Layout), MsfData(MsfData) {}
52 
53 std::unique_ptr<MappedBlockStream>
54 MappedBlockStream::createStream(uint32_t BlockSize,
55                                 const MSFStreamLayout &Layout,
56                                 BinaryStreamRef MsfData) {
57   return llvm::make_unique<MappedBlockStreamImpl<MappedBlockStream>>(
58       BlockSize, Layout, MsfData);
59 }
60 
61 std::unique_ptr<MappedBlockStream> MappedBlockStream::createIndexedStream(
62     const MSFLayout &Layout, BinaryStreamRef MsfData, uint32_t StreamIndex) {
63   assert(StreamIndex < Layout.StreamMap.size() && "Invalid stream index");
64   MSFStreamLayout SL;
65   SL.Blocks = Layout.StreamMap[StreamIndex];
66   SL.Length = Layout.StreamSizes[StreamIndex];
67   return llvm::make_unique<MappedBlockStreamImpl<MappedBlockStream>>(
68       Layout.SB->BlockSize, SL, MsfData);
69 }
70 
71 std::unique_ptr<MappedBlockStream>
72 MappedBlockStream::createDirectoryStream(const MSFLayout &Layout,
73                                          BinaryStreamRef MsfData) {
74   MSFStreamLayout SL;
75   SL.Blocks = Layout.DirectoryBlocks;
76   SL.Length = Layout.SB->NumDirectoryBytes;
77   return createStream(Layout.SB->BlockSize, SL, MsfData);
78 }
79 
80 std::unique_ptr<MappedBlockStream>
81 MappedBlockStream::createFpmStream(const MSFLayout &Layout,
82                                    BinaryStreamRef MsfData) {
83   MSFStreamLayout SL;
84   initializeFpmStreamLayout(Layout, SL);
85   return createStream(Layout.SB->BlockSize, SL, MsfData);
86 }
87 
88 Error MappedBlockStream::readBytes(uint32_t Offset, uint32_t Size,
89                                    ArrayRef<uint8_t> &Buffer) {
90   // Make sure we aren't trying to read beyond the end of the stream.
91   if (auto EC = checkOffset(Offset, Size))
92     return EC;
93 
94   if (tryReadContiguously(Offset, Size, Buffer))
95     return Error::success();
96 
97   auto CacheIter = CacheMap.find(Offset);
98   if (CacheIter != CacheMap.end()) {
99     // Try to find an alloc that was large enough for this request.
100     for (auto &Entry : CacheIter->second) {
101       if (Entry.size() >= Size) {
102         Buffer = Entry.slice(0, Size);
103         return Error::success();
104       }
105     }
106   }
107 
108   // We couldn't find a buffer that started at the correct offset (the most
109   // common scenario).  Try to see if there is a buffer that starts at some
110   // other offset but overlaps the desired range.
111   for (auto &CacheItem : CacheMap) {
112     Interval RequestExtent = std::make_pair(Offset, Offset + Size);
113 
114     // We already checked this one on the fast path above.
115     if (CacheItem.first == Offset)
116       continue;
117     // If the initial extent of the cached item is beyond the ending extent
118     // of the request, there is no overlap.
119     if (CacheItem.first >= Offset + Size)
120       continue;
121 
122     // We really only have to check the last item in the list, since we append
123     // in order of increasing length.
124     if (CacheItem.second.empty())
125       continue;
126 
127     auto CachedAlloc = CacheItem.second.back();
128     // If the initial extent of the request is beyond the ending extent of
129     // the cached item, there is no overlap.
130     Interval CachedExtent =
131         std::make_pair(CacheItem.first, CacheItem.first + CachedAlloc.size());
132     if (RequestExtent.first >= CachedExtent.first + CachedExtent.second)
133       continue;
134 
135     Interval Intersection = intersect(CachedExtent, RequestExtent);
136     // Only use this if the entire request extent is contained in the cached
137     // extent.
138     if (Intersection != RequestExtent)
139       continue;
140 
141     uint32_t CacheRangeOffset =
142         AbsoluteDifference(CachedExtent.first, Intersection.first);
143     Buffer = CachedAlloc.slice(CacheRangeOffset, Size);
144     return Error::success();
145   }
146 
147   // Otherwise allocate a large enough buffer in the pool, memcpy the data
148   // into it, and return an ArrayRef to that.  Do not touch existing pool
149   // allocations, as existing clients may be holding a pointer which must
150   // not be invalidated.
151   uint8_t *WriteBuffer = static_cast<uint8_t *>(Pool.Allocate(Size, 8));
152   if (auto EC = readBytes(Offset, MutableArrayRef<uint8_t>(WriteBuffer, Size)))
153     return EC;
154 
155   if (CacheIter != CacheMap.end()) {
156     CacheIter->second.emplace_back(WriteBuffer, Size);
157   } else {
158     std::vector<CacheEntry> List;
159     List.emplace_back(WriteBuffer, Size);
160     CacheMap.insert(std::make_pair(Offset, List));
161   }
162   Buffer = ArrayRef<uint8_t>(WriteBuffer, Size);
163   return Error::success();
164 }
165 
166 Error MappedBlockStream::readLongestContiguousChunk(uint32_t Offset,
167                                                     ArrayRef<uint8_t> &Buffer) {
168   // Make sure we aren't trying to read beyond the end of the stream.
169   if (auto EC = checkOffset(Offset, 1))
170     return EC;
171 
172   uint32_t First = Offset / BlockSize;
173   uint32_t Last = First;
174 
175   while (Last < getNumBlocks() - 1) {
176     if (StreamLayout.Blocks[Last] != StreamLayout.Blocks[Last + 1] - 1)
177       break;
178     ++Last;
179   }
180 
181   uint32_t OffsetInFirstBlock = Offset % BlockSize;
182   uint32_t BytesFromFirstBlock = BlockSize - OffsetInFirstBlock;
183   uint32_t BlockSpan = Last - First + 1;
184   uint32_t ByteSpan = BytesFromFirstBlock + (BlockSpan - 1) * BlockSize;
185 
186   ArrayRef<uint8_t> BlockData;
187   uint32_t MsfOffset = blockToOffset(StreamLayout.Blocks[First], BlockSize);
188   if (auto EC = MsfData.readBytes(MsfOffset, BlockSize, BlockData))
189     return EC;
190 
191   BlockData = BlockData.drop_front(OffsetInFirstBlock);
192   Buffer = ArrayRef<uint8_t>(BlockData.data(), ByteSpan);
193   return Error::success();
194 }
195 
196 uint32_t MappedBlockStream::getLength() { return StreamLayout.Length; }
197 
198 bool MappedBlockStream::tryReadContiguously(uint32_t Offset, uint32_t Size,
199                                             ArrayRef<uint8_t> &Buffer) {
200   if (Size == 0) {
201     Buffer = ArrayRef<uint8_t>();
202     return true;
203   }
204   // Attempt to fulfill the request with a reference directly into the stream.
205   // This can work even if the request crosses a block boundary, provided that
206   // all subsequent blocks are contiguous.  For example, a 10k read with a 4k
207   // block size can be filled with a reference if, from the starting offset,
208   // 3 blocks in a row are contiguous.
209   uint32_t BlockNum = Offset / BlockSize;
210   uint32_t OffsetInBlock = Offset % BlockSize;
211   uint32_t BytesFromFirstBlock = std::min(Size, BlockSize - OffsetInBlock);
212   uint32_t NumAdditionalBlocks =
213       llvm::alignTo(Size - BytesFromFirstBlock, BlockSize) / BlockSize;
214 
215   uint32_t RequiredContiguousBlocks = NumAdditionalBlocks + 1;
216   uint32_t E = StreamLayout.Blocks[BlockNum];
217   for (uint32_t I = 0; I < RequiredContiguousBlocks; ++I, ++E) {
218     if (StreamLayout.Blocks[I + BlockNum] != E)
219       return false;
220   }
221 
222   // Read out the entire block where the requested offset starts.  Then drop
223   // bytes from the beginning so that the actual starting byte lines up with
224   // the requested starting byte.  Then, since we know this is a contiguous
225   // cross-block span, explicitly resize the ArrayRef to cover the entire
226   // request length.
227   ArrayRef<uint8_t> BlockData;
228   uint32_t FirstBlockAddr = StreamLayout.Blocks[BlockNum];
229   uint32_t MsfOffset = blockToOffset(FirstBlockAddr, BlockSize);
230   if (auto EC = MsfData.readBytes(MsfOffset, BlockSize, BlockData)) {
231     consumeError(std::move(EC));
232     return false;
233   }
234   BlockData = BlockData.drop_front(OffsetInBlock);
235   Buffer = ArrayRef<uint8_t>(BlockData.data(), Size);
236   return true;
237 }
238 
239 Error MappedBlockStream::readBytes(uint32_t Offset,
240                                    MutableArrayRef<uint8_t> Buffer) {
241   uint32_t BlockNum = Offset / BlockSize;
242   uint32_t OffsetInBlock = Offset % BlockSize;
243 
244   // Make sure we aren't trying to read beyond the end of the stream.
245   if (auto EC = checkOffset(Offset, Buffer.size()))
246     return EC;
247 
248   uint32_t BytesLeft = Buffer.size();
249   uint32_t BytesWritten = 0;
250   uint8_t *WriteBuffer = Buffer.data();
251   while (BytesLeft > 0) {
252     uint32_t StreamBlockAddr = StreamLayout.Blocks[BlockNum];
253 
254     ArrayRef<uint8_t> BlockData;
255     uint32_t Offset = blockToOffset(StreamBlockAddr, BlockSize);
256     if (auto EC = MsfData.readBytes(Offset, BlockSize, BlockData))
257       return EC;
258 
259     const uint8_t *ChunkStart = BlockData.data() + OffsetInBlock;
260     uint32_t BytesInChunk = std::min(BytesLeft, BlockSize - OffsetInBlock);
261     ::memcpy(WriteBuffer + BytesWritten, ChunkStart, BytesInChunk);
262 
263     BytesWritten += BytesInChunk;
264     BytesLeft -= BytesInChunk;
265     ++BlockNum;
266     OffsetInBlock = 0;
267   }
268 
269   return Error::success();
270 }
271 
272 uint32_t MappedBlockStream::getNumBytesCopied() const {
273   return static_cast<uint32_t>(Pool.getBytesAllocated());
274 }
275 
276 void MappedBlockStream::invalidateCache() { CacheMap.shrink_and_clear(); }
277 
278 void MappedBlockStream::fixCacheAfterWrite(uint32_t Offset,
279                                            ArrayRef<uint8_t> Data) const {
280   // If this write overlapped a read which previously came from the pool,
281   // someone may still be holding a pointer to that alloc which is now invalid.
282   // Compute the overlapping range and update the cache entry, so any
283   // outstanding buffers are automatically updated.
284   for (const auto &MapEntry : CacheMap) {
285     // If the end of the written extent precedes the beginning of the cached
286     // extent, ignore this map entry.
287     if (Offset + Data.size() < MapEntry.first)
288       continue;
289     for (const auto &Alloc : MapEntry.second) {
290       // If the end of the cached extent precedes the beginning of the written
291       // extent, ignore this alloc.
292       if (MapEntry.first + Alloc.size() < Offset)
293         continue;
294 
295       // If we get here, they are guaranteed to overlap.
296       Interval WriteInterval = std::make_pair(Offset, Offset + Data.size());
297       Interval CachedInterval =
298           std::make_pair(MapEntry.first, MapEntry.first + Alloc.size());
299       // If they overlap, we need to write the new data into the overlapping
300       // range.
301       auto Intersection = intersect(WriteInterval, CachedInterval);
302       assert(Intersection.first <= Intersection.second);
303 
304       uint32_t Length = Intersection.second - Intersection.first;
305       uint32_t SrcOffset =
306           AbsoluteDifference(WriteInterval.first, Intersection.first);
307       uint32_t DestOffset =
308           AbsoluteDifference(CachedInterval.first, Intersection.first);
309       ::memcpy(Alloc.data() + DestOffset, Data.data() + SrcOffset, Length);
310     }
311   }
312 }
313 
314 WritableMappedBlockStream::WritableMappedBlockStream(
315     uint32_t BlockSize, const MSFStreamLayout &Layout,
316     WritableBinaryStreamRef MsfData)
317     : ReadInterface(BlockSize, Layout, MsfData), WriteInterface(MsfData) {}
318 
319 std::unique_ptr<WritableMappedBlockStream>
320 WritableMappedBlockStream::createStream(uint32_t BlockSize,
321                                         const MSFStreamLayout &Layout,
322                                         WritableBinaryStreamRef MsfData) {
323   return llvm::make_unique<MappedBlockStreamImpl<WritableMappedBlockStream>>(
324       BlockSize, Layout, MsfData);
325 }
326 
327 std::unique_ptr<WritableMappedBlockStream>
328 WritableMappedBlockStream::createIndexedStream(const MSFLayout &Layout,
329                                                WritableBinaryStreamRef MsfData,
330                                                uint32_t StreamIndex) {
331   assert(StreamIndex < Layout.StreamMap.size() && "Invalid stream index");
332   MSFStreamLayout SL;
333   SL.Blocks = Layout.StreamMap[StreamIndex];
334   SL.Length = Layout.StreamSizes[StreamIndex];
335   return createStream(Layout.SB->BlockSize, SL, MsfData);
336 }
337 
338 std::unique_ptr<WritableMappedBlockStream>
339 WritableMappedBlockStream::createDirectoryStream(
340     const MSFLayout &Layout, WritableBinaryStreamRef MsfData) {
341   MSFStreamLayout SL;
342   SL.Blocks = Layout.DirectoryBlocks;
343   SL.Length = Layout.SB->NumDirectoryBytes;
344   return createStream(Layout.SB->BlockSize, SL, MsfData);
345 }
346 
347 std::unique_ptr<WritableMappedBlockStream>
348 WritableMappedBlockStream::createFpmStream(const MSFLayout &Layout,
349                                            WritableBinaryStreamRef MsfData) {
350   MSFStreamLayout SL;
351   initializeFpmStreamLayout(Layout, SL);
352   return createStream(Layout.SB->BlockSize, SL, MsfData);
353 }
354 
355 Error WritableMappedBlockStream::readBytes(uint32_t Offset, uint32_t Size,
356                                            ArrayRef<uint8_t> &Buffer) {
357   return ReadInterface.readBytes(Offset, Size, Buffer);
358 }
359 
360 Error WritableMappedBlockStream::readLongestContiguousChunk(
361     uint32_t Offset, ArrayRef<uint8_t> &Buffer) {
362   return ReadInterface.readLongestContiguousChunk(Offset, Buffer);
363 }
364 
365 uint32_t WritableMappedBlockStream::getLength() {
366   return ReadInterface.getLength();
367 }
368 
369 Error WritableMappedBlockStream::writeBytes(uint32_t Offset,
370                                             ArrayRef<uint8_t> Buffer) {
371   // Make sure we aren't trying to write beyond the end of the stream.
372   if (auto EC = checkOffset(Offset, Buffer.size()))
373     return EC;
374 
375   uint32_t BlockNum = Offset / getBlockSize();
376   uint32_t OffsetInBlock = Offset % getBlockSize();
377 
378   uint32_t BytesLeft = Buffer.size();
379   uint32_t BytesWritten = 0;
380   while (BytesLeft > 0) {
381     uint32_t StreamBlockAddr = getStreamLayout().Blocks[BlockNum];
382     uint32_t BytesToWriteInChunk =
383         std::min(BytesLeft, getBlockSize() - OffsetInBlock);
384 
385     const uint8_t *Chunk = Buffer.data() + BytesWritten;
386     ArrayRef<uint8_t> ChunkData(Chunk, BytesToWriteInChunk);
387     uint32_t MsfOffset = blockToOffset(StreamBlockAddr, getBlockSize());
388     MsfOffset += OffsetInBlock;
389     if (auto EC = WriteInterface.writeBytes(MsfOffset, ChunkData))
390       return EC;
391 
392     BytesLeft -= BytesToWriteInChunk;
393     BytesWritten += BytesToWriteInChunk;
394     ++BlockNum;
395     OffsetInBlock = 0;
396   }
397 
398   ReadInterface.fixCacheAfterWrite(Offset, Buffer);
399 
400   return Error::success();
401 }
402 
403 Error WritableMappedBlockStream::commit() { return WriteInterface.commit(); }
404