1 //===- DwarfStreamer.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 #include "llvm/DWARFLinker/DWARFStreamer.h" 10 #include "llvm/ADT/Triple.h" 11 #include "llvm/CodeGen/NonRelocatableStringpool.h" 12 #include "llvm/DWARFLinker/DWARFLinkerCompileUnit.h" 13 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 14 #include "llvm/MC/MCAsmBackend.h" 15 #include "llvm/MC/MCCodeEmitter.h" 16 #include "llvm/MC/MCDwarf.h" 17 #include "llvm/MC/MCObjectWriter.h" 18 #include "llvm/MC/MCSection.h" 19 #include "llvm/MC/MCStreamer.h" 20 #include "llvm/MC/MCSubtargetInfo.h" 21 #include "llvm/MC/MCTargetOptions.h" 22 #include "llvm/MC/MCTargetOptionsCommandFlags.h" 23 #include "llvm/MC/TargetRegistry.h" 24 #include "llvm/Support/LEB128.h" 25 #include "llvm/Target/TargetOptions.h" 26 27 namespace llvm { 28 29 bool DwarfStreamer::init(Triple TheTriple, 30 StringRef Swift5ReflectionSegmentName) { 31 std::string ErrorStr; 32 std::string TripleName; 33 StringRef Context = "dwarf streamer init"; 34 35 // Get the target. 36 const Target *TheTarget = 37 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr); 38 if (!TheTarget) 39 return error(ErrorStr, Context), false; 40 TripleName = TheTriple.getTriple(); 41 42 // Create all the MC Objects. 43 MRI.reset(TheTarget->createMCRegInfo(TripleName)); 44 if (!MRI) 45 return error(Twine("no register info for target ") + TripleName, Context), 46 false; 47 48 MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags(); 49 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 50 if (!MAI) 51 return error("no asm info for target " + TripleName, Context), false; 52 53 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", "")); 54 if (!MSTI) 55 return error("no subtarget info for target " + TripleName, Context), false; 56 57 MC.reset(new MCContext(TheTriple, MAI.get(), MRI.get(), MSTI.get(), nullptr, 58 nullptr, true, Swift5ReflectionSegmentName)); 59 MOFI.reset(TheTarget->createMCObjectFileInfo(*MC, /*PIC=*/false, false)); 60 MC->setObjectFileInfo(MOFI.get()); 61 62 MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions); 63 if (!MAB) 64 return error("no asm backend for target " + TripleName, Context), false; 65 66 MII.reset(TheTarget->createMCInstrInfo()); 67 if (!MII) 68 return error("no instr info info for target " + TripleName, Context), false; 69 70 MCE = TheTarget->createMCCodeEmitter(*MII, *MC); 71 if (!MCE) 72 return error("no code emitter for target " + TripleName, Context), false; 73 74 switch (OutFileType) { 75 case OutputFileType::Assembly: { 76 MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(), 77 *MAI, *MII, *MRI); 78 MS = TheTarget->createAsmStreamer( 79 *MC, std::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP, 80 std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB), 81 true); 82 break; 83 } 84 case OutputFileType::Object: { 85 MS = TheTarget->createMCObjectStreamer( 86 TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB), 87 MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE), 88 *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible, 89 /*DWARFMustBeAtTheEnd*/ false); 90 break; 91 } 92 } 93 94 if (!MS) 95 return error("no object streamer for target " + TripleName, Context), false; 96 97 // Finally create the AsmPrinter we'll use to emit the DIEs. 98 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(), 99 None)); 100 if (!TM) 101 return error("no target machine for target " + TripleName, Context), false; 102 103 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS))); 104 if (!Asm) 105 return error("no asm printer for target " + TripleName, Context), false; 106 107 RangesSectionSize = 0; 108 LocSectionSize = 0; 109 LineSectionSize = 0; 110 FrameSectionSize = 0; 111 DebugInfoSectionSize = 0; 112 113 return true; 114 } 115 116 void DwarfStreamer::finish() { MS->finish(); } 117 118 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) { 119 MS->switchSection(MOFI->getDwarfInfoSection()); 120 MC->setDwarfVersion(DwarfVersion); 121 } 122 123 /// Emit the compilation unit header for \p Unit in the debug_info section. 124 /// 125 /// A Dwarf 4 section header is encoded as: 126 /// uint32_t Unit length (omitting this field) 127 /// uint16_t Version 128 /// uint32_t Abbreviation table offset 129 /// uint8_t Address size 130 /// Leading to a total of 11 bytes. 131 /// 132 /// A Dwarf 5 section header is encoded as: 133 /// uint32_t Unit length (omitting this field) 134 /// uint16_t Version 135 /// uint8_t Unit type 136 /// uint8_t Address size 137 /// uint32_t Abbreviation table offset 138 /// Leading to a total of 12 bytes. 139 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit, 140 unsigned DwarfVersion) { 141 switchToDebugInfoSection(DwarfVersion); 142 143 /// The start of the unit within its section. 144 Unit.setLabelBegin(Asm->createTempSymbol("cu_begin")); 145 Asm->OutStreamer->emitLabel(Unit.getLabelBegin()); 146 147 // Emit size of content not including length itself. The size has already 148 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to 149 // account for the length field. 150 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4); 151 Asm->emitInt16(DwarfVersion); 152 153 if (DwarfVersion >= 5) { 154 Asm->emitInt8(dwarf::DW_UT_compile); 155 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize()); 156 // We share one abbreviations table across all units so it's always at the 157 // start of the section. 158 Asm->emitInt32(0); 159 DebugInfoSectionSize += 12; 160 } else { 161 // We share one abbreviations table across all units so it's always at the 162 // start of the section. 163 Asm->emitInt32(0); 164 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize()); 165 DebugInfoSectionSize += 11; 166 } 167 168 // Remember this CU. 169 EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()}); 170 } 171 172 /// Emit the \p Abbrevs array as the shared abbreviation table 173 /// for the linked Dwarf file. 174 void DwarfStreamer::emitAbbrevs( 175 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs, 176 unsigned DwarfVersion) { 177 MS->switchSection(MOFI->getDwarfAbbrevSection()); 178 MC->setDwarfVersion(DwarfVersion); 179 Asm->emitDwarfAbbrevs(Abbrevs); 180 } 181 182 /// Recursively emit the DIE tree rooted at \p Die. 183 void DwarfStreamer::emitDIE(DIE &Die) { 184 MS->switchSection(MOFI->getDwarfInfoSection()); 185 Asm->emitDwarfDIE(Die); 186 DebugInfoSectionSize += Die.getSize(); 187 } 188 189 /// Emit contents of section SecName From Obj. 190 void DwarfStreamer::emitSectionContents(StringRef SecData, StringRef SecName) { 191 MCSection *Section = 192 StringSwitch<MCSection *>(SecName) 193 .Case("debug_line", MC->getObjectFileInfo()->getDwarfLineSection()) 194 .Case("debug_loc", MC->getObjectFileInfo()->getDwarfLocSection()) 195 .Case("debug_ranges", 196 MC->getObjectFileInfo()->getDwarfRangesSection()) 197 .Case("debug_frame", MC->getObjectFileInfo()->getDwarfFrameSection()) 198 .Case("debug_aranges", 199 MC->getObjectFileInfo()->getDwarfARangesSection()) 200 .Default(nullptr); 201 202 if (Section) { 203 MS->switchSection(Section); 204 205 MS->emitBytes(SecData); 206 } 207 } 208 209 /// Emit DIE containing warnings. 210 void DwarfStreamer::emitPaperTrailWarningsDie(DIE &Die) { 211 switchToDebugInfoSection(/* Version */ 2); 212 auto &Asm = getAsmPrinter(); 213 Asm.emitInt32(11 + Die.getSize() - 4); 214 Asm.emitInt16(2); 215 Asm.emitInt32(0); 216 Asm.emitInt8(MC->getTargetTriple().isArch64Bit() ? 8 : 4); 217 DebugInfoSectionSize += 11; 218 emitDIE(Die); 219 } 220 221 /// Emit the debug_str section stored in \p Pool. 222 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) { 223 Asm->OutStreamer->switchSection(MOFI->getDwarfStrSection()); 224 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission(); 225 for (auto Entry : Entries) { 226 // Emit the string itself. 227 Asm->OutStreamer->emitBytes(Entry.getString()); 228 // Emit a null terminator. 229 Asm->emitInt8(0); 230 } 231 232 #if 0 233 if (DwarfVersion >= 5) { 234 // Emit an empty string offset section. 235 Asm->OutStreamer->switchSection(MOFI->getDwarfStrOffSection()); 236 Asm->emitDwarfUnitLength(4, "Length of String Offsets Set"); 237 Asm->emitInt16(DwarfVersion); 238 Asm->emitInt16(0); 239 } 240 #endif 241 } 242 243 void DwarfStreamer::emitDebugNames( 244 AccelTable<DWARF5AccelTableStaticData> &Table) { 245 if (EmittedUnits.empty()) 246 return; 247 248 // Build up data structures needed to emit this section. 249 std::vector<MCSymbol *> CompUnits; 250 DenseMap<unsigned, size_t> UniqueIdToCuMap; 251 unsigned Id = 0; 252 for (auto &CU : EmittedUnits) { 253 CompUnits.push_back(CU.LabelBegin); 254 // We might be omitting CUs, so we need to remap them. 255 UniqueIdToCuMap[CU.ID] = Id++; 256 } 257 258 Asm->OutStreamer->switchSection(MOFI->getDwarfDebugNamesSection()); 259 emitDWARF5AccelTable( 260 Asm.get(), Table, CompUnits, 261 [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) { 262 return UniqueIdToCuMap[Entry.getCUIndex()]; 263 }); 264 } 265 266 void DwarfStreamer::emitAppleNamespaces( 267 AccelTable<AppleAccelTableStaticOffsetData> &Table) { 268 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelNamespaceSection()); 269 auto *SectionBegin = Asm->createTempSymbol("namespac_begin"); 270 Asm->OutStreamer->emitLabel(SectionBegin); 271 emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin); 272 } 273 274 void DwarfStreamer::emitAppleNames( 275 AccelTable<AppleAccelTableStaticOffsetData> &Table) { 276 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelNamesSection()); 277 auto *SectionBegin = Asm->createTempSymbol("names_begin"); 278 Asm->OutStreamer->emitLabel(SectionBegin); 279 emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin); 280 } 281 282 void DwarfStreamer::emitAppleObjc( 283 AccelTable<AppleAccelTableStaticOffsetData> &Table) { 284 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelObjCSection()); 285 auto *SectionBegin = Asm->createTempSymbol("objc_begin"); 286 Asm->OutStreamer->emitLabel(SectionBegin); 287 emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin); 288 } 289 290 void DwarfStreamer::emitAppleTypes( 291 AccelTable<AppleAccelTableStaticTypeData> &Table) { 292 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelTypesSection()); 293 auto *SectionBegin = Asm->createTempSymbol("types_begin"); 294 Asm->OutStreamer->emitLabel(SectionBegin); 295 emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin); 296 } 297 298 /// Emit the swift_ast section stored in \p Buffers. 299 void DwarfStreamer::emitSwiftAST(StringRef Buffer) { 300 MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection(); 301 SwiftASTSection->setAlignment(Align(32)); 302 MS->switchSection(SwiftASTSection); 303 MS->emitBytes(Buffer); 304 } 305 306 void DwarfStreamer::emitSwiftReflectionSection( 307 llvm::binaryformat::Swift5ReflectionSectionKind ReflSectionKind, 308 StringRef Buffer, uint32_t Alignment, uint32_t Size) { 309 MCSection *ReflectionSection = 310 MOFI->getSwift5ReflectionSection(ReflSectionKind); 311 if (ReflectionSection == nullptr) 312 return; 313 ReflectionSection->setAlignment(Align(Alignment)); 314 MS->switchSection(ReflectionSection); 315 MS->emitBytes(Buffer); 316 } 317 318 /// Emit the debug_range section contents for \p FuncRange by 319 /// translating the original \p Entries. The debug_range section 320 /// format is totally trivial, consisting just of pairs of address 321 /// sized addresses describing the ranges. 322 void DwarfStreamer::emitRangesEntries( 323 int64_t UnitPcOffset, uint64_t OrigLowPc, 324 const FunctionIntervals::const_iterator &FuncRange, 325 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries, 326 unsigned AddressSize) { 327 MS->switchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); 328 329 // Offset each range by the right amount. 330 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset; 331 for (const auto &Range : Entries) { 332 if (Range.isBaseAddressSelectionEntry(AddressSize)) { 333 warn("unsupported base address selection operation", 334 "emitting debug_ranges"); 335 break; 336 } 337 // Do not emit empty ranges. 338 if (Range.StartAddress == Range.EndAddress) 339 continue; 340 341 // All range entries should lie in the function range. 342 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() && 343 Range.EndAddress + OrigLowPc <= FuncRange.stop())) 344 warn("inconsistent range data.", "emitting debug_ranges"); 345 MS->emitIntValue(Range.StartAddress + PcOffset, AddressSize); 346 MS->emitIntValue(Range.EndAddress + PcOffset, AddressSize); 347 RangesSectionSize += 2 * AddressSize; 348 } 349 350 // Add the terminator entry. 351 MS->emitIntValue(0, AddressSize); 352 MS->emitIntValue(0, AddressSize); 353 RangesSectionSize += 2 * AddressSize; 354 } 355 356 /// Emit the debug_aranges contribution of a unit and 357 /// if \p DoDebugRanges is true the debug_range contents for a 358 /// compile_unit level DW_AT_ranges attribute (Which are basically the 359 /// same thing with a different base address). 360 /// Just aggregate all the ranges gathered inside that unit. 361 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit, 362 bool DoDebugRanges) { 363 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); 364 // Gather the ranges in a vector, so that we can simplify them. The 365 // IntervalMap will have coalesced the non-linked ranges, but here 366 // we want to coalesce the linked addresses. 367 std::vector<std::pair<uint64_t, uint64_t>> Ranges; 368 const auto &FunctionRanges = Unit.getFunctionRanges(); 369 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end(); 370 Range != End; ++Range) 371 Ranges.push_back(std::make_pair(Range.start() + Range.value(), 372 Range.stop() + Range.value())); 373 374 // The object addresses where sorted, but again, the linked 375 // addresses might end up in a different order. 376 llvm::sort(Ranges); 377 378 if (!Ranges.empty()) { 379 MS->switchSection(MC->getObjectFileInfo()->getDwarfARangesSection()); 380 381 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange"); 382 MCSymbol *EndLabel = Asm->createTempSymbol("Earange"); 383 384 unsigned HeaderSize = 385 sizeof(int32_t) + // Size of contents (w/o this field 386 sizeof(int16_t) + // DWARF ARange version number 387 sizeof(int32_t) + // Offset of CU in the .debug_info section 388 sizeof(int8_t) + // Pointer Size (in bytes) 389 sizeof(int8_t); // Segment Size (in bytes) 390 391 unsigned TupleSize = AddressSize * 2; 392 unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize)); 393 394 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Arange length 395 Asm->OutStreamer->emitLabel(BeginLabel); 396 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number 397 Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset 398 Asm->emitInt8(AddressSize); // Address size 399 Asm->emitInt8(0); // Segment size 400 401 Asm->OutStreamer->emitFill(Padding, 0x0); 402 403 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; 404 ++Range) { 405 uint64_t RangeStart = Range->first; 406 MS->emitIntValue(RangeStart, AddressSize); 407 while ((Range + 1) != End && Range->second == (Range + 1)->first) 408 ++Range; 409 MS->emitIntValue(Range->second - RangeStart, AddressSize); 410 } 411 412 // Emit terminator 413 Asm->OutStreamer->emitIntValue(0, AddressSize); 414 Asm->OutStreamer->emitIntValue(0, AddressSize); 415 Asm->OutStreamer->emitLabel(EndLabel); 416 } 417 418 if (!DoDebugRanges) 419 return; 420 421 MS->switchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); 422 // Offset each range by the right amount. 423 int64_t PcOffset = -Unit.getLowPc(); 424 // Emit coalesced ranges. 425 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) { 426 MS->emitIntValue(Range->first + PcOffset, AddressSize); 427 while (Range + 1 != End && Range->second == (Range + 1)->first) 428 ++Range; 429 MS->emitIntValue(Range->second + PcOffset, AddressSize); 430 RangesSectionSize += 2 * AddressSize; 431 } 432 433 // Add the terminator entry. 434 MS->emitIntValue(0, AddressSize); 435 MS->emitIntValue(0, AddressSize); 436 RangesSectionSize += 2 * AddressSize; 437 } 438 439 /// Emit location lists for \p Unit and update attributes to point to the new 440 /// entries. 441 void DwarfStreamer::emitLocationsForUnit( 442 const CompileUnit &Unit, DWARFContext &Dwarf, 443 std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) { 444 const auto &Attributes = Unit.getLocationAttributes(); 445 446 if (Attributes.empty()) 447 return; 448 449 MS->switchSection(MC->getObjectFileInfo()->getDwarfLocSection()); 450 451 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); 452 uint64_t BaseAddressMarker = (AddressSize == 8) 453 ? std::numeric_limits<uint64_t>::max() 454 : std::numeric_limits<uint32_t>::max(); 455 const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection(); 456 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize); 457 DWARFUnit &OrigUnit = Unit.getOrigUnit(); 458 auto OrigUnitDie = OrigUnit.getUnitDIE(false); 459 int64_t UnitPcOffset = 0; 460 if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc))) 461 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc(); 462 463 SmallVector<uint8_t, 32> Buffer; 464 for (const auto &Attr : Attributes) { 465 uint64_t Offset = Attr.first.get(); 466 Attr.first.set(LocSectionSize); 467 // This is the quantity to add to the old location address to get 468 // the correct address for the new one. 469 int64_t LocPcOffset = Attr.second + UnitPcOffset; 470 while (Data.isValidOffset(Offset)) { 471 uint64_t Low = Data.getUnsigned(&Offset, AddressSize); 472 uint64_t High = Data.getUnsigned(&Offset, AddressSize); 473 LocSectionSize += 2 * AddressSize; 474 // End of list entry. 475 if (Low == 0 && High == 0) { 476 Asm->OutStreamer->emitIntValue(0, AddressSize); 477 Asm->OutStreamer->emitIntValue(0, AddressSize); 478 break; 479 } 480 // Base address selection entry. 481 if (Low == BaseAddressMarker) { 482 Asm->OutStreamer->emitIntValue(BaseAddressMarker, AddressSize); 483 Asm->OutStreamer->emitIntValue(High + Attr.second, AddressSize); 484 LocPcOffset = 0; 485 continue; 486 } 487 // Location list entry. 488 Asm->OutStreamer->emitIntValue(Low + LocPcOffset, AddressSize); 489 Asm->OutStreamer->emitIntValue(High + LocPcOffset, AddressSize); 490 uint64_t Length = Data.getU16(&Offset); 491 Asm->OutStreamer->emitIntValue(Length, 2); 492 // Copy the bytes into to the buffer, process them, emit them. 493 Buffer.reserve(Length); 494 Buffer.resize(0); 495 StringRef Input = InputSec.Data.substr(Offset, Length); 496 ProcessExpr(Input, Buffer); 497 Asm->OutStreamer->emitBytes( 498 StringRef((const char *)Buffer.data(), Length)); 499 Offset += Length; 500 LocSectionSize += Length + 2; 501 } 502 } 503 } 504 505 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params, 506 StringRef PrologueBytes, 507 unsigned MinInstLength, 508 std::vector<DWARFDebugLine::Row> &Rows, 509 unsigned PointerSize) { 510 // Switch to the section where the table will be emitted into. 511 MS->switchSection(MC->getObjectFileInfo()->getDwarfLineSection()); 512 MCSymbol *LineStartSym = MC->createTempSymbol(); 513 MCSymbol *LineEndSym = MC->createTempSymbol(); 514 515 // The first 4 bytes is the total length of the information for this 516 // compilation unit (not including these 4 bytes for the length). 517 Asm->emitLabelDifference(LineEndSym, LineStartSym, 4); 518 Asm->OutStreamer->emitLabel(LineStartSym); 519 // Copy Prologue. 520 MS->emitBytes(PrologueBytes); 521 LineSectionSize += PrologueBytes.size() + 4; 522 523 SmallString<128> EncodingBuffer; 524 raw_svector_ostream EncodingOS(EncodingBuffer); 525 526 if (Rows.empty()) { 527 // We only have the dummy entry, dsymutil emits an entry with a 0 528 // address in that case. 529 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0, 530 EncodingOS); 531 MS->emitBytes(EncodingOS.str()); 532 LineSectionSize += EncodingBuffer.size(); 533 MS->emitLabel(LineEndSym); 534 return; 535 } 536 537 // Line table state machine fields 538 unsigned FileNum = 1; 539 unsigned LastLine = 1; 540 unsigned Column = 0; 541 unsigned IsStatement = 1; 542 unsigned Isa = 0; 543 uint64_t Address = -1ULL; 544 545 unsigned RowsSinceLastSequence = 0; 546 547 for (DWARFDebugLine::Row &Row : Rows) { 548 int64_t AddressDelta; 549 if (Address == -1ULL) { 550 MS->emitIntValue(dwarf::DW_LNS_extended_op, 1); 551 MS->emitULEB128IntValue(PointerSize + 1); 552 MS->emitIntValue(dwarf::DW_LNE_set_address, 1); 553 MS->emitIntValue(Row.Address.Address, PointerSize); 554 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1); 555 AddressDelta = 0; 556 } else { 557 AddressDelta = (Row.Address.Address - Address) / MinInstLength; 558 } 559 560 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable. 561 // We should find a way to share this code, but the current compatibility 562 // requirement with classic dsymutil makes it hard. Revisit that once this 563 // requirement is dropped. 564 565 if (FileNum != Row.File) { 566 FileNum = Row.File; 567 MS->emitIntValue(dwarf::DW_LNS_set_file, 1); 568 MS->emitULEB128IntValue(FileNum); 569 LineSectionSize += 1 + getULEB128Size(FileNum); 570 } 571 if (Column != Row.Column) { 572 Column = Row.Column; 573 MS->emitIntValue(dwarf::DW_LNS_set_column, 1); 574 MS->emitULEB128IntValue(Column); 575 LineSectionSize += 1 + getULEB128Size(Column); 576 } 577 578 // FIXME: We should handle the discriminator here, but dsymutil doesn't 579 // consider it, thus ignore it for now. 580 581 if (Isa != Row.Isa) { 582 Isa = Row.Isa; 583 MS->emitIntValue(dwarf::DW_LNS_set_isa, 1); 584 MS->emitULEB128IntValue(Isa); 585 LineSectionSize += 1 + getULEB128Size(Isa); 586 } 587 if (IsStatement != Row.IsStmt) { 588 IsStatement = Row.IsStmt; 589 MS->emitIntValue(dwarf::DW_LNS_negate_stmt, 1); 590 LineSectionSize += 1; 591 } 592 if (Row.BasicBlock) { 593 MS->emitIntValue(dwarf::DW_LNS_set_basic_block, 1); 594 LineSectionSize += 1; 595 } 596 597 if (Row.PrologueEnd) { 598 MS->emitIntValue(dwarf::DW_LNS_set_prologue_end, 1); 599 LineSectionSize += 1; 600 } 601 602 if (Row.EpilogueBegin) { 603 MS->emitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); 604 LineSectionSize += 1; 605 } 606 607 int64_t LineDelta = int64_t(Row.Line) - LastLine; 608 if (!Row.EndSequence) { 609 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS); 610 MS->emitBytes(EncodingOS.str()); 611 LineSectionSize += EncodingBuffer.size(); 612 EncodingBuffer.resize(0); 613 Address = Row.Address.Address; 614 LastLine = Row.Line; 615 RowsSinceLastSequence++; 616 } else { 617 if (LineDelta) { 618 MS->emitIntValue(dwarf::DW_LNS_advance_line, 1); 619 MS->emitSLEB128IntValue(LineDelta); 620 LineSectionSize += 1 + getSLEB128Size(LineDelta); 621 } 622 if (AddressDelta) { 623 MS->emitIntValue(dwarf::DW_LNS_advance_pc, 1); 624 MS->emitULEB128IntValue(AddressDelta); 625 LineSectionSize += 1 + getULEB128Size(AddressDelta); 626 } 627 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 628 0, EncodingOS); 629 MS->emitBytes(EncodingOS.str()); 630 LineSectionSize += EncodingBuffer.size(); 631 EncodingBuffer.resize(0); 632 Address = -1ULL; 633 LastLine = FileNum = IsStatement = 1; 634 RowsSinceLastSequence = Column = Isa = 0; 635 } 636 } 637 638 if (RowsSinceLastSequence) { 639 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0, 640 EncodingOS); 641 MS->emitBytes(EncodingOS.str()); 642 LineSectionSize += EncodingBuffer.size(); 643 EncodingBuffer.resize(0); 644 } 645 646 MS->emitLabel(LineEndSym); 647 } 648 649 /// Copy the debug_line over to the updated binary while unobfuscating the file 650 /// names and directories. 651 void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) { 652 MS->switchSection(MC->getObjectFileInfo()->getDwarfLineSection()); 653 StringRef Contents = Data.getData(); 654 655 // We have to deconstruct the line table header, because it contains to 656 // length fields that will need to be updated when we change the length of 657 // the files and directories in there. 658 unsigned UnitLength = Data.getU32(&Offset); 659 uint64_t UnitEnd = Offset + UnitLength; 660 MCSymbol *BeginLabel = MC->createTempSymbol(); 661 MCSymbol *EndLabel = MC->createTempSymbol(); 662 unsigned Version = Data.getU16(&Offset); 663 664 if (Version > 5) { 665 warn("Unsupported line table version: dropping contents and not " 666 "unobfsucating line table."); 667 return; 668 } 669 670 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); 671 Asm->OutStreamer->emitLabel(BeginLabel); 672 Asm->emitInt16(Version); 673 LineSectionSize += 6; 674 675 MCSymbol *HeaderBeginLabel = MC->createTempSymbol(); 676 MCSymbol *HeaderEndLabel = MC->createTempSymbol(); 677 Asm->emitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4); 678 Asm->OutStreamer->emitLabel(HeaderBeginLabel); 679 Offset += 4; 680 LineSectionSize += 4; 681 682 uint64_t AfterHeaderLengthOffset = Offset; 683 // Skip to the directories. 684 Offset += (Version >= 4) ? 5 : 4; 685 unsigned OpcodeBase = Data.getU8(&Offset); 686 Offset += OpcodeBase - 1; 687 Asm->OutStreamer->emitBytes(Contents.slice(AfterHeaderLengthOffset, Offset)); 688 LineSectionSize += Offset - AfterHeaderLengthOffset; 689 690 // Offset points to the first directory. 691 while (const char *Dir = Data.getCStr(&Offset)) { 692 if (Dir[0] == 0) 693 break; 694 695 StringRef Translated = Translator(Dir); 696 Asm->OutStreamer->emitBytes(Translated); 697 Asm->emitInt8(0); 698 LineSectionSize += Translated.size() + 1; 699 } 700 Asm->emitInt8(0); 701 LineSectionSize += 1; 702 703 while (const char *File = Data.getCStr(&Offset)) { 704 if (File[0] == 0) 705 break; 706 707 StringRef Translated = Translator(File); 708 Asm->OutStreamer->emitBytes(Translated); 709 Asm->emitInt8(0); 710 LineSectionSize += Translated.size() + 1; 711 712 uint64_t OffsetBeforeLEBs = Offset; 713 Asm->emitULEB128(Data.getULEB128(&Offset)); 714 Asm->emitULEB128(Data.getULEB128(&Offset)); 715 Asm->emitULEB128(Data.getULEB128(&Offset)); 716 LineSectionSize += Offset - OffsetBeforeLEBs; 717 } 718 Asm->emitInt8(0); 719 LineSectionSize += 1; 720 721 Asm->OutStreamer->emitLabel(HeaderEndLabel); 722 723 // Copy the actual line table program over. 724 Asm->OutStreamer->emitBytes(Contents.slice(Offset, UnitEnd)); 725 LineSectionSize += UnitEnd - Offset; 726 727 Asm->OutStreamer->emitLabel(EndLabel); 728 Offset = UnitEnd; 729 } 730 731 /// Emit the pubnames or pubtypes section contribution for \p 732 /// Unit into \p Sec. The data is provided in \p Names. 733 void DwarfStreamer::emitPubSectionForUnit( 734 MCSection *Sec, StringRef SecName, const CompileUnit &Unit, 735 const std::vector<CompileUnit::AccelInfo> &Names) { 736 if (Names.empty()) 737 return; 738 739 // Start the dwarf pubnames section. 740 Asm->OutStreamer->switchSection(Sec); 741 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin"); 742 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end"); 743 744 bool HeaderEmitted = false; 745 // Emit the pubnames for this compilation unit. 746 for (const auto &Name : Names) { 747 if (Name.SkipPubSection) 748 continue; 749 750 if (!HeaderEmitted) { 751 // Emit the header. 752 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Length 753 Asm->OutStreamer->emitLabel(BeginLabel); 754 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version 755 Asm->emitInt32(Unit.getStartOffset()); // Unit offset 756 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size 757 HeaderEmitted = true; 758 } 759 Asm->emitInt32(Name.Die->getOffset()); 760 761 // Emit the string itself. 762 Asm->OutStreamer->emitBytes(Name.Name.getString()); 763 // Emit a null terminator. 764 Asm->emitInt8(0); 765 } 766 767 if (!HeaderEmitted) 768 return; 769 Asm->emitInt32(0); // End marker. 770 Asm->OutStreamer->emitLabel(EndLabel); 771 } 772 773 /// Emit .debug_pubnames for \p Unit. 774 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) { 775 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(), 776 "names", Unit, Unit.getPubnames()); 777 } 778 779 /// Emit .debug_pubtypes for \p Unit. 780 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) { 781 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(), 782 "types", Unit, Unit.getPubtypes()); 783 } 784 785 /// Emit a CIE into the debug_frame section. 786 void DwarfStreamer::emitCIE(StringRef CIEBytes) { 787 MS->switchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); 788 789 MS->emitBytes(CIEBytes); 790 FrameSectionSize += CIEBytes.size(); 791 } 792 793 /// Emit a FDE into the debug_frame section. \p FDEBytes 794 /// contains the FDE data without the length, CIE offset and address 795 /// which will be replaced with the parameter values. 796 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize, 797 uint32_t Address, StringRef FDEBytes) { 798 MS->switchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); 799 800 MS->emitIntValue(FDEBytes.size() + 4 + AddrSize, 4); 801 MS->emitIntValue(CIEOffset, 4); 802 MS->emitIntValue(Address, AddrSize); 803 MS->emitBytes(FDEBytes); 804 FrameSectionSize += FDEBytes.size() + 8 + AddrSize; 805 } 806 807 } // namespace llvm 808