1 //===- MSFBuilder.cpp -----------------------------------------------------===//
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/ADT/ArrayRef.h"
11 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
12 #include "llvm/DebugInfo/MSF/MSFError.h"
13 #include "llvm/Support/Endian.h"
14 #include "llvm/Support/Error.h"
15 #include <algorithm>
16 #include <cassert>
17 #include <cstdint>
18 #include <cstring>
19 #include <memory>
20 #include <utility>
21 #include <vector>
22 
23 using namespace llvm;
24 using namespace llvm::msf;
25 using namespace llvm::support;
26 
27 static const uint32_t kSuperBlockBlock = 0;
28 static const uint32_t kFreePageMap0Block = 1;
29 static const uint32_t kFreePageMap1Block = 2;
30 static const uint32_t kNumReservedPages = 3;
31 
32 static const uint32_t kDefaultFreePageMap = kFreePageMap0Block;
33 static const uint32_t kDefaultBlockMapAddr = kNumReservedPages;
34 
35 MSFBuilder::MSFBuilder(uint32_t BlockSize, uint32_t MinBlockCount, bool CanGrow,
36                        BumpPtrAllocator &Allocator)
37     : Allocator(Allocator), IsGrowable(CanGrow),
38       FreePageMap(kDefaultFreePageMap), BlockSize(BlockSize),
39       MininumBlocks(MinBlockCount), BlockMapAddr(kDefaultBlockMapAddr),
40       FreeBlocks(MinBlockCount, true) {
41   FreeBlocks[kSuperBlockBlock] = false;
42   FreeBlocks[kFreePageMap0Block] = false;
43   FreeBlocks[kFreePageMap1Block] = false;
44   FreeBlocks[BlockMapAddr] = false;
45 }
46 
47 Expected<MSFBuilder> MSFBuilder::create(BumpPtrAllocator &Allocator,
48                                         uint32_t BlockSize,
49                                         uint32_t MinBlockCount, bool CanGrow) {
50   if (!isValidBlockSize(BlockSize))
51     return make_error<MSFError>(msf_error_code::invalid_format,
52                                 "The requested block size is unsupported");
53 
54   return MSFBuilder(BlockSize,
55                     std::max(MinBlockCount, msf::getMinimumBlockCount()),
56                     CanGrow, Allocator);
57 }
58 
59 Error MSFBuilder::setBlockMapAddr(uint32_t Addr) {
60   if (Addr == BlockMapAddr)
61     return Error::success();
62 
63   if (Addr >= FreeBlocks.size()) {
64     if (!IsGrowable)
65       return make_error<MSFError>(msf_error_code::insufficient_buffer,
66                                   "Cannot grow the number of blocks");
67     FreeBlocks.resize(Addr + 1, true);
68   }
69 
70   if (!isBlockFree(Addr))
71     return make_error<MSFError>(
72         msf_error_code::block_in_use,
73         "Requested block map address is already in use");
74   FreeBlocks[BlockMapAddr] = true;
75   FreeBlocks[Addr] = false;
76   BlockMapAddr = Addr;
77   return Error::success();
78 }
79 
80 void MSFBuilder::setFreePageMap(uint32_t Fpm) { FreePageMap = Fpm; }
81 
82 void MSFBuilder::setUnknown1(uint32_t Unk1) { Unknown1 = Unk1; }
83 
84 Error MSFBuilder::setDirectoryBlocksHint(ArrayRef<uint32_t> DirBlocks) {
85   for (auto B : DirectoryBlocks)
86     FreeBlocks[B] = true;
87   for (auto B : DirBlocks) {
88     if (!isBlockFree(B)) {
89       return make_error<MSFError>(msf_error_code::unspecified,
90                                   "Attempt to reuse an allocated block");
91     }
92     FreeBlocks[B] = false;
93   }
94 
95   DirectoryBlocks = DirBlocks;
96   return Error::success();
97 }
98 
99 Error MSFBuilder::allocateBlocks(uint32_t NumBlocks,
100                                  MutableArrayRef<uint32_t> Blocks) {
101   if (NumBlocks == 0)
102     return Error::success();
103 
104   uint32_t NumFreeBlocks = FreeBlocks.count();
105   if (NumFreeBlocks < NumBlocks) {
106     if (!IsGrowable)
107       return make_error<MSFError>(msf_error_code::insufficient_buffer,
108                                   "There are no free Blocks in the file");
109     uint32_t AllocBlocks = NumBlocks - NumFreeBlocks;
110     FreeBlocks.resize(AllocBlocks + FreeBlocks.size(), true);
111   }
112 
113   int I = 0;
114   int Block = FreeBlocks.find_first();
115   do {
116     assert(Block != -1 && "We ran out of Blocks!");
117 
118     uint32_t NextBlock = static_cast<uint32_t>(Block);
119     Blocks[I++] = NextBlock;
120     FreeBlocks.reset(NextBlock);
121     Block = FreeBlocks.find_next(Block);
122   } while (--NumBlocks > 0);
123   return Error::success();
124 }
125 
126 uint32_t MSFBuilder::getNumUsedBlocks() const {
127   return getTotalBlockCount() - getNumFreeBlocks();
128 }
129 
130 uint32_t MSFBuilder::getNumFreeBlocks() const { return FreeBlocks.count(); }
131 
132 uint32_t MSFBuilder::getTotalBlockCount() const { return FreeBlocks.size(); }
133 
134 bool MSFBuilder::isBlockFree(uint32_t Idx) const { return FreeBlocks[Idx]; }
135 
136 Expected<uint32_t> MSFBuilder::addStream(uint32_t Size,
137                                          ArrayRef<uint32_t> Blocks) {
138   // Add a new stream mapped to the specified blocks.  Verify that the specified
139   // blocks are both necessary and sufficient for holding the requested number
140   // of bytes, and verify that all requested blocks are free.
141   uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize);
142   if (ReqBlocks != Blocks.size())
143     return make_error<MSFError>(
144         msf_error_code::invalid_format,
145         "Incorrect number of blocks for requested stream size");
146   for (auto Block : Blocks) {
147     if (Block >= FreeBlocks.size())
148       FreeBlocks.resize(Block + 1, true);
149 
150     if (!FreeBlocks.test(Block))
151       return make_error<MSFError>(
152           msf_error_code::unspecified,
153           "Attempt to re-use an already allocated block");
154   }
155   // Mark all the blocks occupied by the new stream as not free.
156   for (auto Block : Blocks) {
157     FreeBlocks.reset(Block);
158   }
159   StreamData.push_back(std::make_pair(Size, Blocks));
160   return StreamData.size() - 1;
161 }
162 
163 Expected<uint32_t> MSFBuilder::addStream(uint32_t Size) {
164   uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize);
165   std::vector<uint32_t> NewBlocks;
166   NewBlocks.resize(ReqBlocks);
167   if (auto EC = allocateBlocks(ReqBlocks, NewBlocks))
168     return std::move(EC);
169   StreamData.push_back(std::make_pair(Size, NewBlocks));
170   return StreamData.size() - 1;
171 }
172 
173 Error MSFBuilder::setStreamSize(uint32_t Idx, uint32_t Size) {
174   uint32_t OldSize = getStreamSize(Idx);
175   if (OldSize == Size)
176     return Error::success();
177 
178   uint32_t NewBlocks = bytesToBlocks(Size, BlockSize);
179   uint32_t OldBlocks = bytesToBlocks(OldSize, BlockSize);
180 
181   if (NewBlocks > OldBlocks) {
182     uint32_t AddedBlocks = NewBlocks - OldBlocks;
183     // If we're growing, we have to allocate new Blocks.
184     std::vector<uint32_t> AddedBlockList;
185     AddedBlockList.resize(AddedBlocks);
186     if (auto EC = allocateBlocks(AddedBlocks, AddedBlockList))
187       return EC;
188     auto &CurrentBlocks = StreamData[Idx].second;
189     CurrentBlocks.insert(CurrentBlocks.end(), AddedBlockList.begin(),
190                          AddedBlockList.end());
191   } else if (OldBlocks > NewBlocks) {
192     // For shrinking, free all the Blocks in the Block map, update the stream
193     // data, then shrink the directory.
194     uint32_t RemovedBlocks = OldBlocks - NewBlocks;
195     auto CurrentBlocks = ArrayRef<uint32_t>(StreamData[Idx].second);
196     auto RemovedBlockList = CurrentBlocks.drop_front(NewBlocks);
197     for (auto P : RemovedBlockList)
198       FreeBlocks[P] = true;
199     StreamData[Idx].second = CurrentBlocks.drop_back(RemovedBlocks);
200   }
201 
202   StreamData[Idx].first = Size;
203   return Error::success();
204 }
205 
206 uint32_t MSFBuilder::getNumStreams() const { return StreamData.size(); }
207 
208 uint32_t MSFBuilder::getStreamSize(uint32_t StreamIdx) const {
209   return StreamData[StreamIdx].first;
210 }
211 
212 ArrayRef<uint32_t> MSFBuilder::getStreamBlocks(uint32_t StreamIdx) const {
213   return StreamData[StreamIdx].second;
214 }
215 
216 uint32_t MSFBuilder::computeDirectoryByteSize() const {
217   // The directory has the following layout, where each item is a ulittle32_t:
218   //    NumStreams
219   //    StreamSizes[NumStreams]
220   //    StreamBlocks[NumStreams][]
221   uint32_t Size = sizeof(ulittle32_t);             // NumStreams
222   Size += StreamData.size() * sizeof(ulittle32_t); // StreamSizes
223   for (const auto &D : StreamData) {
224     uint32_t ExpectedNumBlocks = bytesToBlocks(D.first, BlockSize);
225     assert(ExpectedNumBlocks == D.second.size() &&
226            "Unexpected number of blocks");
227     Size += ExpectedNumBlocks * sizeof(ulittle32_t);
228   }
229   return Size;
230 }
231 
232 Expected<MSFLayout> MSFBuilder::build() {
233   SuperBlock *SB = Allocator.Allocate<SuperBlock>();
234   MSFLayout L;
235   L.SB = SB;
236 
237   std::memcpy(SB->MagicBytes, Magic, sizeof(Magic));
238   SB->BlockMapAddr = BlockMapAddr;
239   SB->BlockSize = BlockSize;
240   SB->NumDirectoryBytes = computeDirectoryByteSize();
241   SB->FreeBlockMapBlock = FreePageMap;
242   SB->Unknown1 = Unknown1;
243 
244   uint32_t NumDirectoryBlocks = bytesToBlocks(SB->NumDirectoryBytes, BlockSize);
245   if (NumDirectoryBlocks > DirectoryBlocks.size()) {
246     // Our hint wasn't enough to satisfy the entire directory.  Allocate
247     // remaining pages.
248     std::vector<uint32_t> ExtraBlocks;
249     uint32_t NumExtraBlocks = NumDirectoryBlocks - DirectoryBlocks.size();
250     ExtraBlocks.resize(NumExtraBlocks);
251     if (auto EC = allocateBlocks(NumExtraBlocks, ExtraBlocks))
252       return std::move(EC);
253     DirectoryBlocks.insert(DirectoryBlocks.end(), ExtraBlocks.begin(),
254                            ExtraBlocks.end());
255   } else if (NumDirectoryBlocks < DirectoryBlocks.size()) {
256     uint32_t NumUnnecessaryBlocks = DirectoryBlocks.size() - NumDirectoryBlocks;
257     for (auto B :
258          ArrayRef<uint32_t>(DirectoryBlocks).drop_back(NumUnnecessaryBlocks))
259       FreeBlocks[B] = true;
260     DirectoryBlocks.resize(NumDirectoryBlocks);
261   }
262 
263   // Don't set the number of blocks in the file until after allocating Blocks
264   // for the directory, since the allocation might cause the file to need to
265   // grow.
266   SB->NumBlocks = FreeBlocks.size();
267 
268   ulittle32_t *DirBlocks = Allocator.Allocate<ulittle32_t>(NumDirectoryBlocks);
269   std::uninitialized_copy_n(DirectoryBlocks.begin(), NumDirectoryBlocks,
270                             DirBlocks);
271   L.DirectoryBlocks = ArrayRef<ulittle32_t>(DirBlocks, NumDirectoryBlocks);
272 
273   // The stream sizes should be re-allocated as a stable pointer and the stream
274   // map should have each of its entries allocated as a separate stable pointer.
275   if (!StreamData.empty()) {
276     ulittle32_t *Sizes = Allocator.Allocate<ulittle32_t>(StreamData.size());
277     L.StreamSizes = ArrayRef<ulittle32_t>(Sizes, StreamData.size());
278     L.StreamMap.resize(StreamData.size());
279     for (uint32_t I = 0; I < StreamData.size(); ++I) {
280       Sizes[I] = StreamData[I].first;
281       ulittle32_t *BlockList =
282           Allocator.Allocate<ulittle32_t>(StreamData[I].second.size());
283       std::uninitialized_copy_n(StreamData[I].second.begin(),
284                                 StreamData[I].second.size(), BlockList);
285       L.StreamMap[I] =
286           ArrayRef<ulittle32_t>(BlockList, StreamData[I].second.size());
287     }
288   }
289 
290   return L;
291 }
292