DbiStreamBuilder.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===//
  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. #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/BinaryFormat/COFF.h"
  11. #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
  12. #include "llvm/DebugInfo/MSF/MSFBuilder.h"
  13. #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
  14. #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
  15. #include "llvm/DebugInfo/PDB/Native/RawError.h"
  16. #include "llvm/Object/COFF.h"
  17. #include "llvm/Support/BinaryStreamWriter.h"
  18. #include "llvm/Support/Parallel.h"
  19. using namespace llvm;
  20. using namespace llvm::codeview;
  21. using namespace llvm::msf;
  22. using namespace llvm::pdb;
  23. DbiStreamBuilder::DbiStreamBuilder(msf::MSFBuilder &Msf)
  24. : Msf(Msf), Allocator(Msf.getAllocator()), Age(1), BuildNumber(0),
  25. PdbDllVersion(0), PdbDllRbld(0), Flags(0), MachineType(PDB_Machine::x86),
  26. Header(nullptr) {}
  27. DbiStreamBuilder::~DbiStreamBuilder() = default;
  28. void DbiStreamBuilder::setVersionHeader(PdbRaw_DbiVer V) { VerHeader = V; }
  29. void DbiStreamBuilder::setAge(uint32_t A) { Age = A; }
  30. void DbiStreamBuilder::setBuildNumber(uint16_t B) { BuildNumber = B; }
  31. void DbiStreamBuilder::setBuildNumber(uint8_t Major, uint8_t Minor) {
  32. BuildNumber = (uint16_t(Major) << DbiBuildNo::BuildMajorShift) &
  33. DbiBuildNo::BuildMajorMask;
  34. BuildNumber |= (uint16_t(Minor) << DbiBuildNo::BuildMinorShift) &
  35. DbiBuildNo::BuildMinorMask;
  36. BuildNumber |= DbiBuildNo::NewVersionFormatMask;
  37. }
  38. void DbiStreamBuilder::setPdbDllVersion(uint16_t V) { PdbDllVersion = V; }
  39. void DbiStreamBuilder::setPdbDllRbld(uint16_t R) { PdbDllRbld = R; }
  40. void DbiStreamBuilder::setFlags(uint16_t F) { Flags = F; }
  41. void DbiStreamBuilder::setMachineType(PDB_Machine M) { MachineType = M; }
  42. void DbiStreamBuilder::setMachineType(COFF::MachineTypes M) {
  43. // These enums are mirrors of each other, so we can just cast the value.
  44. MachineType = static_cast<pdb::PDB_Machine>(static_cast<unsigned>(M));
  45. }
  46. void DbiStreamBuilder::setGlobalsStreamIndex(uint32_t Index) {
  47. GlobalsStreamIndex = Index;
  48. }
  49. void DbiStreamBuilder::setSymbolRecordStreamIndex(uint32_t Index) {
  50. SymRecordStreamIndex = Index;
  51. }
  52. void DbiStreamBuilder::setPublicsStreamIndex(uint32_t Index) {
  53. PublicsStreamIndex = Index;
  54. }
  55. void DbiStreamBuilder::addNewFpoData(const codeview::FrameData &FD) {
  56. if (!NewFpoData)
  57. NewFpoData.emplace(false);
  58. NewFpoData->addFrameData(FD);
  59. }
  60. void DbiStreamBuilder::addOldFpoData(const object::FpoData &FD) {
  61. OldFpoData.push_back(FD);
  62. }
  63. Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
  64. ArrayRef<uint8_t> Data) {
  65. assert(Type != DbgHeaderType::NewFPO &&
  66. "NewFPO data should be written via addFrameData()!");
  67. DbgStreams[(int)Type] = DebugStream{};
  68. DbgStreams[(int)Type]->Size = Data.size();
  69. DbgStreams[(int)Type]->WriteFn = [Data](BinaryStreamWriter &Writer) {
  70. return Writer.writeArray(Data);
  71. };
  72. return Error::success();
  73. }
  74. uint32_t DbiStreamBuilder::addECName(StringRef Name) {
  75. return ECNamesBuilder.insert(Name);
  76. }
  77. uint32_t DbiStreamBuilder::calculateSerializedLength() const {
  78. // For now we only support serializing the header.
  79. return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
  80. calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
  81. calculateSectionMapStreamSize() + calculateDbgStreamsSize() +
  82. ECNamesBuilder.calculateSerializedSize();
  83. }
  84. Expected<DbiModuleDescriptorBuilder &>
  85. DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
  86. uint32_t Index = ModiList.size();
  87. ModiList.push_back(
  88. std::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf));
  89. return *ModiList.back();
  90. }
  91. Error DbiStreamBuilder::addModuleSourceFile(DbiModuleDescriptorBuilder &Module,
  92. StringRef File) {
  93. uint32_t Index = SourceFileNames.size();
  94. SourceFileNames.insert(std::make_pair(File, Index));
  95. Module.addSourceFile(File);
  96. return Error::success();
  97. }
  98. Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) {
  99. auto NameIter = SourceFileNames.find(File);
  100. if (NameIter == SourceFileNames.end())
  101. return make_error<RawError>(raw_error_code::no_entry,
  102. "The specified source file was not found");
  103. return NameIter->getValue();
  104. }
  105. uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
  106. uint32_t Size = 0;
  107. for (const auto &M : ModiList)
  108. Size += M->calculateSerializedLength();
  109. return Size;
  110. }
  111. uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
  112. if (SectionContribs.empty())
  113. return 0;
  114. return sizeof(enum PdbRaw_DbiSecContribVer) +
  115. sizeof(SectionContribs[0]) * SectionContribs.size();
  116. }
  117. uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
  118. if (SectionMap.empty())
  119. return 0;
  120. return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
  121. }
  122. uint32_t DbiStreamBuilder::calculateNamesOffset() const {
  123. uint32_t Offset = 0;
  124. Offset += sizeof(ulittle16_t); // NumModules
  125. Offset += sizeof(ulittle16_t); // NumSourceFiles
  126. Offset += ModiList.size() * sizeof(ulittle16_t); // ModIndices
  127. Offset += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
  128. uint32_t NumFileInfos = 0;
  129. for (const auto &M : ModiList)
  130. NumFileInfos += M->source_files().size();
  131. Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
  132. return Offset;
  133. }
  134. uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
  135. uint32_t Size = calculateNamesOffset();
  136. Size += calculateNamesBufferSize();
  137. return alignTo(Size, sizeof(uint32_t));
  138. }
  139. uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
  140. uint32_t Size = 0;
  141. for (const auto &F : SourceFileNames) {
  142. Size += F.getKeyLength() + 1; // Names[I];
  143. }
  144. return Size;
  145. }
  146. uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
  147. return DbgStreams.size() * sizeof(uint16_t);
  148. }
  149. Error DbiStreamBuilder::generateFileInfoSubstream() {
  150. uint32_t Size = calculateFileInfoSubstreamSize();
  151. auto Data = Allocator.Allocate<uint8_t>(Size);
  152. uint32_t NamesOffset = calculateNamesOffset();
  153. FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
  154. llvm::support::little);
  155. WritableBinaryStreamRef MetadataBuffer =
  156. WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
  157. BinaryStreamWriter MetadataWriter(MetadataBuffer);
  158. uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size());
  159. uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
  160. if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
  161. return EC;
  162. if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
  163. return EC;
  164. for (uint16_t I = 0; I < ModiCount; ++I) {
  165. if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
  166. return EC;
  167. }
  168. for (const auto &MI : ModiList) {
  169. FileCount = static_cast<uint16_t>(MI->source_files().size());
  170. if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
  171. return EC;
  172. }
  173. // Before writing the FileNameOffsets array, write the NamesBuffer array.
  174. // A side effect of this is that this will actually compute the various
  175. // file name offsets, so we can then go back and write the FileNameOffsets
  176. // array to the other substream.
  177. NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
  178. BinaryStreamWriter NameBufferWriter(NamesBuffer);
  179. for (auto &Name : SourceFileNames) {
  180. Name.second = NameBufferWriter.getOffset();
  181. if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
  182. return EC;
  183. }
  184. for (const auto &MI : ModiList) {
  185. for (StringRef Name : MI->source_files()) {
  186. auto Result = SourceFileNames.find(Name);
  187. if (Result == SourceFileNames.end())
  188. return make_error<RawError>(raw_error_code::no_entry,
  189. "The source file was not found.");
  190. if (auto EC = MetadataWriter.writeInteger(Result->second))
  191. return EC;
  192. }
  193. }
  194. if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t)))
  195. return EC;
  196. if (NameBufferWriter.bytesRemaining() > 0)
  197. return make_error<RawError>(raw_error_code::invalid_format,
  198. "The names buffer contained unexpected data.");
  199. if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
  200. return make_error<RawError>(
  201. raw_error_code::invalid_format,
  202. "The metadata buffer contained unexpected data.");
  203. return Error::success();
  204. }
  205. Error DbiStreamBuilder::finalize() {
  206. if (Header)
  207. return Error::success();
  208. for (auto &MI : ModiList)
  209. MI->finalize();
  210. if (auto EC = generateFileInfoSubstream())
  211. return EC;
  212. DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
  213. ::memset(H, 0, sizeof(DbiStreamHeader));
  214. H->VersionHeader = *VerHeader;
  215. H->VersionSignature = -1;
  216. H->Age = Age;
  217. H->BuildNumber = BuildNumber;
  218. H->Flags = Flags;
  219. H->PdbDllRbld = PdbDllRbld;
  220. H->PdbDllVersion = PdbDllVersion;
  221. H->MachineType = static_cast<uint16_t>(MachineType);
  222. H->ECSubstreamSize = ECNamesBuilder.calculateSerializedSize();
  223. H->FileInfoSize = FileInfoBuffer.getLength();
  224. H->ModiSubstreamSize = calculateModiSubstreamSize();
  225. H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
  226. H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
  227. H->SectionMapSize = calculateSectionMapStreamSize();
  228. H->TypeServerSize = 0;
  229. H->SymRecordStreamIndex = SymRecordStreamIndex;
  230. H->PublicSymbolStreamIndex = PublicsStreamIndex;
  231. H->MFCTypeServerIndex = 0; // Not sure what this is, but link.exe writes 0.
  232. H->GlobalSymbolStreamIndex = GlobalsStreamIndex;
  233. Header = H;
  234. return Error::success();
  235. }
  236. Error DbiStreamBuilder::finalizeMsfLayout() {
  237. if (NewFpoData) {
  238. DbgStreams[(int)DbgHeaderType::NewFPO] = DebugStream{};
  239. DbgStreams[(int)DbgHeaderType::NewFPO]->Size =
  240. NewFpoData->calculateSerializedSize();
  241. DbgStreams[(int)DbgHeaderType::NewFPO]->WriteFn =
  242. [this](BinaryStreamWriter &Writer) {
  243. return NewFpoData->commit(Writer);
  244. };
  245. }
  246. if (!OldFpoData.empty()) {
  247. DbgStreams[(int)DbgHeaderType::FPO] = DebugStream{};
  248. DbgStreams[(int)DbgHeaderType::FPO]->Size =
  249. sizeof(object::FpoData) * OldFpoData.size();
  250. DbgStreams[(int)DbgHeaderType::FPO]->WriteFn =
  251. [this](BinaryStreamWriter &Writer) {
  252. return Writer.writeArray(ArrayRef(OldFpoData));
  253. };
  254. }
  255. for (auto &S : DbgStreams) {
  256. if (!S)
  257. continue;
  258. auto ExpectedIndex = Msf.addStream(S->Size);
  259. if (!ExpectedIndex)
  260. return ExpectedIndex.takeError();
  261. S->StreamNumber = *ExpectedIndex;
  262. }
  263. for (auto &MI : ModiList) {
  264. if (auto EC = MI->finalizeMsfLayout())
  265. return EC;
  266. }
  267. uint32_t Length = calculateSerializedLength();
  268. if (auto EC = Msf.setStreamSize(StreamDBI, Length))
  269. return EC;
  270. return Error::success();
  271. }
  272. static uint16_t toSecMapFlags(uint32_t Flags) {
  273. uint16_t Ret = 0;
  274. if (Flags & COFF::IMAGE_SCN_MEM_READ)
  275. Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
  276. if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
  277. Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
  278. if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
  279. Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
  280. if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
  281. Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
  282. // This seems always 1.
  283. Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
  284. return Ret;
  285. }
  286. // Populate the Section Map from COFF section headers.
  287. //
  288. // A Section Map seem to be a copy of a COFF section list in other format.
  289. // I don't know why a PDB file contains both a COFF section header and
  290. // a Section Map, but it seems it must be present in a PDB.
  291. void DbiStreamBuilder::createSectionMap(
  292. ArrayRef<llvm::object::coff_section> SecHdrs) {
  293. int Idx = 0;
  294. auto Add = [&]() -> SecMapEntry & {
  295. SectionMap.emplace_back();
  296. auto &Entry = SectionMap.back();
  297. memset(&Entry, 0, sizeof(Entry));
  298. Entry.Frame = Idx + 1;
  299. // We don't know the meaning of these fields yet.
  300. Entry.SecName = UINT16_MAX;
  301. Entry.ClassName = UINT16_MAX;
  302. return Entry;
  303. };
  304. for (auto &Hdr : SecHdrs) {
  305. auto &Entry = Add();
  306. Entry.Flags = toSecMapFlags(Hdr.Characteristics);
  307. Entry.SecByteLength = Hdr.VirtualSize;
  308. ++Idx;
  309. }
  310. // The last entry is for absolute symbols.
  311. auto &Entry = Add();
  312. Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
  313. static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
  314. Entry.SecByteLength = UINT32_MAX;
  315. }
  316. Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
  317. WritableBinaryStreamRef MsfBuffer) {
  318. if (auto EC = finalize())
  319. return EC;
  320. auto DbiS = WritableMappedBlockStream::createIndexedStream(
  321. Layout, MsfBuffer, StreamDBI, Allocator);
  322. BinaryStreamWriter Writer(*DbiS);
  323. if (auto EC = Writer.writeObject(*Header))
  324. return EC;
  325. for (auto &M : ModiList) {
  326. if (auto EC = M->commit(Writer))
  327. return EC;
  328. }
  329. // Commit symbol streams. This is a lot of data, so do it in parallel.
  330. if (auto EC = parallelForEachError(
  331. ModiList, [&](std::unique_ptr<DbiModuleDescriptorBuilder> &M) {
  332. return M->commitSymbolStream(Layout, MsfBuffer);
  333. }))
  334. return EC;
  335. if (!SectionContribs.empty()) {
  336. if (auto EC = Writer.writeEnum(DbiSecContribVer60))
  337. return EC;
  338. if (auto EC = Writer.writeArray(ArrayRef(SectionContribs)))
  339. return EC;
  340. }
  341. if (!SectionMap.empty()) {
  342. ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
  343. SecMapHeader SMHeader = {Size, Size};
  344. if (auto EC = Writer.writeObject(SMHeader))
  345. return EC;
  346. if (auto EC = Writer.writeArray(ArrayRef(SectionMap)))
  347. return EC;
  348. }
  349. if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
  350. return EC;
  351. if (auto EC = ECNamesBuilder.commit(Writer))
  352. return EC;
  353. for (auto &Stream : DbgStreams) {
  354. uint16_t StreamNumber = kInvalidStreamIndex;
  355. if (Stream)
  356. StreamNumber = Stream->StreamNumber;
  357. if (auto EC = Writer.writeInteger(StreamNumber))
  358. return EC;
  359. }
  360. for (auto &Stream : DbgStreams) {
  361. if (!Stream)
  362. continue;
  363. assert(Stream->StreamNumber != kInvalidStreamIndex);
  364. auto WritableStream = WritableMappedBlockStream::createIndexedStream(
  365. Layout, MsfBuffer, Stream->StreamNumber, Allocator);
  366. BinaryStreamWriter DbgStreamWriter(*WritableStream);
  367. if (auto EC = Stream->WriteFn(DbgStreamWriter))
  368. return EC;
  369. }
  370. if (Writer.bytesRemaining() > 0)
  371. return make_error<RawError>(raw_error_code::invalid_format,
  372. "Unexpected bytes found in DBI Stream");
  373. return Error::success();
  374. }