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