MappedBlockStream.cpp 16 KB

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