Path: blob/main/contrib/llvm-project/llvm/lib/DebugInfo/MSF/MSFBuilder.cpp
35266 views
//===- MSFBuilder.cpp -----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/DebugInfo/MSF/MSFBuilder.h"9#include "llvm/ADT/ArrayRef.h"10#include "llvm/DebugInfo/MSF/MSFError.h"11#include "llvm/DebugInfo/MSF/MappedBlockStream.h"12#include "llvm/Support/BinaryByteStream.h"13#include "llvm/Support/BinaryStreamWriter.h"14#include "llvm/Support/Endian.h"15#include "llvm/Support/Error.h"16#include "llvm/Support/FileOutputBuffer.h"17#include "llvm/Support/FormatVariadic.h"18#include "llvm/Support/TimeProfiler.h"19#include <algorithm>20#include <cassert>21#include <cstdint>22#include <cstring>23#include <memory>24#include <utility>25#include <vector>2627using namespace llvm;28using namespace llvm::msf;29using namespace llvm::support;3031static const uint32_t kSuperBlockBlock = 0;32static const uint32_t kFreePageMap0Block = 1;33static const uint32_t kFreePageMap1Block = 2;34static const uint32_t kNumReservedPages = 3;3536static const uint32_t kDefaultFreePageMap = kFreePageMap1Block;37static const uint32_t kDefaultBlockMapAddr = kNumReservedPages;3839MSFBuilder::MSFBuilder(uint32_t BlockSize, uint32_t MinBlockCount, bool CanGrow,40BumpPtrAllocator &Allocator)41: Allocator(Allocator), IsGrowable(CanGrow),42FreePageMap(kDefaultFreePageMap), BlockSize(BlockSize),43BlockMapAddr(kDefaultBlockMapAddr), FreeBlocks(MinBlockCount, true) {44FreeBlocks[kSuperBlockBlock] = false;45FreeBlocks[kFreePageMap0Block] = false;46FreeBlocks[kFreePageMap1Block] = false;47FreeBlocks[BlockMapAddr] = false;48}4950Expected<MSFBuilder> MSFBuilder::create(BumpPtrAllocator &Allocator,51uint32_t BlockSize,52uint32_t MinBlockCount, bool CanGrow) {53if (!isValidBlockSize(BlockSize))54return make_error<MSFError>(msf_error_code::invalid_format,55"The requested block size is unsupported");5657return MSFBuilder(BlockSize,58std::max(MinBlockCount, msf::getMinimumBlockCount()),59CanGrow, Allocator);60}6162Error MSFBuilder::setBlockMapAddr(uint32_t Addr) {63if (Addr == BlockMapAddr)64return Error::success();6566if (Addr >= FreeBlocks.size()) {67if (!IsGrowable)68return make_error<MSFError>(msf_error_code::insufficient_buffer,69"Cannot grow the number of blocks");70FreeBlocks.resize(Addr + 1, true);71}7273if (!isBlockFree(Addr))74return make_error<MSFError>(75msf_error_code::block_in_use,76"Requested block map address is already in use");77FreeBlocks[BlockMapAddr] = true;78FreeBlocks[Addr] = false;79BlockMapAddr = Addr;80return Error::success();81}8283void MSFBuilder::setFreePageMap(uint32_t Fpm) { FreePageMap = Fpm; }8485void MSFBuilder::setUnknown1(uint32_t Unk1) { Unknown1 = Unk1; }8687Error MSFBuilder::setDirectoryBlocksHint(ArrayRef<uint32_t> DirBlocks) {88for (auto B : DirectoryBlocks)89FreeBlocks[B] = true;90for (auto B : DirBlocks) {91if (!isBlockFree(B)) {92return make_error<MSFError>(msf_error_code::unspecified,93"Attempt to reuse an allocated block");94}95FreeBlocks[B] = false;96}9798DirectoryBlocks = DirBlocks;99return Error::success();100}101102Error MSFBuilder::allocateBlocks(uint32_t NumBlocks,103MutableArrayRef<uint32_t> Blocks) {104if (NumBlocks == 0)105return Error::success();106107uint32_t NumFreeBlocks = FreeBlocks.count();108if (NumFreeBlocks < NumBlocks) {109if (!IsGrowable)110return make_error<MSFError>(msf_error_code::insufficient_buffer,111"There are no free Blocks in the file");112uint32_t AllocBlocks = NumBlocks - NumFreeBlocks;113uint32_t OldBlockCount = FreeBlocks.size();114uint32_t NewBlockCount = AllocBlocks + OldBlockCount;115uint32_t NextFpmBlock = alignTo(OldBlockCount, BlockSize) + 1;116FreeBlocks.resize(NewBlockCount, true);117// If we crossed over an fpm page, we actually need to allocate 2 extra118// blocks for each FPM group crossed and mark both blocks from the group as119// used. FPM blocks are marked as allocated regardless of whether or not120// they ultimately describe the status of blocks in the file. This means121// that not only are extraneous blocks at the end of the main FPM marked as122// allocated, but also blocks from the alternate FPM are always marked as123// allocated.124while (NextFpmBlock < NewBlockCount) {125NewBlockCount += 2;126FreeBlocks.resize(NewBlockCount, true);127FreeBlocks.reset(NextFpmBlock, NextFpmBlock + 2);128NextFpmBlock += BlockSize;129}130}131132int I = 0;133int Block = FreeBlocks.find_first();134do {135assert(Block != -1 && "We ran out of Blocks!");136137uint32_t NextBlock = static_cast<uint32_t>(Block);138Blocks[I++] = NextBlock;139FreeBlocks.reset(NextBlock);140Block = FreeBlocks.find_next(Block);141} while (--NumBlocks > 0);142return Error::success();143}144145uint32_t MSFBuilder::getNumUsedBlocks() const {146return getTotalBlockCount() - getNumFreeBlocks();147}148149uint32_t MSFBuilder::getNumFreeBlocks() const { return FreeBlocks.count(); }150151uint32_t MSFBuilder::getTotalBlockCount() const { return FreeBlocks.size(); }152153bool MSFBuilder::isBlockFree(uint32_t Idx) const { return FreeBlocks[Idx]; }154155Expected<uint32_t> MSFBuilder::addStream(uint32_t Size,156ArrayRef<uint32_t> Blocks) {157// Add a new stream mapped to the specified blocks. Verify that the specified158// blocks are both necessary and sufficient for holding the requested number159// of bytes, and verify that all requested blocks are free.160uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize);161if (ReqBlocks != Blocks.size())162return make_error<MSFError>(163msf_error_code::invalid_format,164"Incorrect number of blocks for requested stream size");165for (auto Block : Blocks) {166if (Block >= FreeBlocks.size())167FreeBlocks.resize(Block + 1, true);168169if (!FreeBlocks.test(Block))170return make_error<MSFError>(171msf_error_code::unspecified,172"Attempt to re-use an already allocated block");173}174// Mark all the blocks occupied by the new stream as not free.175for (auto Block : Blocks) {176FreeBlocks.reset(Block);177}178StreamData.push_back(std::make_pair(Size, Blocks));179return StreamData.size() - 1;180}181182Expected<uint32_t> MSFBuilder::addStream(uint32_t Size) {183uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize);184std::vector<uint32_t> NewBlocks;185NewBlocks.resize(ReqBlocks);186if (auto EC = allocateBlocks(ReqBlocks, NewBlocks))187return std::move(EC);188StreamData.push_back(std::make_pair(Size, NewBlocks));189return StreamData.size() - 1;190}191192Error MSFBuilder::setStreamSize(uint32_t Idx, uint32_t Size) {193uint32_t OldSize = getStreamSize(Idx);194if (OldSize == Size)195return Error::success();196197uint32_t NewBlocks = bytesToBlocks(Size, BlockSize);198uint32_t OldBlocks = bytesToBlocks(OldSize, BlockSize);199200if (NewBlocks > OldBlocks) {201uint32_t AddedBlocks = NewBlocks - OldBlocks;202// If we're growing, we have to allocate new Blocks.203std::vector<uint32_t> AddedBlockList;204AddedBlockList.resize(AddedBlocks);205if (auto EC = allocateBlocks(AddedBlocks, AddedBlockList))206return EC;207auto &CurrentBlocks = StreamData[Idx].second;208llvm::append_range(CurrentBlocks, AddedBlockList);209} else if (OldBlocks > NewBlocks) {210// For shrinking, free all the Blocks in the Block map, update the stream211// data, then shrink the directory.212uint32_t RemovedBlocks = OldBlocks - NewBlocks;213auto CurrentBlocks = ArrayRef<uint32_t>(StreamData[Idx].second);214auto RemovedBlockList = CurrentBlocks.drop_front(NewBlocks);215for (auto P : RemovedBlockList)216FreeBlocks[P] = true;217StreamData[Idx].second = CurrentBlocks.drop_back(RemovedBlocks);218}219220StreamData[Idx].first = Size;221return Error::success();222}223224uint32_t MSFBuilder::getNumStreams() const { return StreamData.size(); }225226uint32_t MSFBuilder::getStreamSize(uint32_t StreamIdx) const {227return StreamData[StreamIdx].first;228}229230ArrayRef<uint32_t> MSFBuilder::getStreamBlocks(uint32_t StreamIdx) const {231return StreamData[StreamIdx].second;232}233234uint32_t MSFBuilder::computeDirectoryByteSize() const {235// The directory has the following layout, where each item is a ulittle32_t:236// NumStreams237// StreamSizes[NumStreams]238// StreamBlocks[NumStreams][]239uint32_t Size = sizeof(ulittle32_t); // NumStreams240Size += StreamData.size() * sizeof(ulittle32_t); // StreamSizes241for (const auto &D : StreamData) {242uint32_t ExpectedNumBlocks = bytesToBlocks(D.first, BlockSize);243assert(ExpectedNumBlocks == D.second.size() &&244"Unexpected number of blocks");245Size += ExpectedNumBlocks * sizeof(ulittle32_t);246}247return Size;248}249250Expected<MSFLayout> MSFBuilder::generateLayout() {251llvm::TimeTraceScope timeScope("MSF: Generate layout");252253SuperBlock *SB = Allocator.Allocate<SuperBlock>();254MSFLayout L;255L.SB = SB;256257std::memcpy(SB->MagicBytes, Magic, sizeof(Magic));258SB->BlockMapAddr = BlockMapAddr;259SB->BlockSize = BlockSize;260SB->NumDirectoryBytes = computeDirectoryByteSize();261SB->FreeBlockMapBlock = FreePageMap;262SB->Unknown1 = Unknown1;263264uint32_t NumDirectoryBlocks = bytesToBlocks(SB->NumDirectoryBytes, BlockSize);265if (NumDirectoryBlocks > DirectoryBlocks.size()) {266// Our hint wasn't enough to satisfy the entire directory. Allocate267// remaining pages.268std::vector<uint32_t> ExtraBlocks;269uint32_t NumExtraBlocks = NumDirectoryBlocks - DirectoryBlocks.size();270ExtraBlocks.resize(NumExtraBlocks);271if (auto EC = allocateBlocks(NumExtraBlocks, ExtraBlocks))272return std::move(EC);273llvm::append_range(DirectoryBlocks, ExtraBlocks);274} else if (NumDirectoryBlocks < DirectoryBlocks.size()) {275uint32_t NumUnnecessaryBlocks = DirectoryBlocks.size() - NumDirectoryBlocks;276for (auto B :277ArrayRef<uint32_t>(DirectoryBlocks).drop_back(NumUnnecessaryBlocks))278FreeBlocks[B] = true;279DirectoryBlocks.resize(NumDirectoryBlocks);280}281282// Don't set the number of blocks in the file until after allocating Blocks283// for the directory, since the allocation might cause the file to need to284// grow.285SB->NumBlocks = FreeBlocks.size();286287ulittle32_t *DirBlocks = Allocator.Allocate<ulittle32_t>(NumDirectoryBlocks);288std::uninitialized_copy_n(DirectoryBlocks.begin(), NumDirectoryBlocks,289DirBlocks);290L.DirectoryBlocks = ArrayRef<ulittle32_t>(DirBlocks, NumDirectoryBlocks);291292// The stream sizes should be re-allocated as a stable pointer and the stream293// map should have each of its entries allocated as a separate stable pointer.294if (!StreamData.empty()) {295ulittle32_t *Sizes = Allocator.Allocate<ulittle32_t>(StreamData.size());296L.StreamSizes = ArrayRef<ulittle32_t>(Sizes, StreamData.size());297L.StreamMap.resize(StreamData.size());298for (uint32_t I = 0; I < StreamData.size(); ++I) {299Sizes[I] = StreamData[I].first;300ulittle32_t *BlockList =301Allocator.Allocate<ulittle32_t>(StreamData[I].second.size());302std::uninitialized_copy_n(StreamData[I].second.begin(),303StreamData[I].second.size(), BlockList);304L.StreamMap[I] =305ArrayRef<ulittle32_t>(BlockList, StreamData[I].second.size());306}307}308309L.FreePageMap = FreeBlocks;310311return L;312}313314static void commitFpm(WritableBinaryStream &MsfBuffer, const MSFLayout &Layout,315BumpPtrAllocator &Allocator) {316auto FpmStream =317WritableMappedBlockStream::createFpmStream(Layout, MsfBuffer, Allocator);318319// We only need to create the alt fpm stream so that it gets initialized.320WritableMappedBlockStream::createFpmStream(Layout, MsfBuffer, Allocator,321true);322323uint32_t BI = 0;324BinaryStreamWriter FpmWriter(*FpmStream);325while (BI < Layout.SB->NumBlocks) {326uint8_t ThisByte = 0;327for (uint32_t I = 0; I < 8; ++I) {328bool IsFree =329(BI < Layout.SB->NumBlocks) ? Layout.FreePageMap.test(BI) : true;330uint8_t Mask = uint8_t(IsFree) << I;331ThisByte |= Mask;332++BI;333}334cantFail(FpmWriter.writeObject(ThisByte));335}336assert(FpmWriter.bytesRemaining() == 0);337}338339Expected<FileBufferByteStream> MSFBuilder::commit(StringRef Path,340MSFLayout &Layout) {341llvm::TimeTraceScope timeScope("Commit MSF");342343Expected<MSFLayout> L = generateLayout();344if (!L)345return L.takeError();346347Layout = std::move(*L);348349uint64_t FileSize = uint64_t(Layout.SB->BlockSize) * Layout.SB->NumBlocks;350// Ensure that the file size is under the limit for the specified block size.351if (FileSize > getMaxFileSizeFromBlockSize(Layout.SB->BlockSize)) {352msf_error_code error_code = [](uint32_t BlockSize) {353switch (BlockSize) {354case 8192:355return msf_error_code::size_overflow_8192;356case 16384:357return msf_error_code::size_overflow_16384;358case 32768:359return msf_error_code::size_overflow_32768;360default:361return msf_error_code::size_overflow_4096;362}363}(Layout.SB->BlockSize);364365return make_error<MSFError>(366error_code,367formatv("File size {0,1:N} too large for current PDB page size {1}",368FileSize, Layout.SB->BlockSize));369}370371uint64_t NumDirectoryBlocks =372bytesToBlocks(Layout.SB->NumDirectoryBytes, Layout.SB->BlockSize);373uint64_t DirectoryBlockMapSize =374NumDirectoryBlocks * sizeof(support::ulittle32_t);375if (DirectoryBlockMapSize > Layout.SB->BlockSize) {376return make_error<MSFError>(msf_error_code::stream_directory_overflow,377formatv("The directory block map ({0} bytes) "378"doesn't fit in a block ({1} bytes)",379DirectoryBlockMapSize,380Layout.SB->BlockSize));381}382383auto OutFileOrError = FileOutputBuffer::create(Path, FileSize);384if (auto EC = OutFileOrError.takeError())385return std::move(EC);386387FileBufferByteStream Buffer(std::move(*OutFileOrError),388llvm::endianness::little);389BinaryStreamWriter Writer(Buffer);390391if (auto EC = Writer.writeObject(*Layout.SB))392return std::move(EC);393394commitFpm(Buffer, Layout, Allocator);395396uint32_t BlockMapOffset =397msf::blockToOffset(Layout.SB->BlockMapAddr, Layout.SB->BlockSize);398Writer.setOffset(BlockMapOffset);399if (auto EC = Writer.writeArray(Layout.DirectoryBlocks))400return std::move(EC);401402auto DirStream = WritableMappedBlockStream::createDirectoryStream(403Layout, Buffer, Allocator);404BinaryStreamWriter DW(*DirStream);405if (auto EC = DW.writeInteger<uint32_t>(Layout.StreamSizes.size()))406return std::move(EC);407408if (auto EC = DW.writeArray(Layout.StreamSizes))409return std::move(EC);410411for (const auto &Blocks : Layout.StreamMap) {412if (auto EC = DW.writeArray(Blocks))413return std::move(EC);414}415416return std::move(Buffer);417}418419420