LLVM 24.0.0git
MSFBuilder.cpp
Go to the documentation of this file.
1//===- MSFBuilder.cpp -----------------------------------------------------===//
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"
15#include "llvm/Support/Endian.h"
16#include "llvm/Support/Error.h"
20#include <algorithm>
21#include <cassert>
22#include <cstdint>
23#include <cstring>
24#include <limits>
25#include <utility>
26#include <vector>
27
28using namespace llvm;
29using namespace llvm::msf;
30using namespace llvm::support;
31
32static const uint32_t kSuperBlockBlock = 0;
35static const uint32_t kNumReservedPages = 3;
36
39
40MSFBuilder::MSFBuilder(uint32_t BlockSize, BumpPtrAllocator &Allocator)
43
45 uint32_t BlockSize,
46 uint32_t MinBlockCount, bool CanGrow) {
47 if (!isValidBlockSize(BlockSize))
49 "The requested block size is unsupported");
50
51 MSFBuilder Builder(BlockSize, Allocator);
52 if (auto EC = Builder.growFreeBlocks(
53 std::max(MinBlockCount, msf::getMinimumBlockCount())))
54 return std::move(EC);
55 Builder.FreeBlocks.reset(kSuperBlockBlock);
56 Builder.FreeBlocks.reset(Builder.BlockMapAddr);
57 Builder.IsGrowable = CanGrow;
58 return Builder;
59}
60
62 if (Addr == BlockMapAddr)
63 return Error::success();
64
65 if (auto EC = growFreeBlocks(uint64_t(Addr) + 1))
66 return EC;
67
68 if (!isBlockFree(Addr))
71 "Requested block map address is already in use");
72 FreeBlocks[BlockMapAddr] = true;
73 FreeBlocks[Addr] = false;
74 BlockMapAddr = Addr;
75 return Error::success();
76}
77
78void MSFBuilder::setFreePageMap(uint32_t Fpm) { FreePageMap = Fpm; }
79
80void MSFBuilder::setUnknown1(uint32_t Unk1) { Unknown1 = Unk1; }
81
83 for (auto B : DirectoryBlocks)
84 FreeBlocks[B] = true;
85 for (auto B : DirBlocks) {
86 if (!isBlockFree(B)) {
88 "Attempt to reuse an allocated block");
89 }
90 FreeBlocks[B] = false;
91 }
92
93 DirectoryBlocks = DirBlocks;
94 return Error::success();
95}
96
97Error MSFBuilder::growFreeBlocks(uint64_t MinBlockCount,
98 uint32_t MinNewFreeBlocks) {
99 const uint64_t OldBlockCount = FreeBlocks.size();
100 uint64_t EndForFreeBlocks = OldBlockCount + MinNewFreeBlocks;
101 uint64_t NewBlockCount = std::max(MinBlockCount, EndForFreeBlocks);
102 if (NewBlockCount == OldBlockCount)
103 return Error::success();
104
105 if (!IsGrowable)
107 "Cannot grow the number of blocks");
108
109 const uint64_t FirstFpm = OldBlockCount == 0
111 : alignTo(OldBlockCount, BlockSize, 1);
112 // BitVector's find_first and find_next return signed block indices.
113 constexpr uint64_t MaxBlockCount = std::numeric_limits<int>::max();
114 // Include both blocks of every FPM pair we reach, even unused FPM pages.
115 // Neither block contributes to the requested number of new free blocks.
116 for (uint64_t Fpm = FirstFpm;
117 Fpm < NewBlockCount && NewBlockCount <= MaxBlockCount;
118 Fpm += BlockSize) {
119 EndForFreeBlocks += 2;
120 NewBlockCount = std::max({NewBlockCount, Fpm + 2, EndForFreeBlocks});
121 }
122 if (NewBlockCount > MaxBlockCount)
124 "The requested number of blocks is too large");
125
126 FreeBlocks.resize(static_cast<uint32_t>(NewBlockCount), true);
127 for (uint32_t Fpm = static_cast<uint32_t>(FirstFpm); Fpm < NewBlockCount;
128 Fpm += BlockSize)
129 FreeBlocks.reset(Fpm, Fpm + 2);
130 return Error::success();
131}
132
133Error MSFBuilder::allocateBlocks(uint32_t NumBlocks,
135 if (NumBlocks == 0)
136 return Error::success();
137
138 uint32_t NumFreeBlocks = FreeBlocks.count();
139 if (NumFreeBlocks < NumBlocks) {
140 if (auto EC = growFreeBlocks(FreeBlocks.size(), NumBlocks - NumFreeBlocks))
141 return EC;
142 }
143
144 int I = 0;
145 int Block = FreeBlocks.find_first();
146 do {
147 assert(Block != -1 && "We ran out of Blocks!");
148
149 uint32_t NextBlock = static_cast<uint32_t>(Block);
150 Blocks[I++] = NextBlock;
151 FreeBlocks.reset(NextBlock);
152 Block = FreeBlocks.find_next(Block);
153 } while (--NumBlocks > 0);
154 return Error::success();
155}
156
160
161uint32_t MSFBuilder::getNumFreeBlocks() const { return FreeBlocks.count(); }
162
163uint32_t MSFBuilder::getTotalBlockCount() const { return FreeBlocks.size(); }
164
165bool MSFBuilder::isBlockFree(uint32_t Idx) const { return FreeBlocks[Idx]; }
166
168 ArrayRef<uint32_t> Blocks) {
169 // Add a new stream mapped to the specified blocks. Verify that the specified
170 // blocks are both necessary and sufficient for holding the requested number
171 // of bytes, and verify that all requested blocks are free.
172 uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize);
173 if (ReqBlocks != Blocks.size())
176 "Incorrect number of blocks for requested stream size");
177 for (auto Block : Blocks) {
178 if (Block >= FreeBlocks.size()) {
179 if (auto EC = growFreeBlocks(uint64_t(Block) + 1))
180 return std::move(EC);
181 }
182
183 if (!FreeBlocks.test(Block))
186 "Attempt to re-use an already allocated block");
187 }
188 // Mark all the blocks occupied by the new stream as not free.
189 for (auto Block : Blocks) {
190 FreeBlocks.reset(Block);
191 }
192 StreamData.push_back(std::make_pair(Size, Blocks));
193 return StreamData.size() - 1;
194}
195
197 uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize);
198 std::vector<uint32_t> NewBlocks;
199 NewBlocks.resize(ReqBlocks);
200 if (auto EC = allocateBlocks(ReqBlocks, NewBlocks))
201 return std::move(EC);
202 StreamData.push_back(std::make_pair(Size, NewBlocks));
203 return StreamData.size() - 1;
204}
205
207 uint32_t OldSize = getStreamSize(Idx);
208 if (OldSize == Size)
209 return Error::success();
210
211 uint32_t NewBlocks = bytesToBlocks(Size, BlockSize);
212 uint32_t OldBlocks = bytesToBlocks(OldSize, BlockSize);
213
214 if (NewBlocks > OldBlocks) {
215 uint32_t AddedBlocks = NewBlocks - OldBlocks;
216 // If we're growing, we have to allocate new Blocks.
217 std::vector<uint32_t> AddedBlockList;
218 AddedBlockList.resize(AddedBlocks);
219 if (auto EC = allocateBlocks(AddedBlocks, AddedBlockList))
220 return EC;
221 auto &CurrentBlocks = StreamData[Idx].second;
222 llvm::append_range(CurrentBlocks, AddedBlockList);
223 } else if (OldBlocks > NewBlocks) {
224 // For shrinking, free all the Blocks in the Block map, update the stream
225 // data, then shrink the directory.
226 uint32_t RemovedBlocks = OldBlocks - NewBlocks;
227 auto CurrentBlocks = ArrayRef<uint32_t>(StreamData[Idx].second);
228 auto RemovedBlockList = CurrentBlocks.drop_front(NewBlocks);
229 for (auto P : RemovedBlockList)
230 FreeBlocks[P] = true;
231 StreamData[Idx].second = CurrentBlocks.drop_back(RemovedBlocks);
232 }
233
234 StreamData[Idx].first = Size;
235 return Error::success();
236}
237
238uint32_t MSFBuilder::getNumStreams() const { return StreamData.size(); }
239
241 return StreamData[StreamIdx].first;
242}
243
245 return StreamData[StreamIdx].second;
246}
247
248uint32_t MSFBuilder::computeDirectoryByteSize() const {
249 // The directory has the following layout, where each item is a ulittle32_t:
250 // NumStreams
251 // StreamSizes[NumStreams]
252 // StreamBlocks[NumStreams][]
253 uint32_t Size = sizeof(ulittle32_t); // NumStreams
254 Size += StreamData.size() * sizeof(ulittle32_t); // StreamSizes
255 for (const auto &D : StreamData) {
256 uint32_t ExpectedNumBlocks = bytesToBlocks(D.first, BlockSize);
257 assert(ExpectedNumBlocks == D.second.size() &&
258 "Unexpected number of blocks");
259 Size += ExpectedNumBlocks * sizeof(ulittle32_t);
260 }
261 return Size;
262}
263
265 llvm::TimeTraceScope timeScope("MSF: Generate layout");
266
267 SuperBlock *SB = Allocator.Allocate<SuperBlock>();
268 MSFLayout L;
269 L.SB = SB;
270
271 std::memcpy(SB->MagicBytes, Magic, sizeof(Magic));
272 SB->BlockMapAddr = BlockMapAddr;
273 SB->BlockSize = BlockSize;
274 SB->NumDirectoryBytes = computeDirectoryByteSize();
275 SB->FreeBlockMapBlock = FreePageMap;
276 SB->Unknown1 = Unknown1;
277
278 uint32_t NumDirectoryBlocks = bytesToBlocks(SB->NumDirectoryBytes, BlockSize);
279 if (NumDirectoryBlocks > DirectoryBlocks.size()) {
280 // Our hint wasn't enough to satisfy the entire directory. Allocate
281 // remaining pages.
282 std::vector<uint32_t> ExtraBlocks;
283 uint32_t NumExtraBlocks = NumDirectoryBlocks - DirectoryBlocks.size();
284 ExtraBlocks.resize(NumExtraBlocks);
285 if (auto EC = allocateBlocks(NumExtraBlocks, ExtraBlocks))
286 return std::move(EC);
287 llvm::append_range(DirectoryBlocks, ExtraBlocks);
288 } else if (NumDirectoryBlocks < DirectoryBlocks.size()) {
289 uint32_t NumUnnecessaryBlocks = DirectoryBlocks.size() - NumDirectoryBlocks;
290 for (auto B :
291 ArrayRef<uint32_t>(DirectoryBlocks).drop_back(NumUnnecessaryBlocks))
292 FreeBlocks[B] = true;
293 DirectoryBlocks.resize(NumDirectoryBlocks);
294 }
295
296 // Don't set the number of blocks in the file until after allocating Blocks
297 // for the directory, since the allocation might cause the file to need to
298 // grow.
299 SB->NumBlocks = FreeBlocks.size();
300
301 ulittle32_t *DirBlocks = Allocator.Allocate<ulittle32_t>(NumDirectoryBlocks);
302 llvm::uninitialized_copy(DirectoryBlocks, DirBlocks);
303 L.DirectoryBlocks = ArrayRef<ulittle32_t>(DirBlocks, NumDirectoryBlocks);
304
305 // The stream sizes should be re-allocated as a stable pointer and the stream
306 // map should have each of its entries allocated as a separate stable pointer.
307 if (!StreamData.empty()) {
308 ulittle32_t *Sizes = Allocator.Allocate<ulittle32_t>(StreamData.size());
309 L.StreamSizes = ArrayRef<ulittle32_t>(Sizes, StreamData.size());
310 L.StreamMap.resize(StreamData.size());
311 for (uint32_t I = 0; I < StreamData.size(); ++I) {
312 Sizes[I] = StreamData[I].first;
313 ulittle32_t *BlockList =
314 Allocator.Allocate<ulittle32_t>(StreamData[I].second.size());
315 llvm::uninitialized_copy(StreamData[I].second, BlockList);
316 L.StreamMap[I] =
317 ArrayRef<ulittle32_t>(BlockList, StreamData[I].second.size());
318 }
319 }
320
321 L.FreePageMap = FreeBlocks;
322
323 return L;
324}
325
326static void commitFpm(WritableBinaryStream &MsfBuffer, const MSFLayout &Layout,
328 auto FpmStream =
330
331 // We only need to create the alt fpm stream so that it gets initialized.
333 true);
334
335 uint32_t BI = 0;
336 BinaryStreamWriter FpmWriter(*FpmStream);
337 while (BI < Layout.SB->NumBlocks) {
338 uint8_t ThisByte = 0;
339 for (uint32_t I = 0; I < 8; ++I) {
340 bool IsFree =
341 (BI < Layout.SB->NumBlocks) ? Layout.FreePageMap.test(BI) : true;
342 uint8_t Mask = uint8_t(IsFree) << I;
343 ThisByte |= Mask;
344 ++BI;
345 }
346 cantFail(FpmWriter.writeObject(ThisByte));
347 }
348 assert(FpmWriter.bytesRemaining() == 0);
349}
350
352 MSFLayout &Layout) {
353 llvm::TimeTraceScope timeScope("Commit MSF");
354
356 if (!L)
357 return L.takeError();
358
359 Layout = std::move(*L);
360
361 uint64_t FileSize = uint64_t(Layout.SB->BlockSize) * Layout.SB->NumBlocks;
362 // Ensure that the file size is under the limit for the specified block size.
363 if (FileSize > getMaxFileSizeFromBlockSize(Layout.SB->BlockSize)) {
364 msf_error_code error_code = [](uint32_t BlockSize) {
365 switch (BlockSize) {
366 case 8192:
368 case 16384:
370 case 32768:
372 default:
374 }
375 }(Layout.SB->BlockSize);
376
378 error_code,
379 formatv("File size {0,1:N} too large for current PDB page size {1}",
380 FileSize, Layout.SB->BlockSize));
381 }
382
383 uint64_t NumDirectoryBlocks =
385 uint64_t DirectoryBlockMapSize =
386 NumDirectoryBlocks * sizeof(support::ulittle32_t);
387 if (DirectoryBlockMapSize > Layout.SB->BlockSize) {
389 formatv("The directory block map ({0} bytes) "
390 "doesn't fit in a block ({1} bytes)",
391 DirectoryBlockMapSize,
392 Layout.SB->BlockSize));
393 }
394
395 auto OutFileOrError = FileOutputBuffer::create(Path, FileSize);
396 if (auto EC = OutFileOrError.takeError())
397 return std::move(EC);
398
399 FileBufferByteStream Buffer(std::move(*OutFileOrError),
401 BinaryStreamWriter Writer(Buffer);
402
403 if (auto EC = Writer.writeObject(*Layout.SB))
404 return std::move(EC);
405
406 commitFpm(Buffer, Layout, Allocator);
407
408 uint32_t BlockMapOffset =
410 Writer.setOffset(BlockMapOffset);
411 if (auto EC = Writer.writeArray(Layout.DirectoryBlocks))
412 return std::move(EC);
413
415 Layout, Buffer, Allocator);
416 BinaryStreamWriter DW(*DirStream);
417 if (auto EC = DW.writeInteger<uint32_t>(Layout.StreamSizes.size()))
418 return std::move(EC);
419
420 if (auto EC = DW.writeArray(Layout.StreamSizes))
421 return std::move(EC);
422
423 for (const auto &Blocks : Layout.StreamMap) {
424 if (auto EC = DW.writeArray(Blocks))
425 return std::move(EC);
426 }
427
428 return std::move(Buffer);
429}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define I(x, y, z)
Definition MD5.cpp:57
static const uint32_t kFreePageMap1Block
static void commitFpm(WritableBinaryStream &MsfBuffer, const MSFLayout &Layout, BumpPtrAllocator &Allocator)
static const uint32_t kSuperBlockBlock
static const uint32_t kFreePageMap0Block
static const uint32_t kDefaultBlockMapAddr
static const uint32_t kNumReservedPages
static const uint32_t kDefaultFreePageMap
#define P(N)
Basic Register Allocator
static const int BlockSize
Definition TarWriter.cpp:33
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Provides write only access to a subclass of WritableBinaryStream.
Error writeArray(ArrayRef< T > Array)
Writes an array of objects of type T to the underlying stream, as if by using memcpy.
Error writeInteger(T Value)
Write the integer Value to the underlying stream in the specified endianness.
Error writeObject(const T &Obj)
Writes the object Obj to the underlying stream, as if by using memcpy.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:179
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
An implementation of WritableBinaryStream backed by an llvm FileOutputBuffer.
static LLVM_ABI Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
A BinaryStream which can be read from as well as written to.
LLVM_ABI uint32_t getNumStreams() const
Get the total number of streams in the MSF layout.
LLVM_ABI Error setBlockMapAddr(uint32_t Addr)
Request the block map to be at a specific block address.
LLVM_ABI ArrayRef< uint32_t > getStreamBlocks(uint32_t StreamIdx) const
Get the list of blocks allocated to a particular stream.
LLVM_ABI Error setDirectoryBlocksHint(ArrayRef< uint32_t > DirBlocks)
LLVM_ABI uint32_t getTotalBlockCount() const
Get the total number of blocks in the MSF file.
LLVM_ABI uint32_t getNumFreeBlocks() const
Get the total number of blocks that exist in the MSF file but are not allocated to any valid data.
LLVM_ABI Error setStreamSize(uint32_t Idx, uint32_t Size)
Update the size of an existing stream.
LLVM_ABI Expected< FileBufferByteStream > commit(StringRef Path, MSFLayout &Layout)
Write the MSF layout to the underlying file.
LLVM_ABI Expected< MSFLayout > generateLayout()
Finalize the layout and build the headers and structures that describe the MSF layout and can be writ...
LLVM_ABI bool isBlockFree(uint32_t Idx) const
Check whether a particular block is allocated or free.
LLVM_ABI void setFreePageMap(uint32_t Fpm)
LLVM_ABI uint32_t getStreamSize(uint32_t StreamIdx) const
Get the size of a stream by index.
static LLVM_ABI Expected< MSFBuilder > create(BumpPtrAllocator &Allocator, uint32_t BlockSize, uint32_t MinBlockCount=0, bool CanGrow=true)
Create a new MSFBuilder.
LLVM_ABI uint32_t getNumUsedBlocks() const
Get the total number of blocks that will be allocated to actual data in this MSF file.
LLVM_ABI void setUnknown1(uint32_t Unk1)
LLVM_ABI Expected< uint32_t > addStream(uint32_t Size, ArrayRef< uint32_t > Blocks)
Add a stream to the MSF file with the given size, occupying the given list of blocks.
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)
uint32_t getMinimumBlockCount()
Definition MSFCommon.h:126
uint64_t blockToOffset(uint64_t BlockNumber, uint64_t BlockSize)
Definition MSFCommon.h:136
uint64_t getMaxFileSizeFromBlockSize(uint32_t Size)
Given the specified block size, returns the maximum possible file size.
Definition MSFCommon.h:112
bool isValidBlockSize(uint32_t Size)
Definition MSFCommon.h:91
uint64_t bytesToBlocks(uint64_t NumBytes, uint64_t BlockSize)
Definition MSFCommon.h:132
static const char Magic[]
Definition MSFCommon.h:24
detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, unaligned > ulittle32_t
Definition Endian.h:270
This is an optimization pass for GlobalISel generic memory operations.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
ArrayRef(const T &OneElt) -> ArrayRef< T >
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
ArrayRef< support::ulittle32_t > StreamSizes
Definition MSFCommon.h:68
ArrayRef< support::ulittle32_t > DirectoryBlocks
Definition MSFCommon.h:67
const SuperBlock * SB
Definition MSFCommon.h:65
BitVector FreePageMap
Definition MSFCommon.h:66
std::vector< ArrayRef< support::ulittle32_t > > StreamMap
Definition MSFCommon.h:69
support::ulittle32_t NumBlocks
Definition MSFCommon.h:43
support::ulittle32_t BlockSize
Definition MSFCommon.h:37
support::ulittle32_t Unknown1
Definition MSFCommon.h:47
char MagicBytes[sizeof(Magic)]
Definition MSFCommon.h:33
support::ulittle32_t NumDirectoryBytes
Definition MSFCommon.h:45
support::ulittle32_t BlockMapAddr
Definition MSFCommon.h:49
support::ulittle32_t FreeBlockMapBlock
Definition MSFCommon.h:39