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 10 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h" 11 12 #include "llvm/ADT/ArrayRef.h" 13 #include "llvm/BinaryFormat/COFF.h" 14 #include "llvm/DebugInfo/MSF/MSFBuilder.h" 15 #include "llvm/DebugInfo/MSF/MappedBlockStream.h" 16 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h" 17 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 18 #include "llvm/DebugInfo/PDB/Native/RawError.h" 19 #include "llvm/Object/COFF.h" 20 #include "llvm/Support/BinaryStreamWriter.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 32 DbiStreamBuilder::~DbiStreamBuilder() {} 33 34 void DbiStreamBuilder::setVersionHeader(PdbRaw_DbiVer V) { VerHeader = V; } 35 36 void DbiStreamBuilder::setAge(uint32_t A) { Age = A; } 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 48 void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) { 49 SectionMap = SecMap; 50 } 51 52 void DbiStreamBuilder::setSymbolRecordStreamIndex(uint32_t Index) { 53 SymRecordStreamIndex = Index; 54 } 55 56 void DbiStreamBuilder::setPublicsStreamIndex(uint32_t Index) { 57 PublicsStreamIndex = Index; 58 } 59 60 Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type, 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 74 uint32_t DbiStreamBuilder::addECName(StringRef Name) { 75 return ECNamesBuilder.insert(Name); 76 } 77 78 uint32_t DbiStreamBuilder::calculateSerializedLength() const { 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 86 Expected<DbiModuleDescriptorBuilder &> 87 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) { 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 101 Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) { 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 109 Error DbiStreamBuilder::addModuleSourceFile(DbiModuleDescriptorBuilder &Module, 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 117 Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) { 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), 182 llvm::support::little); 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>( 236 raw_error_code::invalid_format, 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; 272 H->MFCTypeServerIndex = kInvalidStreamIndex; 273 H->GlobalSymbolStreamIndex = kInvalidStreamIndex; 274 275 Header = H; 276 return Error::success(); 277 } 278 279 Error DbiStreamBuilder::finalizeMsfLayout() { 280 for (auto &MI : ModiList) { 281 if (auto EC = MI->finalizeMsfLayout()) 282 return EC; 283 } 284 285 uint32_t Length = calculateSerializedLength(); 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 310 void DbiStreamBuilder::addSectionContrib(DbiModuleDescriptorBuilder *ModuleDbi, 311 const object::coff_section *SecHdr) { 312 SectionContrib SC; 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( 329 ArrayRef<llvm::object::coff_section> SecHdrs) { 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 363 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout, 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 } 421