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/DebugInfo/MSF/MSFBuilder.h" 14 #include "llvm/DebugInfo/MSF/MappedBlockStream.h" 15 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h" 16 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 17 #include "llvm/DebugInfo/PDB/Native/RawError.h" 18 #include "llvm/Object/COFF.h" 19 #include "llvm/Support/BinaryStreamWriter.h" 20 #include "llvm/Support/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 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::setSectionContribs(ArrayRef<SectionContrib> Arr) { 49 SectionContribs = Arr; 50 } 51 52 void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) { 53 SectionMap = SecMap; 54 } 55 56 Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type, 57 ArrayRef<uint8_t> Data) { 58 if (DbgStreams[(int)Type].StreamNumber) 59 return make_error<RawError>(raw_error_code::duplicate_entry, 60 "The specified stream type already exists"); 61 auto ExpectedIndex = Msf.addStream(Data.size()); 62 if (!ExpectedIndex) 63 return ExpectedIndex.takeError(); 64 uint32_t Index = std::move(*ExpectedIndex); 65 DbgStreams[(int)Type].Data = Data; 66 DbgStreams[(int)Type].StreamNumber = Index; 67 return Error::success(); 68 } 69 70 uint32_t DbiStreamBuilder::calculateSerializedLength() const { 71 // For now we only support serializing the header. 72 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() + 73 calculateModiSubstreamSize() + calculateSectionContribsStreamSize() + 74 calculateSectionMapStreamSize() + calculateDbgStreamsSize(); 75 } 76 77 Expected<DbiModuleDescriptorBuilder &> 78 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) { 79 uint32_t Index = ModiList.size(); 80 auto MIB = 81 llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf); 82 auto M = MIB.get(); 83 auto Result = ModiMap.insert(std::make_pair(ModuleName, std::move(MIB))); 84 85 if (!Result.second) 86 return make_error<RawError>(raw_error_code::duplicate_entry, 87 "The specified module already exists"); 88 ModiList.push_back(M); 89 return *M; 90 } 91 92 Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) { 93 auto ModIter = ModiMap.find(Module); 94 if (ModIter == ModiMap.end()) 95 return make_error<RawError>(raw_error_code::no_entry, 96 "The specified module was not found"); 97 uint32_t Index = SourceFileNames.size(); 98 SourceFileNames.insert(std::make_pair(File, Index)); 99 auto &ModEntry = *ModIter; 100 ModEntry.second->addSourceFile(File); 101 return Error::success(); 102 } 103 104 Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) { 105 auto NameIter = SourceFileNames.find(File); 106 if (NameIter == SourceFileNames.end()) 107 return make_error<RawError>(raw_error_code::no_entry, 108 "The specified source file was not found"); 109 return NameIter->getValue(); 110 } 111 112 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const { 113 uint32_t Size = 0; 114 for (const auto &M : ModiList) 115 Size += M->calculateSerializedLength(); 116 return Size; 117 } 118 119 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const { 120 if (SectionContribs.empty()) 121 return 0; 122 return sizeof(enum PdbRaw_DbiSecContribVer) + 123 sizeof(SectionContribs[0]) * SectionContribs.size(); 124 } 125 126 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const { 127 if (SectionMap.empty()) 128 return 0; 129 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size(); 130 } 131 132 uint32_t DbiStreamBuilder::calculateNamesOffset() const { 133 uint32_t Offset = 0; 134 Offset += sizeof(ulittle16_t); // NumModules 135 Offset += sizeof(ulittle16_t); // NumSourceFiles 136 Offset += ModiList.size() * sizeof(ulittle16_t); // ModIndices 137 Offset += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts 138 uint32_t NumFileInfos = 0; 139 for (const auto &M : ModiList) 140 NumFileInfos += M->source_files().size(); 141 Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets 142 return Offset; 143 } 144 145 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const { 146 uint32_t Size = calculateNamesOffset(); 147 Size += calculateNamesBufferSize(); 148 return alignTo(Size, sizeof(uint32_t)); 149 } 150 151 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const { 152 uint32_t Size = 0; 153 for (const auto &F : SourceFileNames) { 154 Size += F.getKeyLength() + 1; // Names[I]; 155 } 156 return Size; 157 } 158 159 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const { 160 return DbgStreams.size() * sizeof(uint16_t); 161 } 162 163 Error DbiStreamBuilder::generateFileInfoSubstream() { 164 uint32_t Size = calculateFileInfoSubstreamSize(); 165 auto Data = Allocator.Allocate<uint8_t>(Size); 166 uint32_t NamesOffset = calculateNamesOffset(); 167 168 FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size), 169 llvm::support::little); 170 171 WritableBinaryStreamRef MetadataBuffer = 172 WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset); 173 BinaryStreamWriter MetadataWriter(MetadataBuffer); 174 175 uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size()); 176 uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size()); 177 if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules 178 return EC; 179 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles 180 return EC; 181 for (uint16_t I = 0; I < ModiCount; ++I) { 182 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices 183 return EC; 184 } 185 for (const auto &MI : ModiList) { 186 FileCount = static_cast<uint16_t>(MI->source_files().size()); 187 if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts 188 return EC; 189 } 190 191 // Before writing the FileNameOffsets array, write the NamesBuffer array. 192 // A side effect of this is that this will actually compute the various 193 // file name offsets, so we can then go back and write the FileNameOffsets 194 // array to the other substream. 195 NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset); 196 BinaryStreamWriter NameBufferWriter(NamesBuffer); 197 for (auto &Name : SourceFileNames) { 198 Name.second = NameBufferWriter.getOffset(); 199 if (auto EC = NameBufferWriter.writeCString(Name.getKey())) 200 return EC; 201 } 202 203 for (const auto &MI : ModiList) { 204 for (StringRef Name : MI->source_files()) { 205 auto Result = SourceFileNames.find(Name); 206 if (Result == SourceFileNames.end()) 207 return make_error<RawError>(raw_error_code::no_entry, 208 "The source file was not found."); 209 if (auto EC = MetadataWriter.writeInteger(Result->second)) 210 return EC; 211 } 212 } 213 214 if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t))) 215 return EC; 216 217 if (NameBufferWriter.bytesRemaining() > 0) 218 return make_error<RawError>(raw_error_code::invalid_format, 219 "The names buffer contained unexpected data."); 220 221 if (MetadataWriter.bytesRemaining() > sizeof(uint32_t)) 222 return make_error<RawError>( 223 raw_error_code::invalid_format, 224 "The metadata buffer contained unexpected data."); 225 226 return Error::success(); 227 } 228 229 Error DbiStreamBuilder::finalize() { 230 if (Header) 231 return Error::success(); 232 233 for (auto &MI : ModiList) 234 MI->finalize(); 235 236 if (auto EC = generateFileInfoSubstream()) 237 return EC; 238 239 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>(); 240 H->VersionHeader = *VerHeader; 241 H->VersionSignature = -1; 242 H->Age = Age; 243 H->BuildNumber = BuildNumber; 244 H->Flags = Flags; 245 H->PdbDllRbld = PdbDllRbld; 246 H->PdbDllVersion = PdbDllVersion; 247 H->MachineType = static_cast<uint16_t>(MachineType); 248 249 H->ECSubstreamSize = 0; 250 H->FileInfoSize = FileInfoBuffer.getLength(); 251 H->ModiSubstreamSize = calculateModiSubstreamSize(); 252 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t); 253 H->SecContrSubstreamSize = calculateSectionContribsStreamSize(); 254 H->SectionMapSize = calculateSectionMapStreamSize(); 255 H->TypeServerSize = 0; 256 H->SymRecordStreamIndex = kInvalidStreamIndex; 257 H->PublicSymbolStreamIndex = kInvalidStreamIndex; 258 H->MFCTypeServerIndex = kInvalidStreamIndex; 259 H->GlobalSymbolStreamIndex = kInvalidStreamIndex; 260 261 Header = H; 262 return Error::success(); 263 } 264 265 Error DbiStreamBuilder::finalizeMsfLayout() { 266 for (auto &MI : ModiList) { 267 if (auto EC = MI->finalizeMsfLayout()) 268 return EC; 269 } 270 271 uint32_t Length = calculateSerializedLength(); 272 if (auto EC = Msf.setStreamSize(StreamDBI, Length)) 273 return EC; 274 return Error::success(); 275 } 276 277 static uint16_t toSecMapFlags(uint32_t Flags) { 278 uint16_t Ret = 0; 279 if (Flags & COFF::IMAGE_SCN_MEM_READ) 280 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read); 281 if (Flags & COFF::IMAGE_SCN_MEM_WRITE) 282 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write); 283 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE) 284 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute); 285 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE) 286 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute); 287 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT)) 288 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit); 289 290 // This seems always 1. 291 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector); 292 293 return Ret; 294 } 295 296 // A utility function to create Section Contributions 297 // for a given input sections. 298 std::vector<SectionContrib> DbiStreamBuilder::createSectionContribs( 299 ArrayRef<object::coff_section> SecHdrs) { 300 std::vector<SectionContrib> Ret; 301 302 // Create a SectionContrib for each input section. 303 for (auto &Sec : SecHdrs) { 304 Ret.emplace_back(); 305 auto &Entry = Ret.back(); 306 memset(&Entry, 0, sizeof(Entry)); 307 308 Entry.Off = Sec.PointerToRawData; 309 Entry.Size = Sec.SizeOfRawData; 310 Entry.Characteristics = Sec.Characteristics; 311 } 312 return Ret; 313 } 314 315 // A utility function to create a Section Map for a given list of COFF sections. 316 // 317 // A Section Map seem to be a copy of a COFF section list in other format. 318 // I don't know why a PDB file contains both a COFF section header and 319 // a Section Map, but it seems it must be present in a PDB. 320 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap( 321 ArrayRef<llvm::object::coff_section> SecHdrs) { 322 std::vector<SecMapEntry> Ret; 323 int Idx = 0; 324 325 auto Add = [&]() -> SecMapEntry & { 326 Ret.emplace_back(); 327 auto &Entry = Ret.back(); 328 memset(&Entry, 0, sizeof(Entry)); 329 330 Entry.Frame = Idx + 1; 331 332 // We don't know the meaning of these fields yet. 333 Entry.SecName = UINT16_MAX; 334 Entry.ClassName = UINT16_MAX; 335 336 return Entry; 337 }; 338 339 for (auto &Hdr : SecHdrs) { 340 auto &Entry = Add(); 341 Entry.Flags = toSecMapFlags(Hdr.Characteristics); 342 Entry.SecByteLength = Hdr.VirtualSize; 343 ++Idx; 344 } 345 346 // The last entry is for absolute symbols. 347 auto &Entry = Add(); 348 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) | 349 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress); 350 Entry.SecByteLength = UINT32_MAX; 351 352 return Ret; 353 } 354 355 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout, 356 WritableBinaryStreamRef MsfBuffer) { 357 if (auto EC = finalize()) 358 return EC; 359 360 auto DbiS = WritableMappedBlockStream::createIndexedStream(Layout, MsfBuffer, 361 StreamDBI); 362 363 BinaryStreamWriter Writer(*DbiS); 364 if (auto EC = Writer.writeObject(*Header)) 365 return EC; 366 367 for (auto &M : ModiList) { 368 if (auto EC = M->commit(Writer, Layout, MsfBuffer)) 369 return EC; 370 } 371 372 if (!SectionContribs.empty()) { 373 if (auto EC = Writer.writeEnum(DbiSecContribVer60)) 374 return EC; 375 if (auto EC = Writer.writeArray(SectionContribs)) 376 return EC; 377 } 378 379 if (!SectionMap.empty()) { 380 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size()); 381 SecMapHeader SMHeader = {Size, Size}; 382 if (auto EC = Writer.writeObject(SMHeader)) 383 return EC; 384 if (auto EC = Writer.writeArray(SectionMap)) 385 return EC; 386 } 387 388 if (auto EC = Writer.writeStreamRef(FileInfoBuffer)) 389 return EC; 390 391 for (auto &Stream : DbgStreams) 392 if (auto EC = Writer.writeInteger(Stream.StreamNumber)) 393 return EC; 394 395 for (auto &Stream : DbgStreams) { 396 if (Stream.StreamNumber == kInvalidStreamIndex) 397 continue; 398 auto WritableStream = WritableMappedBlockStream::createIndexedStream( 399 Layout, MsfBuffer, Stream.StreamNumber); 400 BinaryStreamWriter DbgStreamWriter(*WritableStream); 401 if (auto EC = DbgStreamWriter.writeArray(Stream.Data)) 402 return EC; 403 } 404 405 if (Writer.bytesRemaining() > 0) 406 return make_error<RawError>(raw_error_code::invalid_format, 407 "Unexpected bytes found in DBI Stream"); 408 return Error::success(); 409 } 410