1*0b57cec5SDimitry Andric //===- MappedBlockStream.cpp - Reads stream data from an MSF file ---------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric 
9*0b57cec5SDimitry Andric #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
10*0b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
11*0b57cec5SDimitry Andric #include "llvm/DebugInfo/MSF/MSFCommon.h"
12*0b57cec5SDimitry Andric #include "llvm/Support/BinaryStreamWriter.h"
13*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
14*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
15*0b57cec5SDimitry Andric #include <algorithm>
16*0b57cec5SDimitry Andric #include <cassert>
17*0b57cec5SDimitry Andric #include <cstdint>
18*0b57cec5SDimitry Andric #include <cstring>
19*0b57cec5SDimitry Andric #include <utility>
20*0b57cec5SDimitry Andric #include <vector>
21*0b57cec5SDimitry Andric 
22*0b57cec5SDimitry Andric using namespace llvm;
23*0b57cec5SDimitry Andric using namespace llvm::msf;
24*0b57cec5SDimitry Andric 
25*0b57cec5SDimitry Andric namespace {
26*0b57cec5SDimitry Andric 
27*0b57cec5SDimitry Andric template <typename Base> class MappedBlockStreamImpl : public Base {
28*0b57cec5SDimitry Andric public:
29*0b57cec5SDimitry Andric   template <typename... Args>
MappedBlockStreamImpl(Args &&...Params)30*0b57cec5SDimitry Andric   MappedBlockStreamImpl(Args &&... Params)
31*0b57cec5SDimitry Andric       : Base(std::forward<Args>(Params)...) {}
32*0b57cec5SDimitry Andric };
33*0b57cec5SDimitry Andric 
34*0b57cec5SDimitry Andric } // end anonymous namespace
35*0b57cec5SDimitry Andric 
36349cc55cSDimitry Andric using Interval = std::pair<uint64_t, uint64_t>;
37*0b57cec5SDimitry Andric 
intersect(const Interval & I1,const Interval & I2)38*0b57cec5SDimitry Andric static Interval intersect(const Interval &I1, const Interval &I2) {
39*0b57cec5SDimitry Andric   return std::make_pair(std::max(I1.first, I2.first),
40*0b57cec5SDimitry Andric                         std::min(I1.second, I2.second));
41*0b57cec5SDimitry Andric }
42*0b57cec5SDimitry Andric 
MappedBlockStream(uint32_t BlockSize,const MSFStreamLayout & Layout,BinaryStreamRef MsfData,BumpPtrAllocator & Allocator)43*0b57cec5SDimitry Andric MappedBlockStream::MappedBlockStream(uint32_t BlockSize,
44*0b57cec5SDimitry Andric                                      const MSFStreamLayout &Layout,
45*0b57cec5SDimitry Andric                                      BinaryStreamRef MsfData,
46*0b57cec5SDimitry Andric                                      BumpPtrAllocator &Allocator)
47*0b57cec5SDimitry Andric     : BlockSize(BlockSize), StreamLayout(Layout), MsfData(MsfData),
48*0b57cec5SDimitry Andric       Allocator(Allocator) {}
49*0b57cec5SDimitry Andric 
createStream(uint32_t BlockSize,const MSFStreamLayout & Layout,BinaryStreamRef MsfData,BumpPtrAllocator & Allocator)50*0b57cec5SDimitry Andric std::unique_ptr<MappedBlockStream> MappedBlockStream::createStream(
51*0b57cec5SDimitry Andric     uint32_t BlockSize, const MSFStreamLayout &Layout, BinaryStreamRef MsfData,
52*0b57cec5SDimitry Andric     BumpPtrAllocator &Allocator) {
538bcb0991SDimitry Andric   return std::make_unique<MappedBlockStreamImpl<MappedBlockStream>>(
54*0b57cec5SDimitry Andric       BlockSize, Layout, MsfData, Allocator);
55*0b57cec5SDimitry Andric }
56*0b57cec5SDimitry Andric 
createIndexedStream(const MSFLayout & Layout,BinaryStreamRef MsfData,uint32_t StreamIndex,BumpPtrAllocator & Allocator)57*0b57cec5SDimitry Andric std::unique_ptr<MappedBlockStream> MappedBlockStream::createIndexedStream(
58*0b57cec5SDimitry Andric     const MSFLayout &Layout, BinaryStreamRef MsfData, uint32_t StreamIndex,
59*0b57cec5SDimitry Andric     BumpPtrAllocator &Allocator) {
60*0b57cec5SDimitry Andric   assert(StreamIndex < Layout.StreamMap.size() && "Invalid stream index");
61*0b57cec5SDimitry Andric   MSFStreamLayout SL;
62*0b57cec5SDimitry Andric   SL.Blocks = Layout.StreamMap[StreamIndex];
63*0b57cec5SDimitry Andric   SL.Length = Layout.StreamSizes[StreamIndex];
648bcb0991SDimitry Andric   return std::make_unique<MappedBlockStreamImpl<MappedBlockStream>>(
65*0b57cec5SDimitry Andric       Layout.SB->BlockSize, SL, MsfData, Allocator);
66*0b57cec5SDimitry Andric }
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric std::unique_ptr<MappedBlockStream>
createDirectoryStream(const MSFLayout & Layout,BinaryStreamRef MsfData,BumpPtrAllocator & Allocator)69*0b57cec5SDimitry Andric MappedBlockStream::createDirectoryStream(const MSFLayout &Layout,
70*0b57cec5SDimitry Andric                                          BinaryStreamRef MsfData,
71*0b57cec5SDimitry Andric                                          BumpPtrAllocator &Allocator) {
72*0b57cec5SDimitry Andric   MSFStreamLayout SL;
73*0b57cec5SDimitry Andric   SL.Blocks = Layout.DirectoryBlocks;
74*0b57cec5SDimitry Andric   SL.Length = Layout.SB->NumDirectoryBytes;
75*0b57cec5SDimitry Andric   return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
76*0b57cec5SDimitry Andric }
77*0b57cec5SDimitry Andric 
78*0b57cec5SDimitry Andric std::unique_ptr<MappedBlockStream>
createFpmStream(const MSFLayout & Layout,BinaryStreamRef MsfData,BumpPtrAllocator & Allocator)79*0b57cec5SDimitry Andric MappedBlockStream::createFpmStream(const MSFLayout &Layout,
80*0b57cec5SDimitry Andric                                    BinaryStreamRef MsfData,
81*0b57cec5SDimitry Andric                                    BumpPtrAllocator &Allocator) {
82*0b57cec5SDimitry Andric   MSFStreamLayout SL(getFpmStreamLayout(Layout));
83*0b57cec5SDimitry Andric   return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
84*0b57cec5SDimitry Andric }
85*0b57cec5SDimitry Andric 
readBytes(uint64_t Offset,uint64_t Size,ArrayRef<uint8_t> & Buffer)86349cc55cSDimitry Andric Error MappedBlockStream::readBytes(uint64_t Offset, uint64_t Size,
87*0b57cec5SDimitry Andric                                    ArrayRef<uint8_t> &Buffer) {
88*0b57cec5SDimitry Andric   // Make sure we aren't trying to read beyond the end of the stream.
89*0b57cec5SDimitry Andric   if (auto EC = checkOffsetForRead(Offset, Size))
90*0b57cec5SDimitry Andric     return EC;
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric   if (tryReadContiguously(Offset, Size, Buffer))
93*0b57cec5SDimitry Andric     return Error::success();
94*0b57cec5SDimitry Andric 
95*0b57cec5SDimitry Andric   auto CacheIter = CacheMap.find(Offset);
96*0b57cec5SDimitry Andric   if (CacheIter != CacheMap.end()) {
97*0b57cec5SDimitry Andric     // Try to find an alloc that was large enough for this request.
98*0b57cec5SDimitry Andric     for (auto &Entry : CacheIter->second) {
99*0b57cec5SDimitry Andric       if (Entry.size() >= Size) {
100*0b57cec5SDimitry Andric         Buffer = Entry.slice(0, Size);
101*0b57cec5SDimitry Andric         return Error::success();
102*0b57cec5SDimitry Andric       }
103*0b57cec5SDimitry Andric     }
104*0b57cec5SDimitry Andric   }
105*0b57cec5SDimitry Andric 
106*0b57cec5SDimitry Andric   // We couldn't find a buffer that started at the correct offset (the most
107*0b57cec5SDimitry Andric   // common scenario).  Try to see if there is a buffer that starts at some
108*0b57cec5SDimitry Andric   // other offset but overlaps the desired range.
109*0b57cec5SDimitry Andric   for (auto &CacheItem : CacheMap) {
110*0b57cec5SDimitry Andric     Interval RequestExtent = std::make_pair(Offset, Offset + Size);
111*0b57cec5SDimitry Andric 
112*0b57cec5SDimitry Andric     // We already checked this one on the fast path above.
113*0b57cec5SDimitry Andric     if (CacheItem.first == Offset)
114*0b57cec5SDimitry Andric       continue;
115*0b57cec5SDimitry Andric     // If the initial extent of the cached item is beyond the ending extent
116*0b57cec5SDimitry Andric     // of the request, there is no overlap.
117*0b57cec5SDimitry Andric     if (CacheItem.first >= Offset + Size)
118*0b57cec5SDimitry Andric       continue;
119*0b57cec5SDimitry Andric 
120*0b57cec5SDimitry Andric     // We really only have to check the last item in the list, since we append
121*0b57cec5SDimitry Andric     // in order of increasing length.
122*0b57cec5SDimitry Andric     if (CacheItem.second.empty())
123*0b57cec5SDimitry Andric       continue;
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric     auto CachedAlloc = CacheItem.second.back();
126*0b57cec5SDimitry Andric     // If the initial extent of the request is beyond the ending extent of
127*0b57cec5SDimitry Andric     // the cached item, there is no overlap.
128*0b57cec5SDimitry Andric     Interval CachedExtent =
129*0b57cec5SDimitry Andric         std::make_pair(CacheItem.first, CacheItem.first + CachedAlloc.size());
130*0b57cec5SDimitry Andric     if (RequestExtent.first >= CachedExtent.first + CachedExtent.second)
131*0b57cec5SDimitry Andric       continue;
132*0b57cec5SDimitry Andric 
133*0b57cec5SDimitry Andric     Interval Intersection = intersect(CachedExtent, RequestExtent);
134*0b57cec5SDimitry Andric     // Only use this if the entire request extent is contained in the cached
135*0b57cec5SDimitry Andric     // extent.
136*0b57cec5SDimitry Andric     if (Intersection != RequestExtent)
137*0b57cec5SDimitry Andric       continue;
138*0b57cec5SDimitry Andric 
139349cc55cSDimitry Andric     uint64_t CacheRangeOffset =
140*0b57cec5SDimitry Andric         AbsoluteDifference(CachedExtent.first, Intersection.first);
141*0b57cec5SDimitry Andric     Buffer = CachedAlloc.slice(CacheRangeOffset, Size);
142*0b57cec5SDimitry Andric     return Error::success();
143*0b57cec5SDimitry Andric   }
144*0b57cec5SDimitry Andric 
145*0b57cec5SDimitry Andric   // Otherwise allocate a large enough buffer in the pool, memcpy the data
146*0b57cec5SDimitry Andric   // into it, and return an ArrayRef to that.  Do not touch existing pool
147*0b57cec5SDimitry Andric   // allocations, as existing clients may be holding a pointer which must
148*0b57cec5SDimitry Andric   // not be invalidated.
149*0b57cec5SDimitry Andric   uint8_t *WriteBuffer = static_cast<uint8_t *>(Allocator.Allocate(Size, 8));
150*0b57cec5SDimitry Andric   if (auto EC = readBytes(Offset, MutableArrayRef<uint8_t>(WriteBuffer, Size)))
151*0b57cec5SDimitry Andric     return EC;
152*0b57cec5SDimitry Andric 
153*0b57cec5SDimitry Andric   if (CacheIter != CacheMap.end()) {
154*0b57cec5SDimitry Andric     CacheIter->second.emplace_back(WriteBuffer, Size);
155*0b57cec5SDimitry Andric   } else {
156*0b57cec5SDimitry Andric     std::vector<CacheEntry> List;
157*0b57cec5SDimitry Andric     List.emplace_back(WriteBuffer, Size);
158*0b57cec5SDimitry Andric     CacheMap.insert(std::make_pair(Offset, List));
159*0b57cec5SDimitry Andric   }
160*0b57cec5SDimitry Andric   Buffer = ArrayRef<uint8_t>(WriteBuffer, Size);
161*0b57cec5SDimitry Andric   return Error::success();
162*0b57cec5SDimitry Andric }
163*0b57cec5SDimitry Andric 
readLongestContiguousChunk(uint64_t Offset,ArrayRef<uint8_t> & Buffer)164349cc55cSDimitry Andric Error MappedBlockStream::readLongestContiguousChunk(uint64_t Offset,
165*0b57cec5SDimitry Andric                                                     ArrayRef<uint8_t> &Buffer) {
166*0b57cec5SDimitry Andric   // Make sure we aren't trying to read beyond the end of the stream.
167*0b57cec5SDimitry Andric   if (auto EC = checkOffsetForRead(Offset, 1))
168*0b57cec5SDimitry Andric     return EC;
169*0b57cec5SDimitry Andric 
170349cc55cSDimitry Andric   uint64_t First = Offset / BlockSize;
171349cc55cSDimitry Andric   uint64_t Last = First;
172*0b57cec5SDimitry Andric 
173*0b57cec5SDimitry Andric   while (Last < getNumBlocks() - 1) {
174*0b57cec5SDimitry Andric     if (StreamLayout.Blocks[Last] != StreamLayout.Blocks[Last + 1] - 1)
175*0b57cec5SDimitry Andric       break;
176*0b57cec5SDimitry Andric     ++Last;
177*0b57cec5SDimitry Andric   }
178*0b57cec5SDimitry Andric 
179349cc55cSDimitry Andric   uint64_t OffsetInFirstBlock = Offset % BlockSize;
180349cc55cSDimitry Andric   uint64_t BytesFromFirstBlock = BlockSize - OffsetInFirstBlock;
181349cc55cSDimitry Andric   uint64_t BlockSpan = Last - First + 1;
182349cc55cSDimitry Andric   uint64_t ByteSpan = BytesFromFirstBlock + (BlockSpan - 1) * BlockSize;
183*0b57cec5SDimitry Andric 
184*0b57cec5SDimitry Andric   ArrayRef<uint8_t> BlockData;
185349cc55cSDimitry Andric   uint64_t MsfOffset = blockToOffset(StreamLayout.Blocks[First], BlockSize);
186*0b57cec5SDimitry Andric   if (auto EC = MsfData.readBytes(MsfOffset, BlockSize, BlockData))
187*0b57cec5SDimitry Andric     return EC;
188*0b57cec5SDimitry Andric 
189*0b57cec5SDimitry Andric   BlockData = BlockData.drop_front(OffsetInFirstBlock);
190*0b57cec5SDimitry Andric   Buffer = ArrayRef<uint8_t>(BlockData.data(), ByteSpan);
191*0b57cec5SDimitry Andric   return Error::success();
192*0b57cec5SDimitry Andric }
193*0b57cec5SDimitry Andric 
getLength()194349cc55cSDimitry Andric uint64_t MappedBlockStream::getLength() { return StreamLayout.Length; }
195*0b57cec5SDimitry Andric 
tryReadContiguously(uint64_t Offset,uint64_t Size,ArrayRef<uint8_t> & Buffer)196349cc55cSDimitry Andric bool MappedBlockStream::tryReadContiguously(uint64_t Offset, uint64_t Size,
197*0b57cec5SDimitry Andric                                             ArrayRef<uint8_t> &Buffer) {
198*0b57cec5SDimitry Andric   if (Size == 0) {
199*0b57cec5SDimitry Andric     Buffer = ArrayRef<uint8_t>();
200*0b57cec5SDimitry Andric     return true;
201*0b57cec5SDimitry Andric   }
202*0b57cec5SDimitry Andric   // Attempt to fulfill the request with a reference directly into the stream.
203*0b57cec5SDimitry Andric   // This can work even if the request crosses a block boundary, provided that
204*0b57cec5SDimitry Andric   // all subsequent blocks are contiguous.  For example, a 10k read with a 4k
205*0b57cec5SDimitry Andric   // block size can be filled with a reference if, from the starting offset,
206*0b57cec5SDimitry Andric   // 3 blocks in a row are contiguous.
207349cc55cSDimitry Andric   uint64_t BlockNum = Offset / BlockSize;
208349cc55cSDimitry Andric   uint64_t OffsetInBlock = Offset % BlockSize;
209349cc55cSDimitry Andric   uint64_t BytesFromFirstBlock = std::min(Size, BlockSize - OffsetInBlock);
210349cc55cSDimitry Andric   uint64_t NumAdditionalBlocks =
211*0b57cec5SDimitry Andric       alignTo(Size - BytesFromFirstBlock, BlockSize) / BlockSize;
212*0b57cec5SDimitry Andric 
213349cc55cSDimitry Andric   uint64_t RequiredContiguousBlocks = NumAdditionalBlocks + 1;
214349cc55cSDimitry Andric   uint64_t E = StreamLayout.Blocks[BlockNum];
215349cc55cSDimitry Andric   for (uint64_t I = 0; I < RequiredContiguousBlocks; ++I, ++E) {
216*0b57cec5SDimitry Andric     if (StreamLayout.Blocks[I + BlockNum] != E)
217*0b57cec5SDimitry Andric       return false;
218*0b57cec5SDimitry Andric   }
219*0b57cec5SDimitry Andric 
220*0b57cec5SDimitry Andric   // Read out the entire block where the requested offset starts.  Then drop
221*0b57cec5SDimitry Andric   // bytes from the beginning so that the actual starting byte lines up with
222*0b57cec5SDimitry Andric   // the requested starting byte.  Then, since we know this is a contiguous
223*0b57cec5SDimitry Andric   // cross-block span, explicitly resize the ArrayRef to cover the entire
224*0b57cec5SDimitry Andric   // request length.
225*0b57cec5SDimitry Andric   ArrayRef<uint8_t> BlockData;
226349cc55cSDimitry Andric   uint64_t FirstBlockAddr = StreamLayout.Blocks[BlockNum];
227349cc55cSDimitry Andric   uint64_t MsfOffset = blockToOffset(FirstBlockAddr, BlockSize);
228*0b57cec5SDimitry Andric   if (auto EC = MsfData.readBytes(MsfOffset, BlockSize, BlockData)) {
229*0b57cec5SDimitry Andric     consumeError(std::move(EC));
230*0b57cec5SDimitry Andric     return false;
231*0b57cec5SDimitry Andric   }
232*0b57cec5SDimitry Andric   BlockData = BlockData.drop_front(OffsetInBlock);
233*0b57cec5SDimitry Andric   Buffer = ArrayRef<uint8_t>(BlockData.data(), Size);
234*0b57cec5SDimitry Andric   return true;
235*0b57cec5SDimitry Andric }
236*0b57cec5SDimitry Andric 
readBytes(uint64_t Offset,MutableArrayRef<uint8_t> Buffer)237349cc55cSDimitry Andric Error MappedBlockStream::readBytes(uint64_t Offset,
238*0b57cec5SDimitry Andric                                    MutableArrayRef<uint8_t> Buffer) {
239349cc55cSDimitry Andric   uint64_t BlockNum = Offset / BlockSize;
240349cc55cSDimitry Andric   uint64_t OffsetInBlock = Offset % BlockSize;
241*0b57cec5SDimitry Andric 
242*0b57cec5SDimitry Andric   // Make sure we aren't trying to read beyond the end of the stream.
243*0b57cec5SDimitry Andric   if (auto EC = checkOffsetForRead(Offset, Buffer.size()))
244*0b57cec5SDimitry Andric     return EC;
245*0b57cec5SDimitry Andric 
246349cc55cSDimitry Andric   uint64_t BytesLeft = Buffer.size();
247349cc55cSDimitry Andric   uint64_t BytesWritten = 0;
248*0b57cec5SDimitry Andric   uint8_t *WriteBuffer = Buffer.data();
249*0b57cec5SDimitry Andric   while (BytesLeft > 0) {
250349cc55cSDimitry Andric     uint64_t StreamBlockAddr = StreamLayout.Blocks[BlockNum];
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric     ArrayRef<uint8_t> BlockData;
253349cc55cSDimitry Andric     uint64_t Offset = blockToOffset(StreamBlockAddr, BlockSize);
254*0b57cec5SDimitry Andric     if (auto EC = MsfData.readBytes(Offset, BlockSize, BlockData))
255*0b57cec5SDimitry Andric       return EC;
256*0b57cec5SDimitry Andric 
257*0b57cec5SDimitry Andric     const uint8_t *ChunkStart = BlockData.data() + OffsetInBlock;
258349cc55cSDimitry Andric     uint64_t BytesInChunk = std::min(BytesLeft, BlockSize - OffsetInBlock);
259*0b57cec5SDimitry Andric     ::memcpy(WriteBuffer + BytesWritten, ChunkStart, BytesInChunk);
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric     BytesWritten += BytesInChunk;
262*0b57cec5SDimitry Andric     BytesLeft -= BytesInChunk;
263*0b57cec5SDimitry Andric     ++BlockNum;
264*0b57cec5SDimitry Andric     OffsetInBlock = 0;
265*0b57cec5SDimitry Andric   }
266*0b57cec5SDimitry Andric 
267*0b57cec5SDimitry Andric   return Error::success();
268*0b57cec5SDimitry Andric }
269*0b57cec5SDimitry Andric 
invalidateCache()270*0b57cec5SDimitry Andric void MappedBlockStream::invalidateCache() { CacheMap.shrink_and_clear(); }
271*0b57cec5SDimitry Andric 
fixCacheAfterWrite(uint64_t Offset,ArrayRef<uint8_t> Data) const272349cc55cSDimitry Andric void MappedBlockStream::fixCacheAfterWrite(uint64_t Offset,
273*0b57cec5SDimitry Andric                                            ArrayRef<uint8_t> Data) const {
274*0b57cec5SDimitry Andric   // If this write overlapped a read which previously came from the pool,
275*0b57cec5SDimitry Andric   // someone may still be holding a pointer to that alloc which is now invalid.
276*0b57cec5SDimitry Andric   // Compute the overlapping range and update the cache entry, so any
277*0b57cec5SDimitry Andric   // outstanding buffers are automatically updated.
278*0b57cec5SDimitry Andric   for (const auto &MapEntry : CacheMap) {
279*0b57cec5SDimitry Andric     // If the end of the written extent precedes the beginning of the cached
280*0b57cec5SDimitry Andric     // extent, ignore this map entry.
281*0b57cec5SDimitry Andric     if (Offset + Data.size() < MapEntry.first)
282*0b57cec5SDimitry Andric       continue;
283*0b57cec5SDimitry Andric     for (const auto &Alloc : MapEntry.second) {
284*0b57cec5SDimitry Andric       // If the end of the cached extent precedes the beginning of the written
285*0b57cec5SDimitry Andric       // extent, ignore this alloc.
286*0b57cec5SDimitry Andric       if (MapEntry.first + Alloc.size() < Offset)
287*0b57cec5SDimitry Andric         continue;
288*0b57cec5SDimitry Andric 
289*0b57cec5SDimitry Andric       // If we get here, they are guaranteed to overlap.
290*0b57cec5SDimitry Andric       Interval WriteInterval = std::make_pair(Offset, Offset + Data.size());
291*0b57cec5SDimitry Andric       Interval CachedInterval =
292*0b57cec5SDimitry Andric           std::make_pair(MapEntry.first, MapEntry.first + Alloc.size());
293*0b57cec5SDimitry Andric       // If they overlap, we need to write the new data into the overlapping
294*0b57cec5SDimitry Andric       // range.
295*0b57cec5SDimitry Andric       auto Intersection = intersect(WriteInterval, CachedInterval);
296*0b57cec5SDimitry Andric       assert(Intersection.first <= Intersection.second);
297*0b57cec5SDimitry Andric 
298349cc55cSDimitry Andric       uint64_t Length = Intersection.second - Intersection.first;
299349cc55cSDimitry Andric       uint64_t SrcOffset =
300*0b57cec5SDimitry Andric           AbsoluteDifference(WriteInterval.first, Intersection.first);
301349cc55cSDimitry Andric       uint64_t DestOffset =
302*0b57cec5SDimitry Andric           AbsoluteDifference(CachedInterval.first, Intersection.first);
303*0b57cec5SDimitry Andric       ::memcpy(Alloc.data() + DestOffset, Data.data() + SrcOffset, Length);
304*0b57cec5SDimitry Andric     }
305*0b57cec5SDimitry Andric   }
306*0b57cec5SDimitry Andric }
307*0b57cec5SDimitry Andric 
WritableMappedBlockStream(uint32_t BlockSize,const MSFStreamLayout & Layout,WritableBinaryStreamRef MsfData,BumpPtrAllocator & Allocator)308*0b57cec5SDimitry Andric WritableMappedBlockStream::WritableMappedBlockStream(
309*0b57cec5SDimitry Andric     uint32_t BlockSize, const MSFStreamLayout &Layout,
310*0b57cec5SDimitry Andric     WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
311*0b57cec5SDimitry Andric     : ReadInterface(BlockSize, Layout, MsfData, Allocator),
312*0b57cec5SDimitry Andric       WriteInterface(MsfData) {}
313*0b57cec5SDimitry Andric 
314*0b57cec5SDimitry Andric std::unique_ptr<WritableMappedBlockStream>
createStream(uint32_t BlockSize,const MSFStreamLayout & Layout,WritableBinaryStreamRef MsfData,BumpPtrAllocator & Allocator)315*0b57cec5SDimitry Andric WritableMappedBlockStream::createStream(uint32_t BlockSize,
316*0b57cec5SDimitry Andric                                         const MSFStreamLayout &Layout,
317*0b57cec5SDimitry Andric                                         WritableBinaryStreamRef MsfData,
318*0b57cec5SDimitry Andric                                         BumpPtrAllocator &Allocator) {
3198bcb0991SDimitry Andric   return std::make_unique<MappedBlockStreamImpl<WritableMappedBlockStream>>(
320*0b57cec5SDimitry Andric       BlockSize, Layout, MsfData, Allocator);
321*0b57cec5SDimitry Andric }
322*0b57cec5SDimitry Andric 
323*0b57cec5SDimitry Andric std::unique_ptr<WritableMappedBlockStream>
createIndexedStream(const MSFLayout & Layout,WritableBinaryStreamRef MsfData,uint32_t StreamIndex,BumpPtrAllocator & Allocator)324*0b57cec5SDimitry Andric WritableMappedBlockStream::createIndexedStream(const MSFLayout &Layout,
325*0b57cec5SDimitry Andric                                                WritableBinaryStreamRef MsfData,
326*0b57cec5SDimitry Andric                                                uint32_t StreamIndex,
327*0b57cec5SDimitry Andric                                                BumpPtrAllocator &Allocator) {
328*0b57cec5SDimitry Andric   assert(StreamIndex < Layout.StreamMap.size() && "Invalid stream index");
329*0b57cec5SDimitry Andric   MSFStreamLayout SL;
330*0b57cec5SDimitry Andric   SL.Blocks = Layout.StreamMap[StreamIndex];
331*0b57cec5SDimitry Andric   SL.Length = Layout.StreamSizes[StreamIndex];
332*0b57cec5SDimitry Andric   return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
333*0b57cec5SDimitry Andric }
334*0b57cec5SDimitry Andric 
335*0b57cec5SDimitry Andric std::unique_ptr<WritableMappedBlockStream>
createDirectoryStream(const MSFLayout & Layout,WritableBinaryStreamRef MsfData,BumpPtrAllocator & Allocator)336*0b57cec5SDimitry Andric WritableMappedBlockStream::createDirectoryStream(
337*0b57cec5SDimitry Andric     const MSFLayout &Layout, WritableBinaryStreamRef MsfData,
338*0b57cec5SDimitry Andric     BumpPtrAllocator &Allocator) {
339*0b57cec5SDimitry Andric   MSFStreamLayout SL;
340*0b57cec5SDimitry Andric   SL.Blocks = Layout.DirectoryBlocks;
341*0b57cec5SDimitry Andric   SL.Length = Layout.SB->NumDirectoryBytes;
342*0b57cec5SDimitry Andric   return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
343*0b57cec5SDimitry Andric }
344*0b57cec5SDimitry Andric 
345*0b57cec5SDimitry Andric std::unique_ptr<WritableMappedBlockStream>
createFpmStream(const MSFLayout & Layout,WritableBinaryStreamRef MsfData,BumpPtrAllocator & Allocator,bool AltFpm)346*0b57cec5SDimitry Andric WritableMappedBlockStream::createFpmStream(const MSFLayout &Layout,
347*0b57cec5SDimitry Andric                                            WritableBinaryStreamRef MsfData,
348*0b57cec5SDimitry Andric                                            BumpPtrAllocator &Allocator,
349*0b57cec5SDimitry Andric                                            bool AltFpm) {
350*0b57cec5SDimitry Andric   // We only want to give the user a stream containing the bytes of the FPM that
351*0b57cec5SDimitry Andric   // are actually valid, but we want to initialize all of the bytes, even those
352*0b57cec5SDimitry Andric   // that come from reserved FPM blocks where the entire block is unused.  To do
353*0b57cec5SDimitry Andric   // this, we first create the full layout, which gives us a stream with all
354*0b57cec5SDimitry Andric   // bytes and all blocks, and initialize everything to 0xFF (all blocks in the
355*0b57cec5SDimitry Andric   // file are unused).  Then we create the minimal layout (which contains only a
356*0b57cec5SDimitry Andric   // subset of the bytes previously initialized), and return that to the user.
357*0b57cec5SDimitry Andric   MSFStreamLayout MinLayout(getFpmStreamLayout(Layout, false, AltFpm));
358*0b57cec5SDimitry Andric 
359*0b57cec5SDimitry Andric   MSFStreamLayout FullLayout(getFpmStreamLayout(Layout, true, AltFpm));
360*0b57cec5SDimitry Andric   auto Result =
361*0b57cec5SDimitry Andric       createStream(Layout.SB->BlockSize, FullLayout, MsfData, Allocator);
362*0b57cec5SDimitry Andric   if (!Result)
363*0b57cec5SDimitry Andric     return Result;
364*0b57cec5SDimitry Andric   std::vector<uint8_t> InitData(Layout.SB->BlockSize, 0xFF);
365*0b57cec5SDimitry Andric   BinaryStreamWriter Initializer(*Result);
366*0b57cec5SDimitry Andric   while (Initializer.bytesRemaining() > 0)
367*0b57cec5SDimitry Andric     cantFail(Initializer.writeBytes(InitData));
368*0b57cec5SDimitry Andric   return createStream(Layout.SB->BlockSize, MinLayout, MsfData, Allocator);
369*0b57cec5SDimitry Andric }
370*0b57cec5SDimitry Andric 
readBytes(uint64_t Offset,uint64_t Size,ArrayRef<uint8_t> & Buffer)371349cc55cSDimitry Andric Error WritableMappedBlockStream::readBytes(uint64_t Offset, uint64_t Size,
372*0b57cec5SDimitry Andric                                            ArrayRef<uint8_t> &Buffer) {
373*0b57cec5SDimitry Andric   return ReadInterface.readBytes(Offset, Size, Buffer);
374*0b57cec5SDimitry Andric }
375*0b57cec5SDimitry Andric 
readLongestContiguousChunk(uint64_t Offset,ArrayRef<uint8_t> & Buffer)376*0b57cec5SDimitry Andric Error WritableMappedBlockStream::readLongestContiguousChunk(
377349cc55cSDimitry Andric     uint64_t Offset, ArrayRef<uint8_t> &Buffer) {
378*0b57cec5SDimitry Andric   return ReadInterface.readLongestContiguousChunk(Offset, Buffer);
379*0b57cec5SDimitry Andric }
380*0b57cec5SDimitry Andric 
getLength()381349cc55cSDimitry Andric uint64_t WritableMappedBlockStream::getLength() {
382*0b57cec5SDimitry Andric   return ReadInterface.getLength();
383*0b57cec5SDimitry Andric }
384*0b57cec5SDimitry Andric 
writeBytes(uint64_t Offset,ArrayRef<uint8_t> Buffer)385349cc55cSDimitry Andric Error WritableMappedBlockStream::writeBytes(uint64_t Offset,
386*0b57cec5SDimitry Andric                                             ArrayRef<uint8_t> Buffer) {
387*0b57cec5SDimitry Andric   // Make sure we aren't trying to write beyond the end of the stream.
388*0b57cec5SDimitry Andric   if (auto EC = checkOffsetForWrite(Offset, Buffer.size()))
389*0b57cec5SDimitry Andric     return EC;
390*0b57cec5SDimitry Andric 
391349cc55cSDimitry Andric   uint64_t BlockNum = Offset / getBlockSize();
392349cc55cSDimitry Andric   uint64_t OffsetInBlock = Offset % getBlockSize();
393*0b57cec5SDimitry Andric 
394349cc55cSDimitry Andric   uint64_t BytesLeft = Buffer.size();
395349cc55cSDimitry Andric   uint64_t BytesWritten = 0;
396*0b57cec5SDimitry Andric   while (BytesLeft > 0) {
397349cc55cSDimitry Andric     uint64_t StreamBlockAddr = getStreamLayout().Blocks[BlockNum];
398349cc55cSDimitry Andric     uint64_t BytesToWriteInChunk =
399*0b57cec5SDimitry Andric         std::min(BytesLeft, getBlockSize() - OffsetInBlock);
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric     const uint8_t *Chunk = Buffer.data() + BytesWritten;
402*0b57cec5SDimitry Andric     ArrayRef<uint8_t> ChunkData(Chunk, BytesToWriteInChunk);
403349cc55cSDimitry Andric     uint64_t MsfOffset = blockToOffset(StreamBlockAddr, getBlockSize());
404*0b57cec5SDimitry Andric     MsfOffset += OffsetInBlock;
405*0b57cec5SDimitry Andric     if (auto EC = WriteInterface.writeBytes(MsfOffset, ChunkData))
406*0b57cec5SDimitry Andric       return EC;
407*0b57cec5SDimitry Andric 
408*0b57cec5SDimitry Andric     BytesLeft -= BytesToWriteInChunk;
409*0b57cec5SDimitry Andric     BytesWritten += BytesToWriteInChunk;
410*0b57cec5SDimitry Andric     ++BlockNum;
411*0b57cec5SDimitry Andric     OffsetInBlock = 0;
412*0b57cec5SDimitry Andric   }
413*0b57cec5SDimitry Andric 
414*0b57cec5SDimitry Andric   ReadInterface.fixCacheAfterWrite(Offset, Buffer);
415*0b57cec5SDimitry Andric 
416*0b57cec5SDimitry Andric   return Error::success();
417*0b57cec5SDimitry Andric }
418*0b57cec5SDimitry Andric 
commit()419*0b57cec5SDimitry Andric Error WritableMappedBlockStream::commit() { return WriteInterface.commit(); }
420