1 //===-- LVCodeViewReader.cpp ----------------------------------------------===// 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 // 9 // This implements the LVCodeViewReader class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/DebugInfo/LogicalView/Readers/LVCodeViewReader.h" 14 #include "llvm/DebugInfo/CodeView/CVSymbolVisitor.h" 15 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 16 #include "llvm/DebugInfo/CodeView/EnumTables.h" 17 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h" 18 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" 19 #include "llvm/DebugInfo/CodeView/SymbolVisitorCallbackPipeline.h" 20 #include "llvm/DebugInfo/LogicalView/Core/LVLine.h" 21 #include "llvm/DebugInfo/LogicalView/Core/LVScope.h" 22 #include "llvm/DebugInfo/LogicalView/Core/LVSymbol.h" 23 #include "llvm/DebugInfo/LogicalView/Core/LVType.h" 24 #include "llvm/DebugInfo/PDB/GenericError.h" 25 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 26 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h" 27 #include "llvm/DebugInfo/PDB/Native/InfoStream.h" 28 #include "llvm/DebugInfo/PDB/Native/LinePrinter.h" 29 #include "llvm/DebugInfo/PDB/Native/PDBFile.h" 30 #include "llvm/DebugInfo/PDB/Native/RawConstants.h" 31 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h" 32 #include "llvm/DebugInfo/PDB/Native/TpiStream.h" 33 #include "llvm/Demangle/Demangle.h" 34 #include "llvm/Object/COFF.h" 35 #include "llvm/Support/Errc.h" 36 #include "llvm/Support/Error.h" 37 #include "llvm/Support/FormatAdapters.h" 38 #include "llvm/Support/FormatVariadic.h" 39 #include "llvm/Support/WithColor.h" 40 41 using namespace llvm; 42 using namespace llvm::codeview; 43 using namespace llvm::logicalview; 44 using namespace llvm::msf; 45 using namespace llvm::object; 46 using namespace llvm::pdb; 47 48 #define DEBUG_TYPE "CodeViewReader" 49 50 StringRef LVCodeViewReader::getSymbolKindName(SymbolKind Kind) { 51 switch (Kind) { 52 #define SYMBOL_RECORD(EnumName, EnumVal, Name) \ 53 case EnumName: \ 54 return #EnumName; 55 #include "llvm/DebugInfo/CodeView/CodeViewSymbols.def" 56 default: 57 return "UnknownSym"; 58 } 59 llvm_unreachable("Unknown SymbolKind::Kind"); 60 } 61 62 std::string LVCodeViewReader::formatRegisterId(RegisterId Register, 63 CPUType CPU) { 64 #define RETURN_CASE(Enum, X, Ret) \ 65 case Enum::X: \ 66 return Ret; 67 68 if (CPU == CPUType::ARMNT) { 69 switch (Register) { 70 #define CV_REGISTERS_ARM 71 #define CV_REGISTER(name, val) RETURN_CASE(RegisterId, name, #name) 72 #include "llvm/DebugInfo/CodeView/CodeViewRegisters.def" 73 #undef CV_REGISTER 74 #undef CV_REGISTERS_ARM 75 76 default: 77 break; 78 } 79 } else if (CPU == CPUType::ARM64) { 80 switch (Register) { 81 #define CV_REGISTERS_ARM64 82 #define CV_REGISTER(name, val) RETURN_CASE(RegisterId, name, #name) 83 #include "llvm/DebugInfo/CodeView/CodeViewRegisters.def" 84 #undef CV_REGISTER 85 #undef CV_REGISTERS_ARM64 86 87 default: 88 break; 89 } 90 } else { 91 switch (Register) { 92 #define CV_REGISTERS_X86 93 #define CV_REGISTER(name, val) RETURN_CASE(RegisterId, name, #name) 94 #include "llvm/DebugInfo/CodeView/CodeViewRegisters.def" 95 #undef CV_REGISTER 96 #undef CV_REGISTERS_X86 97 98 default: 99 break; 100 } 101 } 102 return "formatUnknownEnum(Id)"; 103 } 104 105 void LVCodeViewReader::printRelocatedField(StringRef Label, 106 const coff_section *CoffSection, 107 uint32_t RelocOffset, 108 uint32_t Offset, 109 StringRef *RelocSym) { 110 StringRef SymStorage; 111 StringRef &Symbol = RelocSym ? *RelocSym : SymStorage; 112 if (!resolveSymbolName(CoffSection, RelocOffset, Symbol)) 113 W.printSymbolOffset(Label, Symbol, Offset); 114 else 115 W.printHex(Label, RelocOffset); 116 } 117 118 void LVCodeViewReader::getLinkageName(const coff_section *CoffSection, 119 uint32_t RelocOffset, uint32_t Offset, 120 StringRef *RelocSym) { 121 StringRef SymStorage; 122 StringRef &Symbol = RelocSym ? *RelocSym : SymStorage; 123 if (resolveSymbolName(CoffSection, RelocOffset, Symbol)) 124 Symbol = ""; 125 } 126 127 Expected<StringRef> 128 LVCodeViewReader::getFileNameForFileOffset(uint32_t FileOffset, 129 const SymbolGroup *SG) { 130 if (SG) { 131 Expected<StringRef> Filename = SG->getNameFromChecksums(FileOffset); 132 if (!Filename) { 133 consumeError(Filename.takeError()); 134 return StringRef(""); 135 } 136 return *Filename; 137 } 138 139 // The file checksum subsection should precede all references to it. 140 if (!CVFileChecksumTable.valid() || !CVStringTable.valid()) 141 return createStringError(object_error::parse_failed, getFileName()); 142 143 VarStreamArray<FileChecksumEntry>::Iterator Iter = 144 CVFileChecksumTable.getArray().at(FileOffset); 145 146 // Check if the file checksum table offset is valid. 147 if (Iter == CVFileChecksumTable.end()) 148 return createStringError(object_error::parse_failed, getFileName()); 149 150 Expected<StringRef> NameOrErr = CVStringTable.getString(Iter->FileNameOffset); 151 if (!NameOrErr) 152 return createStringError(object_error::parse_failed, getFileName()); 153 return *NameOrErr; 154 } 155 156 Error LVCodeViewReader::printFileNameForOffset(StringRef Label, 157 uint32_t FileOffset, 158 const SymbolGroup *SG) { 159 Expected<StringRef> NameOrErr = getFileNameForFileOffset(FileOffset, SG); 160 if (!NameOrErr) 161 return NameOrErr.takeError(); 162 W.printHex(Label, *NameOrErr, FileOffset); 163 return Error::success(); 164 } 165 166 void LVCodeViewReader::cacheRelocations() { 167 for (const SectionRef &Section : getObj().sections()) { 168 const coff_section *CoffSection = getObj().getCOFFSection(Section); 169 170 for (const RelocationRef &Relocacion : Section.relocations()) 171 RelocMap[CoffSection].push_back(Relocacion); 172 173 // Sort relocations by address. 174 llvm::sort(RelocMap[CoffSection], [](RelocationRef L, RelocationRef R) { 175 return L.getOffset() < R.getOffset(); 176 }); 177 } 178 } 179 180 // Given a section and an offset into this section the function returns the 181 // symbol used for the relocation at the offset. 182 Error LVCodeViewReader::resolveSymbol(const coff_section *CoffSection, 183 uint64_t Offset, SymbolRef &Sym) { 184 const auto &Relocations = RelocMap[CoffSection]; 185 basic_symbol_iterator SymI = getObj().symbol_end(); 186 for (const RelocationRef &Relocation : Relocations) { 187 uint64_t RelocationOffset = Relocation.getOffset(); 188 189 if (RelocationOffset == Offset) { 190 SymI = Relocation.getSymbol(); 191 break; 192 } 193 } 194 if (SymI == getObj().symbol_end()) 195 return make_error<StringError>("Unknown Symbol", inconvertibleErrorCode()); 196 Sym = *SymI; 197 return ErrorSuccess(); 198 } 199 200 // Given a section and an offset into this section the function returns the 201 // name of the symbol used for the relocation at the offset. 202 Error LVCodeViewReader::resolveSymbolName(const coff_section *CoffSection, 203 uint64_t Offset, StringRef &Name) { 204 SymbolRef Symbol; 205 if (Error E = resolveSymbol(CoffSection, Offset, Symbol)) 206 return E; 207 Expected<StringRef> NameOrErr = Symbol.getName(); 208 if (!NameOrErr) 209 return NameOrErr.takeError(); 210 Name = *NameOrErr; 211 return ErrorSuccess(); 212 } 213 214 // CodeView and DWARF can have references to compiler generated elements, 215 // used for initialization. The MSVC includes in the PDBs, internal compile 216 // units, associated with the MS runtime support. We mark them as 'system' 217 // and they are printed only if the command line option 'internal=system'. 218 bool LVCodeViewReader::isSystemEntry(LVElement *Element, StringRef Name) const { 219 Name = Name.empty() ? Element->getName() : Name; 220 auto Find = [=](const char *String) -> bool { 221 return StringRef::npos != Name.find(String); 222 }; 223 auto Starts = [=](const char *Pattern) -> bool { 224 return Name.starts_with(Pattern); 225 }; 226 auto CheckExclude = [&]() -> bool { 227 if (Starts("__") || Starts("_PMD") || Starts("_PMFN")) 228 return true; 229 if (Find("_s__")) 230 return true; 231 if (Find("_CatchableType") || Find("_TypeDescriptor")) 232 return true; 233 if (Find("Intermediate\\vctools")) 234 return true; 235 if (Find("$initializer$") || Find("dynamic initializer")) 236 return true; 237 if (Find("`vftable'") || Find("_GLOBAL__sub")) 238 return true; 239 return false; 240 }; 241 bool Excluded = CheckExclude(); 242 if (Excluded) 243 Element->setIsSystem(); 244 245 return Excluded; 246 } 247 248 Error LVCodeViewReader::collectInlineeInfo( 249 DebugInlineeLinesSubsectionRef &Lines, const llvm::pdb::SymbolGroup *SG) { 250 for (const InlineeSourceLine &Line : Lines) { 251 TypeIndex TIInlinee = Line.Header->Inlinee; 252 uint32_t LineNumber = Line.Header->SourceLineNum; 253 uint32_t FileOffset = Line.Header->FileID; 254 LLVM_DEBUG({ 255 DictScope S(W, "InlineeSourceLine"); 256 LogicalVisitor.printTypeIndex("Inlinee", TIInlinee, StreamTPI); 257 if (Error Err = printFileNameForOffset("FileID", FileOffset, SG)) 258 return Err; 259 W.printNumber("SourceLineNum", LineNumber); 260 261 if (Lines.hasExtraFiles()) { 262 W.printNumber("ExtraFileCount", Line.ExtraFiles.size()); 263 ListScope ExtraFiles(W, "ExtraFiles"); 264 for (const ulittle32_t &FID : Line.ExtraFiles) 265 if (Error Err = printFileNameForOffset("FileID", FID, SG)) 266 return Err; 267 } 268 }); 269 Expected<StringRef> NameOrErr = getFileNameForFileOffset(FileOffset, SG); 270 if (!NameOrErr) 271 return NameOrErr.takeError(); 272 LogicalVisitor.addInlineeInfo(TIInlinee, LineNumber, *NameOrErr); 273 } 274 275 return Error::success(); 276 } 277 278 Error LVCodeViewReader::traverseInlineeLines(StringRef Subsection) { 279 BinaryStreamReader SR(Subsection, llvm::endianness::little); 280 DebugInlineeLinesSubsectionRef Lines; 281 if (Error E = Lines.initialize(SR)) 282 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 283 284 return collectInlineeInfo(Lines); 285 } 286 287 Error LVCodeViewReader::createLines( 288 const FixedStreamArray<LineNumberEntry> &LineNumbers, LVAddress Addendum, 289 uint32_t Segment, uint32_t Begin, uint32_t Size, uint32_t NameIndex, 290 const SymbolGroup *SG) { 291 LLVM_DEBUG({ 292 uint32_t End = Begin + Size; 293 W.getOStream() << formatv("{0:x-4}:{1:x-8}-{2:x-8}\n", Segment, Begin, End); 294 }); 295 296 for (const LineNumberEntry &Line : LineNumbers) { 297 if (Line.Offset >= Size) 298 return createStringError(object_error::parse_failed, getFileName()); 299 300 LineInfo LI(Line.Flags); 301 302 LLVM_DEBUG({ 303 W.getOStream() << formatv( 304 "{0} {1:x-8}\n", utostr(LI.getStartLine()), 305 fmt_align(Begin + Line.Offset, AlignStyle::Right, 8, '0')); 306 }); 307 308 // The 'processLines()' function will move each created logical line 309 // to its enclosing logical scope, using the debug ranges information 310 // and they will be released when its scope parent is deleted. 311 LVLineDebug *LineDebug = createLineDebug(); 312 CULines.push_back(LineDebug); 313 LVAddress Address = linearAddress(Segment, Begin + Line.Offset); 314 LineDebug->setAddress(Address + Addendum); 315 316 if (LI.isAlwaysStepInto()) 317 LineDebug->setIsAlwaysStepInto(); 318 else if (LI.isNeverStepInto()) 319 LineDebug->setIsNeverStepInto(); 320 else 321 LineDebug->setLineNumber(LI.getStartLine()); 322 323 if (LI.isStatement()) 324 LineDebug->setIsNewStatement(); 325 326 Expected<StringRef> NameOrErr = getFileNameForFileOffset(NameIndex, SG); 327 if (!NameOrErr) 328 return NameOrErr.takeError(); 329 LineDebug->setFilename(*NameOrErr); 330 } 331 332 return Error::success(); 333 } 334 335 Error LVCodeViewReader::initializeFileAndStringTables( 336 BinaryStreamReader &Reader) { 337 while (Reader.bytesRemaining() > 0 && 338 (!CVFileChecksumTable.valid() || !CVStringTable.valid())) { 339 // The section consists of a number of subsection in the following format: 340 // |SubSectionType|SubSectionSize|Contents...| 341 uint32_t SubType, SubSectionSize; 342 343 if (Error E = Reader.readInteger(SubType)) 344 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 345 if (Error E = Reader.readInteger(SubSectionSize)) 346 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 347 348 StringRef Contents; 349 if (Error E = Reader.readFixedString(Contents, SubSectionSize)) 350 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 351 352 BinaryStreamRef ST(Contents, llvm::endianness::little); 353 switch (DebugSubsectionKind(SubType)) { 354 case DebugSubsectionKind::FileChecksums: 355 if (Error E = CVFileChecksumTable.initialize(ST)) 356 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 357 break; 358 case DebugSubsectionKind::StringTable: 359 if (Error E = CVStringTable.initialize(ST)) 360 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 361 break; 362 default: 363 break; 364 } 365 366 uint32_t PaddedSize = alignTo(SubSectionSize, 4); 367 if (Error E = Reader.skip(PaddedSize - SubSectionSize)) 368 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 369 } 370 371 return Error::success(); 372 } 373 374 Error LVCodeViewReader::loadTypeServer(TypeServer2Record &TS) { 375 LLVM_DEBUG({ 376 W.printString("Guid", formatv("{0}", TS.getGuid()).str()); 377 W.printNumber("Age", TS.getAge()); 378 W.printString("Name", TS.getName()); 379 }); 380 381 SmallString<128> ServerName(TS.getName()); 382 BuffOrErr = MemoryBuffer::getFile(ServerName); 383 if (BuffOrErr.getError()) { 384 // The server name does not exist. Try in the same directory as the 385 // input file. 386 ServerName = createAlternativePath(ServerName); 387 BuffOrErr = MemoryBuffer::getFile(ServerName); 388 if (BuffOrErr.getError()) { 389 // For the error message, use the original type server name. 390 return createStringError(errc::bad_file_descriptor, 391 "File '%s' does not exist.", 392 TS.getName().str().c_str()); 393 } 394 } 395 MemBuffer = std::move(BuffOrErr.get()); 396 397 // Check if the buffer corresponds to a PDB file. 398 assert(identify_magic((*MemBuffer).getBuffer()) == file_magic::pdb && 399 "Invalid PDB file."); 400 401 if (Error Err = loadDataForPDB(PDB_ReaderType::Native, ServerName, Session)) 402 return createStringError(errorToErrorCode(std::move(Err)), "%s", 403 ServerName.c_str()); 404 405 PdbSession.reset(static_cast<NativeSession *>(Session.release())); 406 PDBFile &Pdb = PdbSession->getPDBFile(); 407 408 // Just because a file with a matching name was found and it was an actual 409 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID 410 // must match the GUID specified in the TypeServer2 record. 411 Expected<InfoStream &> expectedInfo = Pdb.getPDBInfoStream(); 412 if (!expectedInfo || expectedInfo->getGuid() != TS.getGuid()) 413 return createStringError(errc::invalid_argument, "signature_out_of_date"); 414 415 // The reader needs to switch to a type server, to process the types from 416 // the server. We need to keep the original input source, as reading other 417 // sections will require the input associated with the loaded object file. 418 TypeServer = std::make_shared<InputFile>(&Pdb); 419 LogicalVisitor.setInput(TypeServer); 420 421 LazyRandomTypeCollection &Types = types(); 422 LazyRandomTypeCollection &Ids = ids(); 423 if (Error Err = traverseTypes(Pdb, Types, Ids)) 424 return Err; 425 426 return Error::success(); 427 } 428 429 Error LVCodeViewReader::loadPrecompiledObject(PrecompRecord &Precomp, 430 CVTypeArray &CVTypesObj) { 431 LLVM_DEBUG({ 432 W.printHex("Count", Precomp.getTypesCount()); 433 W.printHex("Signature", Precomp.getSignature()); 434 W.printString("PrecompFile", Precomp.getPrecompFilePath()); 435 }); 436 437 SmallString<128> ServerName(Precomp.getPrecompFilePath()); 438 BuffOrErr = MemoryBuffer::getFile(ServerName); 439 if (BuffOrErr.getError()) { 440 // The server name does not exist. Try in the directory as the input file. 441 ServerName = createAlternativePath(ServerName); 442 if (BuffOrErr.getError()) { 443 // For the error message, use the original type server name. 444 return createStringError(errc::bad_file_descriptor, 445 "File '%s' does not exist.", 446 Precomp.getPrecompFilePath().str().c_str()); 447 } 448 } 449 MemBuffer = std::move(BuffOrErr.get()); 450 451 Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(*MemBuffer); 452 if (errorToErrorCode(BinOrErr.takeError())) 453 return createStringError(errc::not_supported, 454 "Binary object format in '%s' is not supported.", 455 ServerName.c_str()); 456 457 Binary &BinaryObj = *BinOrErr.get(); 458 if (!BinaryObj.isCOFF()) 459 return createStringError(errc::not_supported, "'%s' is not a COFF object.", 460 ServerName.c_str()); 461 462 Builder = std::make_unique<AppendingTypeTableBuilder>(BuilderAllocator); 463 464 // The MSVC precompiled header object file, should contain just a single 465 // ".debug$P" section. 466 COFFObjectFile &Obj = *cast<COFFObjectFile>(&BinaryObj); 467 for (const SectionRef &Section : Obj.sections()) { 468 Expected<StringRef> SectionNameOrErr = Section.getName(); 469 if (!SectionNameOrErr) 470 return SectionNameOrErr.takeError(); 471 if (*SectionNameOrErr == ".debug$P") { 472 Expected<StringRef> DataOrErr = Section.getContents(); 473 if (!DataOrErr) 474 return DataOrErr.takeError(); 475 uint32_t Magic; 476 if (Error Err = consume(*DataOrErr, Magic)) 477 return Err; 478 if (Magic != COFF::DEBUG_SECTION_MAGIC) 479 return errorCodeToError(object_error::parse_failed); 480 481 ReaderPrecomp = std::make_unique<BinaryStreamReader>( 482 *DataOrErr, llvm::endianness::little); 483 cantFail( 484 ReaderPrecomp->readArray(CVTypesPrecomp, ReaderPrecomp->getLength())); 485 486 // Append all the type records up to the LF_ENDPRECOMP marker and 487 // check if the signatures match. 488 for (const CVType &Type : CVTypesPrecomp) { 489 ArrayRef<uint8_t> TypeData = Type.data(); 490 if (Type.kind() == LF_ENDPRECOMP) { 491 EndPrecompRecord EndPrecomp = cantFail( 492 TypeDeserializer::deserializeAs<EndPrecompRecord>(TypeData)); 493 if (Precomp.getSignature() != EndPrecomp.getSignature()) 494 return createStringError(errc::invalid_argument, "no matching pch"); 495 break; 496 } 497 Builder->insertRecordBytes(TypeData); 498 } 499 // Done processing .debug$P, break out of section loop. 500 break; 501 } 502 } 503 504 // Append all the type records, skipping the first record which is the 505 // reference to the precompiled header object information. 506 for (const CVType &Type : CVTypesObj) { 507 ArrayRef<uint8_t> TypeData = Type.data(); 508 if (Type.kind() != LF_PRECOMP) 509 Builder->insertRecordBytes(TypeData); 510 } 511 512 // Set up a type stream that refers to the added type records. 513 Builder->ForEachRecord( 514 [&](TypeIndex TI, const CVType &Type) { TypeArray.push_back(Type); }); 515 516 ItemStream = 517 std::make_unique<BinaryItemStream<CVType>>(llvm::endianness::little); 518 ItemStream->setItems(TypeArray); 519 TypeStream.setUnderlyingStream(*ItemStream); 520 521 PrecompHeader = 522 std::make_shared<LazyRandomTypeCollection>(TypeStream, TypeArray.size()); 523 524 // Change the original input source to use the collected type records. 525 LogicalVisitor.setInput(PrecompHeader); 526 527 LazyRandomTypeCollection &Types = types(); 528 LazyRandomTypeCollection &Ids = ids(); 529 LVTypeVisitor TDV(W, &LogicalVisitor, Types, Ids, StreamTPI, 530 LogicalVisitor.getShared()); 531 return visitTypeStream(Types, TDV); 532 } 533 534 Error LVCodeViewReader::traverseTypeSection(StringRef SectionName, 535 const SectionRef &Section) { 536 LLVM_DEBUG({ 537 ListScope D(W, "CodeViewTypes"); 538 W.printNumber("Section", SectionName, getObj().getSectionID(Section)); 539 }); 540 541 Expected<StringRef> DataOrErr = Section.getContents(); 542 if (!DataOrErr) 543 return DataOrErr.takeError(); 544 uint32_t Magic; 545 if (Error Err = consume(*DataOrErr, Magic)) 546 return Err; 547 if (Magic != COFF::DEBUG_SECTION_MAGIC) 548 return errorCodeToError(object_error::parse_failed); 549 550 // Get the first type record. It will indicate if this object uses a type 551 // server (/Zi) or a PCH file (/Yu). 552 CVTypeArray CVTypes; 553 BinaryStreamReader Reader(*DataOrErr, llvm::endianness::little); 554 cantFail(Reader.readArray(CVTypes, Reader.getLength())); 555 CVTypeArray::Iterator FirstType = CVTypes.begin(); 556 557 // The object was compiled with /Zi. It uses types from a type server PDB. 558 if (FirstType->kind() == LF_TYPESERVER2) { 559 TypeServer2Record TS = cantFail( 560 TypeDeserializer::deserializeAs<TypeServer2Record>(FirstType->data())); 561 return loadTypeServer(TS); 562 } 563 564 // The object was compiled with /Yc or /Yu. It uses types from another 565 // object file with a matching signature. 566 if (FirstType->kind() == LF_PRECOMP) { 567 PrecompRecord Precomp = cantFail( 568 TypeDeserializer::deserializeAs<PrecompRecord>(FirstType->data())); 569 return loadPrecompiledObject(Precomp, CVTypes); 570 } 571 572 LazyRandomTypeCollection &Types = types(); 573 LazyRandomTypeCollection &Ids = ids(); 574 Types.reset(*DataOrErr, 100); 575 LVTypeVisitor TDV(W, &LogicalVisitor, Types, Ids, StreamTPI, 576 LogicalVisitor.getShared()); 577 return visitTypeStream(Types, TDV); 578 } 579 580 Error LVCodeViewReader::traverseTypes(PDBFile &Pdb, 581 LazyRandomTypeCollection &Types, 582 LazyRandomTypeCollection &Ids) { 583 // Traverse types (TPI and IPI). 584 auto VisitTypes = [&](LazyRandomTypeCollection &Types, 585 LazyRandomTypeCollection &Ids, 586 SpecialStream StreamIdx) -> Error { 587 LVTypeVisitor TDV(W, &LogicalVisitor, Types, Ids, StreamIdx, 588 LogicalVisitor.getShared()); 589 return visitTypeStream(Types, TDV); 590 }; 591 592 Expected<TpiStream &> StreamTpiOrErr = Pdb.getPDBTpiStream(); 593 if (!StreamTpiOrErr) 594 return StreamTpiOrErr.takeError(); 595 TpiStream &StreamTpi = *StreamTpiOrErr; 596 StreamTpi.buildHashMap(); 597 LLVM_DEBUG({ 598 W.getOStream() << formatv("Showing {0:N} TPI records\n", 599 StreamTpi.getNumTypeRecords()); 600 }); 601 if (Error Err = VisitTypes(Types, Ids, StreamTPI)) 602 return Err; 603 604 Expected<TpiStream &> StreamIpiOrErr = Pdb.getPDBIpiStream(); 605 if (!StreamIpiOrErr) 606 return StreamIpiOrErr.takeError(); 607 TpiStream &StreamIpi = *StreamIpiOrErr; 608 StreamIpi.buildHashMap(); 609 LLVM_DEBUG({ 610 W.getOStream() << formatv("Showing {0:N} IPI records\n", 611 StreamIpi.getNumTypeRecords()); 612 }); 613 return VisitTypes(Ids, Ids, StreamIPI); 614 } 615 616 Error LVCodeViewReader::traverseSymbolsSubsection(StringRef Subsection, 617 const SectionRef &Section, 618 StringRef SectionContents) { 619 ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(), 620 Subsection.bytes_end()); 621 LVSymbolVisitorDelegate VisitorDelegate(this, Section, &getObj(), 622 SectionContents); 623 CVSymbolArray Symbols; 624 BinaryStreamReader Reader(BinaryData, llvm::endianness::little); 625 if (Error E = Reader.readArray(Symbols, Reader.getLength())) 626 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 627 628 LazyRandomTypeCollection &Types = types(); 629 LazyRandomTypeCollection &Ids = ids(); 630 SymbolVisitorCallbackPipeline Pipeline; 631 SymbolDeserializer Deserializer(&VisitorDelegate, 632 CodeViewContainer::ObjectFile); 633 // As we are processing a COFF format, use TPI as IPI, so the generic code 634 // to process the CodeView format does not contain any additional checks. 635 LVSymbolVisitor Traverser(this, W, &LogicalVisitor, Types, Ids, 636 &VisitorDelegate, LogicalVisitor.getShared()); 637 638 Pipeline.addCallbackToPipeline(Deserializer); 639 Pipeline.addCallbackToPipeline(Traverser); 640 CVSymbolVisitor Visitor(Pipeline); 641 return Visitor.visitSymbolStream(Symbols); 642 } 643 644 Error LVCodeViewReader::traverseSymbolSection(StringRef SectionName, 645 const SectionRef &Section) { 646 LLVM_DEBUG({ 647 ListScope D(W, "CodeViewDebugInfo"); 648 W.printNumber("Section", SectionName, getObj().getSectionID(Section)); 649 }); 650 651 Expected<StringRef> SectionOrErr = Section.getContents(); 652 if (!SectionOrErr) 653 return SectionOrErr.takeError(); 654 StringRef SectionContents = *SectionOrErr; 655 StringRef Data = SectionContents; 656 657 SmallVector<StringRef, 10> SymbolNames; 658 StringMap<StringRef> FunctionLineTables; 659 660 uint32_t Magic; 661 if (Error E = consume(Data, Magic)) 662 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 663 664 if (Magic != COFF::DEBUG_SECTION_MAGIC) 665 return createStringError(object_error::parse_failed, getFileName()); 666 667 BinaryStreamReader FSReader(Data, llvm::endianness::little); 668 if (Error Err = initializeFileAndStringTables(FSReader)) 669 return Err; 670 671 while (!Data.empty()) { 672 // The section consists of a number of subsection in the following format: 673 // |SubSectionType|SubSectionSize|Contents...| 674 uint32_t SubType, SubSectionSize; 675 if (Error E = consume(Data, SubType)) 676 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 677 if (Error E = consume(Data, SubSectionSize)) 678 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 679 680 // Process the subsection as normal even if the ignore bit is set. 681 SubType &= ~SubsectionIgnoreFlag; 682 683 // Get the contents of the subsection. 684 if (SubSectionSize > Data.size()) 685 return createStringError(object_error::parse_failed, getFileName()); 686 StringRef Contents = Data.substr(0, SubSectionSize); 687 688 // Add SubSectionSize to the current offset and align that offset 689 // to find the next subsection. 690 size_t SectionOffset = Data.data() - SectionContents.data(); 691 size_t NextOffset = SectionOffset + SubSectionSize; 692 NextOffset = alignTo(NextOffset, 4); 693 if (NextOffset > SectionContents.size()) 694 return createStringError(object_error::parse_failed, getFileName()); 695 Data = SectionContents.drop_front(NextOffset); 696 697 switch (DebugSubsectionKind(SubType)) { 698 case DebugSubsectionKind::Symbols: 699 if (Error Err = 700 traverseSymbolsSubsection(Contents, Section, SectionContents)) 701 return Err; 702 break; 703 704 case DebugSubsectionKind::InlineeLines: 705 if (Error Err = traverseInlineeLines(Contents)) 706 return Err; 707 break; 708 709 case DebugSubsectionKind::Lines: 710 // Holds a PC to file:line table. Some data to parse this subsection 711 // is stored in the other subsections, so just check sanity and store 712 // the pointers for deferred processing. 713 714 // Collect function and ranges only if we need to print logical lines. 715 if (options().getGeneralCollectRanges()) { 716 717 if (SubSectionSize < 12) { 718 // There should be at least three words to store two function 719 // relocations and size of the code. 720 return createStringError(object_error::parse_failed, getFileName()); 721 } 722 723 StringRef SymbolName; 724 if (Error Err = resolveSymbolName(getObj().getCOFFSection(Section), 725 SectionOffset, SymbolName)) 726 return createStringError(errorToErrorCode(std::move(Err)), 727 getFileName()); 728 729 LLVM_DEBUG({ W.printString("Symbol Name", SymbolName); }); 730 if (FunctionLineTables.count(SymbolName) != 0) { 731 // Saw debug info for this function already? 732 return createStringError(object_error::parse_failed, getFileName()); 733 } 734 735 FunctionLineTables[SymbolName] = Contents; 736 SymbolNames.push_back(SymbolName); 737 } 738 break; 739 740 // Do nothing for unrecognized subsections. 741 default: 742 break; 743 } 744 W.flush(); 745 } 746 747 // Traverse the line tables now that we've read all the subsections and 748 // know all the required information. 749 for (StringRef SymbolName : SymbolNames) { 750 LLVM_DEBUG({ 751 ListScope S(W, "FunctionLineTable"); 752 W.printString("Symbol Name", SymbolName); 753 }); 754 755 BinaryStreamReader Reader(FunctionLineTables[SymbolName], 756 llvm::endianness::little); 757 758 DebugLinesSubsectionRef Lines; 759 if (Error E = Lines.initialize(Reader)) 760 return createStringError(errorToErrorCode(std::move(E)), getFileName()); 761 762 // Find the associated symbol table information. 763 LVSymbolTableEntry SymbolTableEntry = getSymbolTableEntry(SymbolName); 764 LVScope *Function = SymbolTableEntry.Scope; 765 if (!Function) 766 continue; 767 768 LVAddress Addendum = SymbolTableEntry.Address; 769 LVSectionIndex SectionIndex = SymbolTableEntry.SectionIndex; 770 771 // The given scope represents the function that contains the line numbers. 772 // Collect all generated debug lines associated with the function. 773 CULines.clear(); 774 775 // For the given scope, collect all scopes ranges. 776 LVRange *ScopesWithRanges = getSectionRanges(SectionIndex); 777 ScopesWithRanges->clear(); 778 Function->getRanges(*ScopesWithRanges); 779 ScopesWithRanges->sort(); 780 781 uint16_t Segment = Lines.header()->RelocSegment; 782 uint32_t Begin = Lines.header()->RelocOffset; 783 uint32_t Size = Lines.header()->CodeSize; 784 for (const LineColumnEntry &Block : Lines) 785 if (Error Err = createLines(Block.LineNumbers, Addendum, Segment, Begin, 786 Size, Block.NameIndex)) 787 return Err; 788 789 // Include lines from any inlined functions within the current function. 790 includeInlineeLines(SectionIndex, Function); 791 792 if (Error Err = createInstructions(Function, SectionIndex)) 793 return Err; 794 795 processLines(&CULines, SectionIndex, Function); 796 } 797 798 return Error::success(); 799 } 800 801 void LVCodeViewReader::sortScopes() { Root->sort(); } 802 803 void LVCodeViewReader::print(raw_ostream &OS) const { 804 LLVM_DEBUG(dbgs() << "CreateReaders\n"); 805 } 806 807 void LVCodeViewReader::mapRangeAddress(const ObjectFile &Obj, 808 const SectionRef &Section, 809 bool IsComdat) { 810 if (!Obj.isCOFF()) 811 return; 812 813 const COFFObjectFile *Object = cast<COFFObjectFile>(&Obj); 814 815 for (const SymbolRef &Sym : Object->symbols()) { 816 if (!Section.containsSymbol(Sym)) 817 continue; 818 819 COFFSymbolRef Symbol = Object->getCOFFSymbol(Sym); 820 if (Symbol.getComplexType() != llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) 821 continue; 822 823 StringRef SymbolName; 824 Expected<StringRef> SymNameOrErr = Object->getSymbolName(Symbol); 825 if (!SymNameOrErr) { 826 W.startLine() << "Invalid symbol name: " << Symbol.getSectionNumber() 827 << "\n"; 828 consumeError(SymNameOrErr.takeError()); 829 continue; 830 } 831 SymbolName = *SymNameOrErr; 832 833 LLVM_DEBUG({ 834 Expected<const coff_section *> SectionOrErr = 835 Object->getSection(Symbol.getSectionNumber()); 836 if (!SectionOrErr) { 837 W.startLine() << "Invalid section number: " << Symbol.getSectionNumber() 838 << "\n"; 839 consumeError(SectionOrErr.takeError()); 840 return; 841 } 842 W.printNumber("Section #", Symbol.getSectionNumber()); 843 W.printString("Name", SymbolName); 844 W.printHex("Value", Symbol.getValue()); 845 }); 846 847 // Record the symbol name (linkage) and its loading address. 848 addToSymbolTable(SymbolName, Symbol.getValue(), Symbol.getSectionNumber(), 849 IsComdat); 850 } 851 } 852 853 Error LVCodeViewReader::createScopes(COFFObjectFile &Obj) { 854 if (Error Err = loadTargetInfo(Obj)) 855 return Err; 856 857 // Initialization required when processing a COFF file: 858 // Cache the symbols relocations. 859 // Create a mapping for virtual addresses. 860 // Get the functions entry points. 861 cacheRelocations(); 862 mapVirtualAddress(Obj); 863 864 for (const SectionRef &Section : Obj.sections()) { 865 Expected<StringRef> SectionNameOrErr = Section.getName(); 866 if (!SectionNameOrErr) 867 return SectionNameOrErr.takeError(); 868 // .debug$T is a standard CodeView type section, while .debug$P is the 869 // same format but used for MSVC precompiled header object files. 870 if (*SectionNameOrErr == ".debug$T" || *SectionNameOrErr == ".debug$P") 871 if (Error Err = traverseTypeSection(*SectionNameOrErr, Section)) 872 return Err; 873 } 874 875 // Process collected namespaces. 876 LogicalVisitor.processNamespaces(); 877 878 for (const SectionRef &Section : Obj.sections()) { 879 Expected<StringRef> SectionNameOrErr = Section.getName(); 880 if (!SectionNameOrErr) 881 return SectionNameOrErr.takeError(); 882 if (*SectionNameOrErr == ".debug$S") 883 if (Error Err = traverseSymbolSection(*SectionNameOrErr, Section)) 884 return Err; 885 } 886 887 // Check if we have to close the Compile Unit scope. 888 LogicalVisitor.closeScope(); 889 890 // Traverse the strings recorded and transform them into filenames. 891 LogicalVisitor.processFiles(); 892 893 // Process collected element lines. 894 LogicalVisitor.processLines(); 895 896 // Translate composite names into a single component. 897 Root->transformScopedName(); 898 return Error::success(); 899 } 900 901 Error LVCodeViewReader::createScopes(PDBFile &Pdb) { 902 if (Error Err = loadTargetInfo(Pdb)) 903 return Err; 904 905 if (!Pdb.hasPDBTpiStream() || !Pdb.hasPDBDbiStream()) 906 return Error::success(); 907 908 // Open the executable associated with the PDB file and get the section 909 // addresses used to calculate linear addresses for CodeView Symbols. 910 if (!ExePath.empty()) { 911 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = 912 MemoryBuffer::getFileOrSTDIN(ExePath); 913 if (BuffOrErr.getError()) { 914 return createStringError(errc::bad_file_descriptor, 915 "File '%s' does not exist.", ExePath.c_str()); 916 } 917 BinaryBuffer = std::move(BuffOrErr.get()); 918 919 // Check if the buffer corresponds to a PECOFF executable. 920 assert(identify_magic(BinaryBuffer->getBuffer()) == 921 file_magic::pecoff_executable && 922 "Invalid PECOFF executable file."); 923 924 Expected<std::unique_ptr<Binary>> BinOrErr = 925 createBinary(BinaryBuffer->getMemBufferRef()); 926 if (errorToErrorCode(BinOrErr.takeError())) { 927 return createStringError(errc::not_supported, 928 "Binary object format in '%s' is not supported.", 929 ExePath.c_str()); 930 } 931 BinaryExecutable = std::move(*BinOrErr); 932 if (COFFObjectFile *COFFObject = 933 dyn_cast<COFFObjectFile>(BinaryExecutable.get())) 934 mapVirtualAddress(*COFFObject); 935 } 936 937 // In order to generate a full logical view, we have to traverse both 938 // streams TPI and IPI if they are present. The following table gives 939 // the stream where a specified type is located. If the IPI stream is 940 // not present, all the types are located in the TPI stream. 941 // 942 // TPI Stream: 943 // LF_POINTER LF_MODIFIER LF_PROCEDURE LF_MFUNCTION 944 // LF_LABEL LF_ARGLIST LF_FIELDLIST LF_ARRAY 945 // LF_CLASS LF_STRUCTURE LF_INTERFACE LF_UNION 946 // LF_ENUM LF_TYPESERVER2 LF_VFTABLE LF_VTSHAPE 947 // LF_BITFIELD LF_METHODLIST LF_PRECOMP LF_ENDPRECOMP 948 // 949 // IPI stream: 950 // LF_FUNC_ID LF_MFUNC_ID LF_BUILDINFO 951 // LF_SUBSTR_LIST LF_STRING_ID LF_UDT_SRC_LINE 952 // LF_UDT_MOD_SRC_LINE 953 954 LazyRandomTypeCollection &Types = types(); 955 LazyRandomTypeCollection &Ids = ids(); 956 if (Error Err = traverseTypes(Pdb, Types, Ids)) 957 return Err; 958 959 // Process collected namespaces. 960 LogicalVisitor.processNamespaces(); 961 962 LLVM_DEBUG({ W.getOStream() << "Traversing inlined lines\n"; }); 963 964 auto VisitInlineeLines = [&](int32_t Modi, const SymbolGroup &SG, 965 DebugInlineeLinesSubsectionRef &Lines) -> Error { 966 return collectInlineeInfo(Lines, &SG); 967 }; 968 969 FilterOptions Filters = {}; 970 LinePrinter Printer(/*Indent=*/2, false, nulls(), Filters); 971 const PrintScope HeaderScope(Printer, /*IndentLevel=*/2); 972 if (Error Err = iterateModuleSubsections<DebugInlineeLinesSubsectionRef>( 973 Input, HeaderScope, VisitInlineeLines)) 974 return Err; 975 976 // Traverse global symbols. 977 LLVM_DEBUG({ W.getOStream() << "Traversing global symbols\n"; }); 978 if (Pdb.hasPDBGlobalsStream()) { 979 Expected<GlobalsStream &> GlobalsOrErr = Pdb.getPDBGlobalsStream(); 980 if (!GlobalsOrErr) 981 return GlobalsOrErr.takeError(); 982 GlobalsStream &Globals = *GlobalsOrErr; 983 const GSIHashTable &Table = Globals.getGlobalsTable(); 984 Expected<SymbolStream &> ExpectedSyms = Pdb.getPDBSymbolStream(); 985 if (ExpectedSyms) { 986 987 SymbolVisitorCallbackPipeline Pipeline; 988 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb); 989 LVSymbolVisitor Traverser(this, W, &LogicalVisitor, Types, Ids, nullptr, 990 LogicalVisitor.getShared()); 991 992 // As the global symbols do not have an associated Compile Unit, create 993 // one, as the container for all global symbols. 994 RecordPrefix Prefix(SymbolKind::S_COMPILE3); 995 CVSymbol Symbol(&Prefix, sizeof(Prefix)); 996 uint32_t Offset = 0; 997 if (Error Err = Traverser.visitSymbolBegin(Symbol, Offset)) 998 consumeError(std::move(Err)); 999 else { 1000 // The CodeView compile unit containing the global symbols does not 1001 // have a name; generate one using its parent name (object filename) 1002 // follow by the '_global' string. 1003 std::string Name(CompileUnit->getParentScope()->getName()); 1004 CompileUnit->setName(Name.append("_global")); 1005 1006 Pipeline.addCallbackToPipeline(Deserializer); 1007 Pipeline.addCallbackToPipeline(Traverser); 1008 CVSymbolVisitor Visitor(Pipeline); 1009 1010 BinaryStreamRef SymStream = 1011 ExpectedSyms->getSymbolArray().getUnderlyingStream(); 1012 for (uint32_t PubSymOff : Table) { 1013 Expected<CVSymbol> Sym = readSymbolFromStream(SymStream, PubSymOff); 1014 if (Sym) { 1015 if (Error Err = Visitor.visitSymbolRecord(*Sym, PubSymOff)) 1016 return createStringError(errorToErrorCode(std::move(Err)), 1017 getFileName()); 1018 } else { 1019 consumeError(Sym.takeError()); 1020 } 1021 } 1022 } 1023 1024 LogicalVisitor.closeScope(); 1025 } else { 1026 consumeError(ExpectedSyms.takeError()); 1027 } 1028 } 1029 1030 // Traverse symbols (DBI). 1031 LLVM_DEBUG({ W.getOStream() << "Traversing symbol groups\n"; }); 1032 1033 auto VisitSymbolGroup = [&](uint32_t Modi, const SymbolGroup &SG) -> Error { 1034 Expected<ModuleDebugStreamRef> ExpectedModS = 1035 getModuleDebugStream(Pdb, Modi); 1036 if (ExpectedModS) { 1037 ModuleDebugStreamRef &ModS = *ExpectedModS; 1038 1039 LLVM_DEBUG({ 1040 W.getOStream() << formatv("Traversing Group: Mod {0:4}\n", Modi); 1041 }); 1042 1043 SymbolVisitorCallbackPipeline Pipeline; 1044 SymbolDeserializer Deserializer(nullptr, CodeViewContainer::Pdb); 1045 LVSymbolVisitor Traverser(this, W, &LogicalVisitor, Types, Ids, nullptr, 1046 LogicalVisitor.getShared()); 1047 1048 Pipeline.addCallbackToPipeline(Deserializer); 1049 Pipeline.addCallbackToPipeline(Traverser); 1050 CVSymbolVisitor Visitor(Pipeline); 1051 BinarySubstreamRef SS = ModS.getSymbolsSubstream(); 1052 if (Error Err = 1053 Visitor.visitSymbolStream(ModS.getSymbolArray(), SS.Offset)) 1054 return createStringError(errorToErrorCode(std::move(Err)), 1055 getFileName()); 1056 } else { 1057 // If the module stream does not exist, it is not an error condition. 1058 consumeError(ExpectedModS.takeError()); 1059 } 1060 1061 return Error::success(); 1062 }; 1063 1064 if (Error Err = iterateSymbolGroups(Input, HeaderScope, VisitSymbolGroup)) 1065 return Err; 1066 1067 // At this stage, the logical view contains all scopes, symbols and types. 1068 // For PDBs we can use the module id, to access its specific compile unit. 1069 // The line record addresses has been already resolved, so we can apply the 1070 // flow as when processing DWARF. 1071 1072 LLVM_DEBUG({ W.getOStream() << "Traversing lines\n"; }); 1073 1074 // Record all line records for a Compile Unit. 1075 CULines.clear(); 1076 1077 auto VisitDebugLines = [this](int32_t Modi, const SymbolGroup &SG, 1078 DebugLinesSubsectionRef &Lines) -> Error { 1079 if (!options().getPrintLines()) 1080 return Error::success(); 1081 1082 uint16_t Segment = Lines.header()->RelocSegment; 1083 uint32_t Begin = Lines.header()->RelocOffset; 1084 uint32_t Size = Lines.header()->CodeSize; 1085 1086 LLVM_DEBUG({ W.getOStream() << formatv("Modi = {0}\n", Modi); }); 1087 1088 // We have line information for a new module; finish processing the 1089 // collected information for the current module. Once it is done, start 1090 // recording the line information for the new module. 1091 if (CurrentModule != Modi) { 1092 if (Error Err = processModule()) 1093 return Err; 1094 CULines.clear(); 1095 CurrentModule = Modi; 1096 } 1097 1098 for (const LineColumnEntry &Block : Lines) 1099 if (Error Err = createLines(Block.LineNumbers, /*Addendum=*/0, Segment, 1100 Begin, Size, Block.NameIndex, &SG)) 1101 return Err; 1102 1103 return Error::success(); 1104 }; 1105 1106 if (Error Err = iterateModuleSubsections<DebugLinesSubsectionRef>( 1107 Input, HeaderScope, VisitDebugLines)) 1108 return Err; 1109 1110 // Check if we have to close the Compile Unit scope. 1111 LogicalVisitor.closeScope(); 1112 1113 // Process collected element lines. 1114 LogicalVisitor.processLines(); 1115 1116 // Translate composite names into a single component. 1117 Root->transformScopedName(); 1118 return Error::success(); 1119 } 1120 1121 Error LVCodeViewReader::processModule() { 1122 if (LVScope *Scope = getScopeForModule(CurrentModule)) { 1123 CompileUnit = static_cast<LVScopeCompileUnit *>(Scope); 1124 1125 LLVM_DEBUG({ dbgs() << "Processing Scope: " << Scope->getName() << "\n"; }); 1126 1127 // For the given compile unit, collect all scopes ranges. 1128 // For a complete ranges and lines mapping, the logical view support 1129 // needs for the compile unit to have a low and high pc values. We 1130 // can traverse the 'Modules' section and get the information for the 1131 // specific module. Another option, is from all the ranges collected 1132 // to take the first and last values. 1133 LVSectionIndex SectionIndex = DotTextSectionIndex; 1134 LVRange *ScopesWithRanges = getSectionRanges(SectionIndex); 1135 ScopesWithRanges->clear(); 1136 CompileUnit->getRanges(*ScopesWithRanges); 1137 if (!ScopesWithRanges->empty()) 1138 CompileUnit->addObject(ScopesWithRanges->getLower(), 1139 ScopesWithRanges->getUpper()); 1140 ScopesWithRanges->sort(); 1141 1142 if (Error Err = createInstructions()) 1143 return Err; 1144 1145 // Include lines from any inlined functions within the current function. 1146 includeInlineeLines(SectionIndex, Scope); 1147 1148 processLines(&CULines, SectionIndex, nullptr); 1149 } 1150 1151 return Error::success(); 1152 } 1153 1154 // In order to create the scopes, the CodeView Reader will: 1155 // = Traverse the TPI/IPI stream (Type visitor): 1156 // Collect forward references, scoped names, type indexes that will represent 1157 // a logical element, strings, line records, linkage names. 1158 // = Traverse the symbols section (Symbol visitor): 1159 // Create the scopes tree and creates the required logical elements, by 1160 // using the collected indexes from the type visitor. 1161 Error LVCodeViewReader::createScopes() { 1162 LLVM_DEBUG({ 1163 W.startLine() << "\n"; 1164 W.printString("File", getFileName().str()); 1165 W.printString("Exe", ExePath); 1166 W.printString("Format", FileFormatName); 1167 }); 1168 1169 if (Error Err = LVReader::createScopes()) 1170 return Err; 1171 1172 LogicalVisitor.setRoot(Root); 1173 1174 if (isObj()) { 1175 if (Error Err = createScopes(getObj())) 1176 return Err; 1177 } else { 1178 if (Error Err = createScopes(getPdb())) 1179 return Err; 1180 } 1181 1182 return Error::success(); 1183 } 1184 1185 Error LVCodeViewReader::loadTargetInfo(const ObjectFile &Obj) { 1186 // Detect the architecture from the object file. We usually don't need OS 1187 // info to lookup a target and create register info. 1188 Triple TT; 1189 TT.setArch(Triple::ArchType(Obj.getArch())); 1190 TT.setVendor(Triple::UnknownVendor); 1191 TT.setOS(Triple::UnknownOS); 1192 1193 // Features to be passed to target/subtarget 1194 Expected<SubtargetFeatures> Features = Obj.getFeatures(); 1195 SubtargetFeatures FeaturesValue; 1196 if (!Features) { 1197 consumeError(Features.takeError()); 1198 FeaturesValue = SubtargetFeatures(); 1199 } 1200 FeaturesValue = *Features; 1201 return loadGenericTargetInfo(TT.str(), FeaturesValue.getString()); 1202 } 1203 1204 Error LVCodeViewReader::loadTargetInfo(const PDBFile &Pdb) { 1205 Triple TT; 1206 TT.setArch(Triple::ArchType::x86_64); 1207 TT.setVendor(Triple::UnknownVendor); 1208 TT.setOS(Triple::Win32); 1209 1210 StringRef TheFeature = ""; 1211 1212 return loadGenericTargetInfo(TT.str(), TheFeature); 1213 } 1214 1215 std::string LVCodeViewReader::getRegisterName(LVSmall Opcode, 1216 ArrayRef<uint64_t> Operands) { 1217 // Get Compilation Unit CPU Type. 1218 CPUType CPU = getCompileUnitCPUType(); 1219 // For CodeView the register always is in Operands[0]; 1220 RegisterId Register = (RegisterId(Operands[0])); 1221 return formatRegisterId(Register, CPU); 1222 } 1223