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