LLVM 17.0.0git
MappedBlockStream.cpp
Go to the documentation of this file.
1//===- MappedBlockStream.cpp - Reads stream data from an MSF file ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
13#include "llvm/Support/Endian.h"
14#include "llvm/Support/Error.h"
16#include <algorithm>
17#include <cassert>
18#include <cstdint>
19#include <cstring>
20#include <utility>
21#include <vector>
22
23using namespace llvm;
24using namespace llvm::msf;
25
26namespace {
27
28template <typename Base> class MappedBlockStreamImpl : public Base {
29public:
30 template <typename... Args>
31 MappedBlockStreamImpl(Args &&... Params)
32 : Base(std::forward<Args>(Params)...) {}
33};
34
35} // end anonymous namespace
36
37using Interval = std::pair<uint64_t, uint64_t>;
38
39static Interval intersect(const Interval &I1, const Interval &I2) {
40 return std::make_pair(std::max(I1.first, I2.first),
41 std::min(I1.second, I2.second));
42}
43
45 const MSFStreamLayout &Layout,
46 BinaryStreamRef MsfData,
47 BumpPtrAllocator &Allocator)
48 : BlockSize(BlockSize), StreamLayout(Layout), MsfData(MsfData),
50
51std::unique_ptr<MappedBlockStream> MappedBlockStream::createStream(
52 uint32_t BlockSize, const MSFStreamLayout &Layout, BinaryStreamRef MsfData,
53 BumpPtrAllocator &Allocator) {
54 return std::make_unique<MappedBlockStreamImpl<MappedBlockStream>>(
55 BlockSize, Layout, MsfData, Allocator);
56}
57
58std::unique_ptr<MappedBlockStream> MappedBlockStream::createIndexedStream(
59 const MSFLayout &Layout, BinaryStreamRef MsfData, uint32_t StreamIndex,
60 BumpPtrAllocator &Allocator) {
61 assert(StreamIndex < Layout.StreamMap.size() && "Invalid stream index");
63 SL.Blocks = Layout.StreamMap[StreamIndex];
64 SL.Length = Layout.StreamSizes[StreamIndex];
65 return std::make_unique<MappedBlockStreamImpl<MappedBlockStream>>(
66 Layout.SB->BlockSize, SL, MsfData, Allocator);
67}
68
69std::unique_ptr<MappedBlockStream>
71 BinaryStreamRef MsfData,
72 BumpPtrAllocator &Allocator) {
74 SL.Blocks = Layout.DirectoryBlocks;
75 SL.Length = Layout.SB->NumDirectoryBytes;
76 return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
77}
78
79std::unique_ptr<MappedBlockStream>
81 BinaryStreamRef MsfData,
82 BumpPtrAllocator &Allocator) {
84 return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
85}
86
88 ArrayRef<uint8_t> &Buffer) {
89 // Make sure we aren't trying to read beyond the end of the stream.
90 if (auto EC = checkOffsetForRead(Offset, Size))
91 return EC;
92
93 if (tryReadContiguously(Offset, Size, Buffer))
94 return Error::success();
95
96 auto CacheIter = CacheMap.find(Offset);
97 if (CacheIter != CacheMap.end()) {
98 // Try to find an alloc that was large enough for this request.
99 for (auto &Entry : CacheIter->second) {
100 if (Entry.size() >= Size) {
101 Buffer = Entry.slice(0, Size);
102 return Error::success();
103 }
104 }
105 }
106
107 // We couldn't find a buffer that started at the correct offset (the most
108 // common scenario). Try to see if there is a buffer that starts at some
109 // other offset but overlaps the desired range.
110 for (auto &CacheItem : CacheMap) {
111 Interval RequestExtent = std::make_pair(Offset, Offset + Size);
112
113 // We already checked this one on the fast path above.
114 if (CacheItem.first == Offset)
115 continue;
116 // If the initial extent of the cached item is beyond the ending extent
117 // of the request, there is no overlap.
118 if (CacheItem.first >= Offset + Size)
119 continue;
120
121 // We really only have to check the last item in the list, since we append
122 // in order of increasing length.
123 if (CacheItem.second.empty())
124 continue;
125
126 auto CachedAlloc = CacheItem.second.back();
127 // If the initial extent of the request is beyond the ending extent of
128 // the cached item, there is no overlap.
129 Interval CachedExtent =
130 std::make_pair(CacheItem.first, CacheItem.first + CachedAlloc.size());
131 if (RequestExtent.first >= CachedExtent.first + CachedExtent.second)
132 continue;
133
134 Interval Intersection = intersect(CachedExtent, RequestExtent);
135 // Only use this if the entire request extent is contained in the cached
136 // extent.
137 if (Intersection != RequestExtent)
138 continue;
139
140 uint64_t CacheRangeOffset =
141 AbsoluteDifference(CachedExtent.first, Intersection.first);
142 Buffer = CachedAlloc.slice(CacheRangeOffset, Size);
143 return Error::success();
144 }
145
146 // Otherwise allocate a large enough buffer in the pool, memcpy the data
147 // into it, and return an ArrayRef to that. Do not touch existing pool
148 // allocations, as existing clients may be holding a pointer which must
149 // not be invalidated.
150 uint8_t *WriteBuffer = static_cast<uint8_t *>(Allocator.Allocate(Size, 8));
151 if (auto EC = readBytes(Offset, MutableArrayRef<uint8_t>(WriteBuffer, Size)))
152 return EC;
153
154 if (CacheIter != CacheMap.end()) {
155 CacheIter->second.emplace_back(WriteBuffer, Size);
156 } else {
157 std::vector<CacheEntry> List;
158 List.emplace_back(WriteBuffer, Size);
159 CacheMap.insert(std::make_pair(Offset, List));
160 }
161 Buffer = ArrayRef<uint8_t>(WriteBuffer, Size);
162 return Error::success();
163}
164
166 ArrayRef<uint8_t> &Buffer) {
167 // Make sure we aren't trying to read beyond the end of the stream.
168 if (auto EC = checkOffsetForRead(Offset, 1))
169 return EC;
170
171 uint64_t First = Offset / BlockSize;
172 uint64_t Last = First;
173
174 while (Last < getNumBlocks() - 1) {
175 if (StreamLayout.Blocks[Last] != StreamLayout.Blocks[Last + 1] - 1)
176 break;
177 ++Last;
178 }
179
180 uint64_t OffsetInFirstBlock = Offset % BlockSize;
181 uint64_t BytesFromFirstBlock = BlockSize - OffsetInFirstBlock;
182 uint64_t BlockSpan = Last - First + 1;
183 uint64_t ByteSpan = BytesFromFirstBlock + (BlockSpan - 1) * BlockSize;
184
185 ArrayRef<uint8_t> BlockData;
186 uint64_t MsfOffset = blockToOffset(StreamLayout.Blocks[First], BlockSize);
187 if (auto EC = MsfData.readBytes(MsfOffset, BlockSize, BlockData))
188 return EC;
189
190 BlockData = BlockData.drop_front(OffsetInFirstBlock);
191 Buffer = ArrayRef<uint8_t>(BlockData.data(), ByteSpan);
192 return Error::success();
193}
194
196
197bool MappedBlockStream::tryReadContiguously(uint64_t Offset, uint64_t Size,
198 ArrayRef<uint8_t> &Buffer) {
199 if (Size == 0) {
200 Buffer = ArrayRef<uint8_t>();
201 return true;
202 }
203 // Attempt to fulfill the request with a reference directly into the stream.
204 // This can work even if the request crosses a block boundary, provided that
205 // all subsequent blocks are contiguous. For example, a 10k read with a 4k
206 // block size can be filled with a reference if, from the starting offset,
207 // 3 blocks in a row are contiguous.
208 uint64_t BlockNum = Offset / BlockSize;
209 uint64_t OffsetInBlock = Offset % BlockSize;
210 uint64_t BytesFromFirstBlock = std::min(Size, BlockSize - OffsetInBlock);
211 uint64_t NumAdditionalBlocks =
212 alignTo(Size - BytesFromFirstBlock, BlockSize) / BlockSize;
213
214 uint64_t RequiredContiguousBlocks = NumAdditionalBlocks + 1;
215 uint64_t E = StreamLayout.Blocks[BlockNum];
216 for (uint64_t I = 0; I < RequiredContiguousBlocks; ++I, ++E) {
217 if (StreamLayout.Blocks[I + BlockNum] != E)
218 return false;
219 }
220
221 // Read out the entire block where the requested offset starts. Then drop
222 // bytes from the beginning so that the actual starting byte lines up with
223 // the requested starting byte. Then, since we know this is a contiguous
224 // cross-block span, explicitly resize the ArrayRef to cover the entire
225 // request length.
227 uint64_t FirstBlockAddr = StreamLayout.Blocks[BlockNum];
228 uint64_t MsfOffset = blockToOffset(FirstBlockAddr, BlockSize);
229 if (auto EC = MsfData.readBytes(MsfOffset, BlockSize, BlockData)) {
230 consumeError(std::move(EC));
231 return false;
232 }
233 BlockData = BlockData.drop_front(OffsetInBlock);
234 Buffer = ArrayRef<uint8_t>(BlockData.data(), Size);
235 return true;
236}
237
240 uint64_t BlockNum = Offset / BlockSize;
241 uint64_t OffsetInBlock = Offset % BlockSize;
242
243 // Make sure we aren't trying to read beyond the end of the stream.
244 if (auto EC = checkOffsetForRead(Offset, Buffer.size()))
245 return EC;
246
247 uint64_t BytesLeft = Buffer.size();
248 uint64_t BytesWritten = 0;
249 uint8_t *WriteBuffer = Buffer.data();
250 while (BytesLeft > 0) {
251 uint64_t StreamBlockAddr = StreamLayout.Blocks[BlockNum];
252
254 uint64_t Offset = blockToOffset(StreamBlockAddr, BlockSize);
255 if (auto EC = MsfData.readBytes(Offset, BlockSize, BlockData))
256 return EC;
257
258 const uint8_t *ChunkStart = BlockData.data() + OffsetInBlock;
259 uint64_t BytesInChunk = std::min(BytesLeft, BlockSize - OffsetInBlock);
260 ::memcpy(WriteBuffer + BytesWritten, ChunkStart, BytesInChunk);
261
262 BytesWritten += BytesInChunk;
263 BytesLeft -= BytesInChunk;
264 ++BlockNum;
265 OffsetInBlock = 0;
266 }
267
268 return Error::success();
269}
270
271void MappedBlockStream::invalidateCache() { CacheMap.shrink_and_clear(); }
272
273void MappedBlockStream::fixCacheAfterWrite(uint64_t Offset,
274 ArrayRef<uint8_t> Data) const {
275 // If this write overlapped a read which previously came from the pool,
276 // someone may still be holding a pointer to that alloc which is now invalid.
277 // Compute the overlapping range and update the cache entry, so any
278 // outstanding buffers are automatically updated.
279 for (const auto &MapEntry : CacheMap) {
280 // If the end of the written extent precedes the beginning of the cached
281 // extent, ignore this map entry.
282 if (Offset + Data.size() < MapEntry.first)
283 continue;
284 for (const auto &Alloc : MapEntry.second) {
285 // If the end of the cached extent precedes the beginning of the written
286 // extent, ignore this alloc.
287 if (MapEntry.first + Alloc.size() < Offset)
288 continue;
289
290 // If we get here, they are guaranteed to overlap.
291 Interval WriteInterval = std::make_pair(Offset, Offset + Data.size());
292 Interval CachedInterval =
293 std::make_pair(MapEntry.first, MapEntry.first + Alloc.size());
294 // If they overlap, we need to write the new data into the overlapping
295 // range.
296 auto Intersection = intersect(WriteInterval, CachedInterval);
297 assert(Intersection.first <= Intersection.second);
298
299 uint64_t Length = Intersection.second - Intersection.first;
300 uint64_t SrcOffset =
301 AbsoluteDifference(WriteInterval.first, Intersection.first);
302 uint64_t DestOffset =
303 AbsoluteDifference(CachedInterval.first, Intersection.first);
304 ::memcpy(Alloc.data() + DestOffset, Data.data() + SrcOffset, Length);
305 }
306 }
307}
308
310 uint32_t BlockSize, const MSFStreamLayout &Layout,
311 WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
312 : ReadInterface(BlockSize, Layout, MsfData, Allocator),
313 WriteInterface(MsfData) {}
314
315std::unique_ptr<WritableMappedBlockStream>
317 const MSFStreamLayout &Layout,
319 BumpPtrAllocator &Allocator) {
320 return std::make_unique<MappedBlockStreamImpl<WritableMappedBlockStream>>(
321 BlockSize, Layout, MsfData, Allocator);
322}
323
324std::unique_ptr<WritableMappedBlockStream>
327 uint32_t StreamIndex,
328 BumpPtrAllocator &Allocator) {
329 assert(StreamIndex < Layout.StreamMap.size() && "Invalid stream index");
331 SL.Blocks = Layout.StreamMap[StreamIndex];
332 SL.Length = Layout.StreamSizes[StreamIndex];
333 return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
334}
335
336std::unique_ptr<WritableMappedBlockStream>
338 const MSFLayout &Layout, WritableBinaryStreamRef MsfData,
339 BumpPtrAllocator &Allocator) {
341 SL.Blocks = Layout.DirectoryBlocks;
342 SL.Length = Layout.SB->NumDirectoryBytes;
343 return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
344}
345
346std::unique_ptr<WritableMappedBlockStream>
349 BumpPtrAllocator &Allocator,
350 bool AltFpm) {
351 // We only want to give the user a stream containing the bytes of the FPM that
352 // are actually valid, but we want to initialize all of the bytes, even those
353 // that come from reserved FPM blocks where the entire block is unused. To do
354 // this, we first create the full layout, which gives us a stream with all
355 // bytes and all blocks, and initialize everything to 0xFF (all blocks in the
356 // file are unused). Then we create the minimal layout (which contains only a
357 // subset of the bytes previously initialized), and return that to the user.
358 MSFStreamLayout MinLayout(getFpmStreamLayout(Layout, false, AltFpm));
359
360 MSFStreamLayout FullLayout(getFpmStreamLayout(Layout, true, AltFpm));
361 auto Result =
362 createStream(Layout.SB->BlockSize, FullLayout, MsfData, Allocator);
363 if (!Result)
364 return Result;
365 std::vector<uint8_t> InitData(Layout.SB->BlockSize, 0xFF);
366 BinaryStreamWriter Initializer(*Result);
367 while (Initializer.bytesRemaining() > 0)
368 cantFail(Initializer.writeBytes(InitData));
369 return createStream(Layout.SB->BlockSize, MinLayout, MsfData, Allocator);
370}
371
373 ArrayRef<uint8_t> &Buffer) {
374 return ReadInterface.readBytes(Offset, Size, Buffer);
375}
376
379 return ReadInterface.readLongestContiguousChunk(Offset, Buffer);
380}
381
383 return ReadInterface.getLength();
384}
385
387 ArrayRef<uint8_t> Buffer) {
388 // Make sure we aren't trying to write beyond the end of the stream.
389 if (auto EC = checkOffsetForWrite(Offset, Buffer.size()))
390 return EC;
391
392 uint64_t BlockNum = Offset / getBlockSize();
393 uint64_t OffsetInBlock = Offset % getBlockSize();
394
395 uint64_t BytesLeft = Buffer.size();
396 uint64_t BytesWritten = 0;
397 while (BytesLeft > 0) {
398 uint64_t StreamBlockAddr = getStreamLayout().Blocks[BlockNum];
399 uint64_t BytesToWriteInChunk =
400 std::min(BytesLeft, getBlockSize() - OffsetInBlock);
401
402 const uint8_t *Chunk = Buffer.data() + BytesWritten;
403 ArrayRef<uint8_t> ChunkData(Chunk, BytesToWriteInChunk);
404 uint64_t MsfOffset = blockToOffset(StreamBlockAddr, getBlockSize());
405 MsfOffset += OffsetInBlock;
406 if (auto EC = WriteInterface.writeBytes(MsfOffset, ChunkData))
407 return EC;
408
409 BytesLeft -= BytesToWriteInChunk;
410 BytesWritten += BytesToWriteInChunk;
411 ++BlockNum;
412 OffsetInBlock = 0;
413 }
414
415 ReadInterface.fixCacheAfterWrite(Offset, Buffer);
416
417 return Error::success();
418}
419
420Error WritableMappedBlockStream::commit() { return WriteInterface.commit(); }
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
uint64_t Size
static ValueLatticeElement intersect(const ValueLatticeElement &A, const ValueLatticeElement &B)
Combine two sets of facts about the same value into a single set of facts.
#define I(x, y, z)
Definition: MD5.cpp:58
static Interval intersect(const Interval &I1, const Interval &I2)
Basic Register Allocator
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const int BlockSize
Definition: TarWriter.cpp:33
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
const T * data() const
Definition: ArrayRef.h:160
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:193
BinaryStreamRef is to BinaryStream what ArrayRef is to an Array.
Error readBytes(uint64_t Offset, uint64_t Size, ArrayRef< uint8_t > &Buffer) const
Given an Offset into this StreamRef and a Size, return a reference to a buffer owned by the stream.
Provides write only access to a subclass of WritableBinaryStream.
uint64_t bytesRemaining() const
Error writeBytes(ArrayRef< uint8_t > Buffer)
Write the bytes specified in Buffer to the underlying stream.
Error checkOffsetForRead(uint64_t Offset, uint64_t DataSize)
Definition: BinaryStream.h:59
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:148
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
static ErrorSuccess success()
Create a success value.
Definition: Error.h:330
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
Definition: Interval.h:36
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:305
T * data() const
Definition: ArrayRef.h:352
Error writeBytes(uint64_t Offset, ArrayRef< uint8_t > Data) const
Given an Offset into this WritableBinaryStreamRef and some input data, writes the data to the underly...
Error commit()
For buffered streams, commits changes to the backing store.
Error checkOffsetForWrite(uint64_t Offset, uint64_t DataSize)
Definition: BinaryStream.h:89
Describes the layout of a stream in an MSF layout.
Definition: MSFCommon.h:77
std::vector< support::ulittle32_t > Blocks
Definition: MSFCommon.h:80
static std::unique_ptr< MappedBlockStream > createIndexedStream(const MSFLayout &Layout, BinaryStreamRef MsfData, uint32_t StreamIndex, BumpPtrAllocator &Allocator)
Error readBytes(uint64_t Offset, uint64_t Size, ArrayRef< uint8_t > &Buffer) override
Given an offset into the stream and a number of bytes, attempt to read the bytes and set the output A...
Error readLongestContiguousChunk(uint64_t Offset, ArrayRef< uint8_t > &Buffer) override
Given an offset into the stream, read as much as possible without copying any data.
static std::unique_ptr< MappedBlockStream > createStream(uint32_t BlockSize, const MSFStreamLayout &Layout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
MappedBlockStream(uint32_t BlockSize, const MSFStreamLayout &StreamLayout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
static std::unique_ptr< MappedBlockStream > createDirectoryStream(const MSFLayout &Layout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
static std::unique_ptr< MappedBlockStream > createFpmStream(const MSFLayout &Layout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
uint64_t getLength() override
Return the number of bytes of data in this stream.
static std::unique_ptr< WritableMappedBlockStream > createIndexedStream(const MSFLayout &Layout, WritableBinaryStreamRef MsfData, uint32_t StreamIndex, BumpPtrAllocator &Allocator)
static std::unique_ptr< WritableMappedBlockStream > createStream(uint32_t BlockSize, const MSFStreamLayout &Layout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
Error commit() override
For buffered streams, commits changes to the backing store.
WritableMappedBlockStream(uint32_t BlockSize, const MSFStreamLayout &StreamLayout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
Error readBytes(uint64_t Offset, uint64_t Size, ArrayRef< uint8_t > &Buffer) override
Given an offset into the stream and a number of bytes, attempt to read the bytes and set the output A...
static std::unique_ptr< WritableMappedBlockStream > createFpmStream(const MSFLayout &Layout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator, bool AltFpm=false)
static std::unique_ptr< WritableMappedBlockStream > createDirectoryStream(const MSFLayout &Layout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
uint64_t getLength() override
Return the number of bytes of data in this stream.
const MSFStreamLayout & getStreamLayout() const
Error readLongestContiguousChunk(uint64_t Offset, ArrayRef< uint8_t > &Buffer) override
Given an offset into the stream, read as much as possible without copying any data.
Error writeBytes(uint64_t Offset, ArrayRef< uint8_t > Buffer) override
Attempt to write the given bytes into the stream at the desired offset.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
uint64_t blockToOffset(uint64_t BlockNumber, uint64_t BlockSize)
Definition: MSFCommon.h:135
MSFStreamLayout getFpmStreamLayout(const MSFLayout &Msf, bool IncludeUnusedFpmData=false, bool AltFpm=false)
Determine the layout of the FPM stream, given the MSF layout.
Definition: MSFCommon.cpp:62
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:406
@ Length
Definition: DWP.cpp:406
std::enable_if_t< std::is_unsigned_v< T >, T > AbsoluteDifference(T X, T Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition: MathExtras.h:574
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:745
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1043
Definition: BitVector.h:858
ArrayRef< support::ulittle32_t > StreamSizes
Definition: MSFCommon.h:67
ArrayRef< support::ulittle32_t > DirectoryBlocks
Definition: MSFCommon.h:66
const SuperBlock * SB
Definition: MSFCommon.h:64
std::vector< ArrayRef< support::ulittle32_t > > StreamMap
Definition: MSFCommon.h:68
support::ulittle32_t BlockSize
Definition: MSFCommon.h:36
support::ulittle32_t NumDirectoryBytes
Definition: MSFCommon.h:44