LLVM  5.0.0
DbiStreamBuilder.cpp
Go to the documentation of this file.
1 //===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===//
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 
11 
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/BinaryFormat/COFF.h"
19 #include "llvm/Object/COFF.h"
21 
22 using namespace llvm;
23 using namespace llvm::codeview;
24 using namespace llvm::msf;
25 using namespace llvm::pdb;
26 
27 DbiStreamBuilder::DbiStreamBuilder(msf::MSFBuilder &Msf)
28  : Msf(Msf), Allocator(Msf.getAllocator()), Age(1), BuildNumber(0),
29  PdbDllVersion(0), PdbDllRbld(0), Flags(0), MachineType(PDB_Machine::x86),
30  Header(nullptr), DbgStreams((int)DbgHeaderType::Max) {}
31 
33 
35 
37 
38 void DbiStreamBuilder::setBuildNumber(uint16_t B) { BuildNumber = B; }
39 
40 void DbiStreamBuilder::setPdbDllVersion(uint16_t V) { PdbDllVersion = V; }
41 
42 void DbiStreamBuilder::setPdbDllRbld(uint16_t R) { PdbDllRbld = R; }
43 
44 void DbiStreamBuilder::setFlags(uint16_t F) { Flags = F; }
45 
46 void DbiStreamBuilder::setMachineType(PDB_Machine M) { MachineType = M; }
47 
49  SectionMap = SecMap;
50 }
51 
53  SymRecordStreamIndex = Index;
54 }
55 
57  PublicsStreamIndex = Index;
58 }
59 
61  ArrayRef<uint8_t> Data) {
62  if (DbgStreams[(int)Type].StreamNumber != kInvalidStreamIndex)
63  return make_error<RawError>(raw_error_code::duplicate_entry,
64  "The specified stream type already exists");
65  auto ExpectedIndex = Msf.addStream(Data.size());
66  if (!ExpectedIndex)
67  return ExpectedIndex.takeError();
68  uint32_t Index = std::move(*ExpectedIndex);
69  DbgStreams[(int)Type].Data = Data;
70  DbgStreams[(int)Type].StreamNumber = Index;
71  return Error::success();
72 }
73 
75  return ECNamesBuilder.insert(Name);
76 }
77 
79  // For now we only support serializing the header.
80  return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
81  calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
82  calculateSectionMapStreamSize() + calculateDbgStreamsSize() +
83  ECNamesBuilder.calculateSerializedSize();
84 }
85 
88  uint32_t Index = ModiList.size();
89  auto MIB =
90  llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf);
91  auto M = MIB.get();
92  auto Result = ModiMap.insert(std::make_pair(ModuleName, std::move(MIB)));
93 
94  if (!Result.second)
95  return make_error<RawError>(raw_error_code::duplicate_entry,
96  "The specified module already exists");
97  ModiList.push_back(M);
98  return *M;
99 }
100 
102  auto ModIter = ModiMap.find(Module);
103  if (ModIter == ModiMap.end())
104  return make_error<RawError>(raw_error_code::no_entry,
105  "The specified module was not found");
106  return addModuleSourceFile(*ModIter->second, File);
107 }
108 
110  StringRef File) {
111  uint32_t Index = SourceFileNames.size();
112  SourceFileNames.insert(std::make_pair(File, Index));
113  Module.addSourceFile(File);
114  return Error::success();
115 }
116 
118  auto NameIter = SourceFileNames.find(File);
119  if (NameIter == SourceFileNames.end())
120  return make_error<RawError>(raw_error_code::no_entry,
121  "The specified source file was not found");
122  return NameIter->getValue();
123 }
124 
125 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
126  uint32_t Size = 0;
127  for (const auto &M : ModiList)
128  Size += M->calculateSerializedLength();
129  return Size;
130 }
131 
132 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
133  if (SectionContribs.empty())
134  return 0;
135  return sizeof(enum PdbRaw_DbiSecContribVer) +
136  sizeof(SectionContribs[0]) * SectionContribs.size();
137 }
138 
139 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
140  if (SectionMap.empty())
141  return 0;
142  return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
143 }
144 
145 uint32_t DbiStreamBuilder::calculateNamesOffset() const {
146  uint32_t Offset = 0;
147  Offset += sizeof(ulittle16_t); // NumModules
148  Offset += sizeof(ulittle16_t); // NumSourceFiles
149  Offset += ModiList.size() * sizeof(ulittle16_t); // ModIndices
150  Offset += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
151  uint32_t NumFileInfos = 0;
152  for (const auto &M : ModiList)
153  NumFileInfos += M->source_files().size();
154  Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
155  return Offset;
156 }
157 
158 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
159  uint32_t Size = calculateNamesOffset();
160  Size += calculateNamesBufferSize();
161  return alignTo(Size, sizeof(uint32_t));
162 }
163 
164 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
165  uint32_t Size = 0;
166  for (const auto &F : SourceFileNames) {
167  Size += F.getKeyLength() + 1; // Names[I];
168  }
169  return Size;
170 }
171 
172 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
173  return DbgStreams.size() * sizeof(uint16_t);
174 }
175 
176 Error DbiStreamBuilder::generateFileInfoSubstream() {
177  uint32_t Size = calculateFileInfoSubstreamSize();
178  auto Data = Allocator.Allocate<uint8_t>(Size);
179  uint32_t NamesOffset = calculateNamesOffset();
180 
181  FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
183 
184  WritableBinaryStreamRef MetadataBuffer =
185  WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
186  BinaryStreamWriter MetadataWriter(MetadataBuffer);
187 
188  uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size());
189  uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
190  if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
191  return EC;
192  if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
193  return EC;
194  for (uint16_t I = 0; I < ModiCount; ++I) {
195  if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
196  return EC;
197  }
198  for (const auto &MI : ModiList) {
199  FileCount = static_cast<uint16_t>(MI->source_files().size());
200  if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
201  return EC;
202  }
203 
204  // Before writing the FileNameOffsets array, write the NamesBuffer array.
205  // A side effect of this is that this will actually compute the various
206  // file name offsets, so we can then go back and write the FileNameOffsets
207  // array to the other substream.
208  NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
209  BinaryStreamWriter NameBufferWriter(NamesBuffer);
210  for (auto &Name : SourceFileNames) {
211  Name.second = NameBufferWriter.getOffset();
212  if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
213  return EC;
214  }
215 
216  for (const auto &MI : ModiList) {
217  for (StringRef Name : MI->source_files()) {
218  auto Result = SourceFileNames.find(Name);
219  if (Result == SourceFileNames.end())
220  return make_error<RawError>(raw_error_code::no_entry,
221  "The source file was not found.");
222  if (auto EC = MetadataWriter.writeInteger(Result->second))
223  return EC;
224  }
225  }
226 
227  if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t)))
228  return EC;
229 
230  if (NameBufferWriter.bytesRemaining() > 0)
231  return make_error<RawError>(raw_error_code::invalid_format,
232  "The names buffer contained unexpected data.");
233 
234  if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
235  return make_error<RawError>(
237  "The metadata buffer contained unexpected data.");
238 
239  return Error::success();
240 }
241 
242 Error DbiStreamBuilder::finalize() {
243  if (Header)
244  return Error::success();
245 
246  for (auto &MI : ModiList)
247  MI->finalize();
248 
249  if (auto EC = generateFileInfoSubstream())
250  return EC;
251 
252  DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
253  ::memset(H, 0, sizeof(DbiStreamHeader));
254  H->VersionHeader = *VerHeader;
255  H->VersionSignature = -1;
256  H->Age = Age;
257  H->BuildNumber = BuildNumber;
258  H->Flags = Flags;
259  H->PdbDllRbld = PdbDllRbld;
260  H->PdbDllVersion = PdbDllVersion;
261  H->MachineType = static_cast<uint16_t>(MachineType);
262 
263  H->ECSubstreamSize = ECNamesBuilder.calculateSerializedSize();
264  H->FileInfoSize = FileInfoBuffer.getLength();
265  H->ModiSubstreamSize = calculateModiSubstreamSize();
266  H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
267  H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
268  H->SectionMapSize = calculateSectionMapStreamSize();
269  H->TypeServerSize = 0;
270  H->SymRecordStreamIndex = SymRecordStreamIndex;
271  H->PublicSymbolStreamIndex = PublicsStreamIndex;
274 
275  Header = H;
276  return Error::success();
277 }
278 
280  for (auto &MI : ModiList) {
281  if (auto EC = MI->finalizeMsfLayout())
282  return EC;
283  }
284 
286  if (auto EC = Msf.setStreamSize(StreamDBI, Length))
287  return EC;
288  return Error::success();
289 }
290 
291 static uint16_t toSecMapFlags(uint32_t Flags) {
292  uint16_t Ret = 0;
293  if (Flags & COFF::IMAGE_SCN_MEM_READ)
294  Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
295  if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
296  Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
297  if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
298  Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
299  if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
300  Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
301  if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
302  Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
303 
304  // This seems always 1.
305  Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
306 
307  return Ret;
308 }
309 
311  const object::coff_section *SecHdr) {
313  memset(&SC, 0, sizeof(SC));
314  SC.ISect = (uint16_t)~0U; // This represents nil.
315  SC.Off = SecHdr->PointerToRawData;
316  SC.Size = SecHdr->SizeOfRawData;
317  SC.Characteristics = SecHdr->Characteristics;
318  // Use the module index in the module dbi stream or nil (-1).
319  SC.Imod = ModuleDbi ? ModuleDbi->getModuleIndex() : (uint16_t)~0U;
320  SectionContribs.emplace_back(SC);
321 }
322 
323 // A utility function to create a Section Map for a given list of COFF sections.
324 //
325 // A Section Map seem to be a copy of a COFF section list in other format.
326 // I don't know why a PDB file contains both a COFF section header and
327 // a Section Map, but it seems it must be present in a PDB.
328 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
330  std::vector<SecMapEntry> Ret;
331  int Idx = 0;
332 
333  auto Add = [&]() -> SecMapEntry & {
334  Ret.emplace_back();
335  auto &Entry = Ret.back();
336  memset(&Entry, 0, sizeof(Entry));
337 
338  Entry.Frame = Idx + 1;
339 
340  // We don't know the meaning of these fields yet.
341  Entry.SecName = UINT16_MAX;
342  Entry.ClassName = UINT16_MAX;
343 
344  return Entry;
345  };
346 
347  for (auto &Hdr : SecHdrs) {
348  auto &Entry = Add();
349  Entry.Flags = toSecMapFlags(Hdr.Characteristics);
350  Entry.SecByteLength = Hdr.VirtualSize;
351  ++Idx;
352  }
353 
354  // The last entry is for absolute symbols.
355  auto &Entry = Add();
356  Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
357  static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
358  Entry.SecByteLength = UINT32_MAX;
359 
360  return Ret;
361 }
362 
364  WritableBinaryStreamRef MsfBuffer) {
365  if (auto EC = finalize())
366  return EC;
367 
368  auto DbiS = WritableMappedBlockStream::createIndexedStream(
369  Layout, MsfBuffer, StreamDBI, Allocator);
370 
371  BinaryStreamWriter Writer(*DbiS);
372  if (auto EC = Writer.writeObject(*Header))
373  return EC;
374 
375  for (auto &M : ModiList) {
376  if (auto EC = M->commit(Writer, Layout, MsfBuffer))
377  return EC;
378  }
379 
380  if (!SectionContribs.empty()) {
381  if (auto EC = Writer.writeEnum(DbiSecContribVer60))
382  return EC;
383  if (auto EC = Writer.writeArray(makeArrayRef(SectionContribs)))
384  return EC;
385  }
386 
387  if (!SectionMap.empty()) {
388  ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
389  SecMapHeader SMHeader = {Size, Size};
390  if (auto EC = Writer.writeObject(SMHeader))
391  return EC;
392  if (auto EC = Writer.writeArray(SectionMap))
393  return EC;
394  }
395 
396  if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
397  return EC;
398 
399  if (auto EC = ECNamesBuilder.commit(Writer))
400  return EC;
401 
402  for (auto &Stream : DbgStreams)
403  if (auto EC = Writer.writeInteger(Stream.StreamNumber))
404  return EC;
405 
406  for (auto &Stream : DbgStreams) {
407  if (Stream.StreamNumber == kInvalidStreamIndex)
408  continue;
409  auto WritableStream = WritableMappedBlockStream::createIndexedStream(
410  Layout, MsfBuffer, Stream.StreamNumber, Allocator);
411  BinaryStreamWriter DbgStreamWriter(*WritableStream);
412  if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
413  return EC;
414  }
415 
416  if (Writer.bytesRemaining() > 0)
417  return make_error<RawError>(raw_error_code::invalid_format,
418  "Unexpected bytes found in DBI Stream");
419  return Error::success();
420 }
support::little32_t FileInfoSize
Size of file info substream.
Definition: RawTypes.h:139
Error writeObject(const T &Obj)
Writes the object Obj to the underlying stream, as if by using memcpy.
uint32_t addECName(StringRef Name)
An implementation of BinaryStream which holds its entire data set in a single contiguous buffer...
uint32_t calculateSerializedLength() const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
support::little32_t VersionSignature
Definition: RawTypes.h:105
void setSectionMap(ArrayRef< SecMapEntry > SecMap)
RefType drop_front(uint32_t N) const
Return a new BinaryStreamRef with the first N elements removed.
void setMachineType(PDB_Machine M)
support::ulittle16_t GlobalSymbolStreamIndex
Global symbol stream #.
Definition: RawTypes.h:112
static std::vector< SecMapEntry > createSectionMap(ArrayRef< llvm::object::coff_section > SecHdrs)
support::ulittle32_t MFCTypeServerIndex
Index of MFC Type Server.
Definition: RawTypes.h:145
iterator find(StringRef Key)
Definition: StringMap.h:333
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
detail::packed_endian_specific_integral< uint16_t, little, unaligned > ulittle16_t
Definition: Endian.h:269
Error commit(BinaryStreamWriter &Writer) const
support::ulittle16_t BuildNumber
See DbiBuildNo structure.
Definition: RawTypes.h:115
support::little32_t TypeServerSize
Size of type server map.
Definition: RawTypes.h:142
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
void addSectionContrib(DbiModuleDescriptorBuilder *ModuleDbi, const llvm::object::coff_section *SecHdr)
support::little32_t SectionMapSize
Size of sec. map substream.
Definition: RawTypes.h:136
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
The fixed size header that appears at the beginning of the DBI Stream.
Definition: RawTypes.h:104
void setSymbolRecordStreamIndex(uint32_t Index)
support::little32_t ECSubstreamSize
Size of EC stream (what is EC?)
Definition: RawTypes.h:151
#define F(x, y, z)
Definition: MD5.cpp:55
Error addDbgStream(pdb::DbgHeaderType Type, ArrayRef< uint8_t > Data)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Error writeArray(ArrayRef< T > Array)
Writes an array of objects of type T to the underlying stream, as if by using memcpy.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
const char * Name
const uint16_t kInvalidStreamIndex
Definition: RawConstants.h:20
support::ulittle16_t PdbDllRbld
rbld number of mspdbNNN.dll
Definition: RawTypes.h:127
support::ulittle32_t Characteristics
Definition: COFF.h:427
support::little32_t Size
Definition: RawTypes.h:37
support::ulittle16_t Imod
Definition: RawTypes.h:39
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
detail::packed_endian_specific_integral< uint32_t, little, unaligned > ulittle32_t
Definition: Endian.h:271
Expected< uint32_t > getSourceFileNameIndex(StringRef FileName)
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:212
#define H(x, y, z)
Definition: MD5.cpp:57
Error writeStreamRef(BinaryStreamRef Ref)
Efficiently reads all data from Ref, and writes it to this stream.
#define A
Definition: LargeTest.cpp:12
unsigned size() const
Definition: StringMap.h:111
Provides write only access to a subclass of WritableBinaryStream.
void setVersionHeader(PdbRaw_DbiVer V)
Error writeInteger(T Value)
Write the the integer Value to the underlying stream in the specified endianness. ...
support::ulittle32_t SizeOfRawData
Definition: COFF.h:421
Error commit(const msf::MSFLayout &Layout, WritableBinaryStreamRef MsfBuffer)
support::little32_t Off
Definition: RawTypes.h:36
support::ulittle16_t PdbDllVersion
version of mspdbNNN.dll
Definition: RawTypes.h:121
Error setStreamSize(uint32_t Idx, uint32_t Size)
Update the size of an existing stream.
Definition: MSFBuilder.cpp:173
support::little32_t OptionalDbgHdrSize
Size of DbgHeader info.
Definition: RawTypes.h:148
support::ulittle16_t Flags
See DbiFlags enum.
Definition: RawTypes.h:154
Basic Register Allocator
support::ulittle16_t ISect
Definition: RawTypes.h:34
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
support::ulittle32_t PointerToRawData
Definition: COFF.h:422
support::ulittle32_t Characteristics
Definition: RawTypes.h:38
#define B
Definition: LargeTest.cpp:24
CHAIN = SC CHAIN, Imm128 - System call.
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.
Definition: MSFBuilder.cpp:136
PdbRaw_DbiSecContribVer
Definition: RawConstants.h:66
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:366
Expected< DbiModuleDescriptorBuilder & > addModuleInfo(StringRef ModuleName)
support::little32_t ModiSubstreamSize
Size of module info stream.
Definition: RawTypes.h:130
Error addModuleSourceFile(StringRef Module, StringRef File)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Error writeEnum(T Num)
Similar to writeInteger.
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
void setPublicsStreamIndex(uint32_t Index)
static uint16_t toSecMapFlags(uint32_t Flags)
uint32_t bytesRemaining() const
support::little32_t SecContrSubstreamSize
Size of sec. contrib stream.
Definition: RawTypes.h:133
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
support::ulittle32_t Age
How "old" is this DBI Stream. Should match the age of the PDB InfoStream.
Definition: RawTypes.h:109
support::ulittle16_t SymRecordStreamIndex
Symbol records stream #.
Definition: RawTypes.h:124
support::ulittle32_t VersionHeader
Definition: RawTypes.h:106
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
IRTranslator LLVM IR MI
support::ulittle16_t PublicSymbolStreamIndex
Public symbols stream #.
Definition: RawTypes.h:118
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
RefType keep_front(uint32_t N) const
Return a new BinaryStreamRef with only the first N elements remaining.
support::ulittle16_t MachineType
See PDB_MachineType enum.
Definition: RawTypes.h:157
uint32_t getLength() override
Return the number of bytes of data in this stream.
iterator end()
Definition: StringMap.h:318