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