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