LLVM  5.0.0
MappedBlockStream.cpp
Go to the documentation of this file.
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 
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/Support/Endian.h"
16 #include "llvm/Support/Error.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 
60  const MSFStreamLayout &Layout,
61  BinaryStreamRef MsfData,
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,
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,
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>
86  BinaryStreamRef MsfData,
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>
96  BinaryStreamRef MsfData,
98  MSFStreamLayout SL;
99  initializeFpmStreamLayout(Layout, SL);
100  return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
101 }
102 
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 
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 
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 
326  uint32_t BlockSize, const MSFStreamLayout &Layout,
328  : ReadInterface(BlockSize, Layout, MsfData, Allocator),
329  WriteInterface(MsfData) {}
330 
331 std::unique_ptr<WritableMappedBlockStream>
333  const MSFStreamLayout &Layout,
334  WritableBinaryStreamRef MsfData,
336  return llvm::make_unique<MappedBlockStreamImpl<WritableMappedBlockStream>>(
337  BlockSize, Layout, MsfData, Allocator);
338 }
339 
340 std::unique_ptr<WritableMappedBlockStream>
342  WritableBinaryStreamRef MsfData,
343  uint32_t StreamIndex,
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>
354  const MSFLayout &Layout, WritableBinaryStreamRef MsfData,
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>
364  WritableBinaryStreamRef MsfData,
366  MSFStreamLayout SL;
367  initializeFpmStreamLayout(Layout, SL);
368  return createStream(Layout.SB->BlockSize, SL, MsfData, Allocator);
369 }
370 
372  ArrayRef<uint8_t> &Buffer) {
373  return ReadInterface.readBytes(Offset, Size, Buffer);
374 }
375 
377  uint32_t Offset, ArrayRef<uint8_t> &Buffer) {
378  return ReadInterface.readLongestContiguousChunk(Offset, Buffer);
379 }
380 
382  return ReadInterface.getLength();
383 }
384 
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(); }
uint32_t getLength() override
Return the number of bytes of data in this stream.
static void initializeFpmStreamLayout(const MSFLayout &Layout, MSFStreamLayout &FpmLayout)
static std::unique_ptr< WritableMappedBlockStream > createDirectoryStream(const MSFLayout &Layout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Error checkOffset(uint32_t Offset, uint32_t DataSize)
Definition: BinaryStream.h:49
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
Definition: Interval.h:37
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static std::unique_ptr< WritableMappedBlockStream > createStream(uint32_t BlockSize, const MSFStreamLayout &Layout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
uint64_t blockToOffset(uint64_t BlockNumber, uint64_t BlockSize)
Definition: MSFCommon.h:84
T * data() const
Definition: ArrayRef.h:329
Error readBytes(uint32_t Offset, uint32_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...
uint32_t getLength() override
Return the number of bytes of data in this stream.
Error commit() override
For buffered streams, commits changes to the backing store.
static Interval intersect(const Interval &I1, const Interval &I2)
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
Error writeBytes(uint32_t Offset, ArrayRef< uint8_t > Buffer) override
Attempt to write the given bytes into the stream at the desired offset.
Error readLongestContiguousChunk(uint32_t Offset, ArrayRef< uint8_t > &Buffer) override
Given an offset into the stream, read as much as possible without copying any data.
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:179
Describes the layout of a stream in an MSF layout.
static std::unique_ptr< MappedBlockStream > createIndexedStream(const MSFLayout &Layout, BinaryStreamRef MsfData, uint32_t StreamIndex, BumpPtrAllocator &Allocator)
Error readLongestContiguousChunk(uint32_t Offset, ArrayRef< uint8_t > &Buffer) override
Given an offset into the stream, read as much as possible without copying any data.
uint32_t getFpmIntervalLength(const MSFLayout &L)
Definition: MSFCommon.h:88
std::vector< support::ulittle32_t > Blocks
support::ulittle32_t BlockSize
Definition: MSFCommon.h:37
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static std::unique_ptr< MappedBlockStream > createDirectoryStream(const MSFLayout &Layout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:138
static std::unique_ptr< MappedBlockStream > createFpmStream(const MSFLayout &Layout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
Error writeBytes(uint32_t Offset, ArrayRef< uint8_t > Data) const
Given an Offset into this WritableBinaryStreamRef and some input data, writes the data to the underly...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:212
static std::unique_ptr< MappedBlockStream > createStream(uint32_t BlockSize, const MSFStreamLayout &Layout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
static std::unique_ptr< WritableMappedBlockStream > createFpmStream(const MSFLayout &Layout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
Error readBytes(uint32_t Offset, uint32_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...
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:593
uint32_t getNumFpmIntervals(const MSFLayout &L)
Definition: MSFCommon.h:92
static const int BlockSize
Definition: TarWriter.cpp:34
Basic Register Allocator
Error commit()
For buffered streams, commits changes to the backing store.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
#define E
Definition: LargeTest.cpp:27
ArrayRef< support::ulittle32_t > DirectoryBlocks
Definition: MSFCommon.h:57
BinaryStreamRef is to BinaryStream what ArrayRef is to an Array.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
MappedBlockStream(uint32_t BlockSize, const MSFStreamLayout &StreamLayout, BinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
static std::unique_ptr< WritableMappedBlockStream > createIndexedStream(const MSFLayout &Layout, WritableBinaryStreamRef MsfData, uint32_t StreamIndex, BumpPtrAllocator &Allocator)
const NodeList & List
Definition: RDFGraph.cpp:205
WritableMappedBlockStream(uint32_t BlockSize, const MSFStreamLayout &StreamLayout, WritableBinaryStreamRef MsfData, BumpPtrAllocator &Allocator)
#define I(x, y, z)
Definition: MD5.cpp:58
std::enable_if< std::is_unsigned< T >::value, T >::type 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:754
std::vector< ArrayRef< support::ulittle32_t > > StreamMap
Definition: MSFCommon.h:59
uint32_t getFullFpmByteSize(const MSFLayout &L)
Definition: MSFCommon.h:97
ArrayRef< support::ulittle32_t > StreamSizes
Definition: MSFCommon.h:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:188
support::ulittle32_t FreeBlockMapBlock
Definition: MSFCommon.h:39
Error readBytes(uint32_t Offset, uint32_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...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
BumpPtrAllocator Alloc
const SuperBlock * SB
Definition: MSFCommon.h:55
support::ulittle32_t NumDirectoryBytes
Definition: MSFCommon.h:45
const T * data() const
Definition: ArrayRef.h:146
const MSFStreamLayout & getStreamLayout() const