1 //===- bolt/Core/DebugData.cpp - Debugging information handling -----------===// 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 file implements functions and classes for handling debug info. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "bolt/Core/DebugData.h" 14 #include "bolt/Core/BinaryContext.h" 15 #include "bolt/Utils/Utils.h" 16 #include "llvm/MC/MCContext.h" 17 #include "llvm/MC/MCObjectStreamer.h" 18 #include "llvm/Support/CommandLine.h" 19 #include "llvm/Support/EndianStream.h" 20 #include "llvm/Support/LEB128.h" 21 #include "llvm/Support/SHA1.h" 22 #include <algorithm> 23 #include <cassert> 24 #include <cstdint> 25 #include <limits> 26 #include <unordered_map> 27 28 #define DEBUG_TYPE "bolt-debug-info" 29 30 namespace opts { 31 extern llvm::cl::opt<unsigned> Verbosity; 32 } // namespace opts 33 34 namespace llvm { 35 class MCSymbol; 36 37 namespace bolt { 38 39 const DebugLineTableRowRef DebugLineTableRowRef::NULL_ROW{0, 0}; 40 41 namespace { 42 43 LLVM_ATTRIBUTE_UNUSED 44 static void printLE64(const std::string &S) { 45 for (uint32_t I = 0, Size = S.size(); I < Size; ++I) { 46 errs() << Twine::utohexstr(S[I]); 47 errs() << Twine::utohexstr((int8_t)S[I]); 48 } 49 errs() << "\n"; 50 } 51 52 // Writes address ranges to Writer as pairs of 64-bit (address, size). 53 // If RelativeRange is true, assumes the address range to be written must be of 54 // the form (begin address, range size), otherwise (begin address, end address). 55 // Terminates the list by writing a pair of two zeroes. 56 // Returns the number of written bytes. 57 uint64_t writeAddressRanges(raw_svector_ostream &Stream, 58 const DebugAddressRangesVector &AddressRanges, 59 const bool WriteRelativeRanges = false) { 60 for (const DebugAddressRange &Range : AddressRanges) { 61 support::endian::write(Stream, Range.LowPC, support::little); 62 support::endian::write( 63 Stream, WriteRelativeRanges ? Range.HighPC - Range.LowPC : Range.HighPC, 64 support::little); 65 } 66 // Finish with 0 entries. 67 support::endian::write(Stream, 0ULL, support::little); 68 support::endian::write(Stream, 0ULL, support::little); 69 return AddressRanges.size() * 16 + 16; 70 } 71 72 } // namespace 73 74 DebugRangesSectionWriter::DebugRangesSectionWriter() { 75 RangesBuffer = std::make_unique<DebugBufferVector>(); 76 RangesStream = std::make_unique<raw_svector_ostream>(*RangesBuffer); 77 78 // Add an empty range as the first entry; 79 SectionOffset += 80 writeAddressRanges(*RangesStream.get(), DebugAddressRangesVector{}); 81 } 82 83 uint64_t DebugRangesSectionWriter::addRanges( 84 DebugAddressRangesVector &&Ranges, 85 std::map<DebugAddressRangesVector, uint64_t> &CachedRanges) { 86 if (Ranges.empty()) 87 return getEmptyRangesOffset(); 88 89 const auto RI = CachedRanges.find(Ranges); 90 if (RI != CachedRanges.end()) 91 return RI->second; 92 93 const uint64_t EntryOffset = addRanges(Ranges); 94 CachedRanges.emplace(std::move(Ranges), EntryOffset); 95 96 return EntryOffset; 97 } 98 99 uint64_t 100 DebugRangesSectionWriter::addRanges(const DebugAddressRangesVector &Ranges) { 101 if (Ranges.empty()) 102 return getEmptyRangesOffset(); 103 104 // Reading the SectionOffset and updating it should be atomic to guarantee 105 // unique and correct offsets in patches. 106 std::lock_guard<std::mutex> Lock(WriterMutex); 107 const uint32_t EntryOffset = SectionOffset; 108 SectionOffset += writeAddressRanges(*RangesStream.get(), Ranges); 109 110 return EntryOffset; 111 } 112 113 uint64_t DebugRangesSectionWriter::getSectionOffset() { 114 std::lock_guard<std::mutex> Lock(WriterMutex); 115 return SectionOffset; 116 } 117 118 void DebugARangesSectionWriter::addCURanges(uint64_t CUOffset, 119 DebugAddressRangesVector &&Ranges) { 120 std::lock_guard<std::mutex> Lock(CUAddressRangesMutex); 121 CUAddressRanges.emplace(CUOffset, std::move(Ranges)); 122 } 123 124 void DebugARangesSectionWriter::writeARangesSection( 125 raw_svector_ostream &RangesStream, const CUOffsetMap &CUMap) const { 126 // For reference on the format of the .debug_aranges section, see the DWARF4 127 // specification, section 6.1.4 Lookup by Address 128 // http://www.dwarfstd.org/doc/DWARF4.pdf 129 for (const auto &CUOffsetAddressRangesPair : CUAddressRanges) { 130 const uint64_t Offset = CUOffsetAddressRangesPair.first; 131 const DebugAddressRangesVector &AddressRanges = 132 CUOffsetAddressRangesPair.second; 133 134 // Emit header. 135 136 // Size of this set: 8 (size of the header) + 4 (padding after header) 137 // + 2*sizeof(uint64_t) bytes for each of the ranges, plus an extra 138 // pair of uint64_t's for the terminating, zero-length range. 139 // Does not include size field itself. 140 uint32_t Size = 8 + 4 + 2 * sizeof(uint64_t) * (AddressRanges.size() + 1); 141 142 // Header field #1: set size. 143 support::endian::write(RangesStream, Size, support::little); 144 145 // Header field #2: version number, 2 as per the specification. 146 support::endian::write(RangesStream, static_cast<uint16_t>(2), 147 support::little); 148 149 assert(CUMap.count(Offset) && "Original CU offset is not found in CU Map"); 150 // Header field #3: debug info offset of the correspondent compile unit. 151 support::endian::write( 152 RangesStream, static_cast<uint32_t>(CUMap.find(Offset)->second.Offset), 153 support::little); 154 155 // Header field #4: address size. 156 // 8 since we only write ELF64 binaries for now. 157 RangesStream << char(8); 158 159 // Header field #5: segment size of target architecture. 160 RangesStream << char(0); 161 162 // Padding before address table - 4 bytes in the 64-bit-pointer case. 163 support::endian::write(RangesStream, static_cast<uint32_t>(0), 164 support::little); 165 166 writeAddressRanges(RangesStream, AddressRanges, true); 167 } 168 } 169 170 DebugAddrWriter::DebugAddrWriter(BinaryContext *Bc) { BC = Bc; } 171 172 void DebugAddrWriter::AddressForDWOCU::dump() { 173 std::vector<IndexAddressPair> SortedMap(indexToAddressBegin(), 174 indexToAdddessEnd()); 175 // Sorting address in increasing order of indices. 176 std::sort(SortedMap.begin(), SortedMap.end(), 177 [](const IndexAddressPair &A, const IndexAddressPair &B) { 178 return A.first < B.first; 179 }); 180 for (auto &Pair : SortedMap) 181 dbgs() << Twine::utohexstr(Pair.second) << "\t" << Pair.first << "\n"; 182 } 183 uint32_t DebugAddrWriter::getIndexFromAddress(uint64_t Address, 184 uint64_t DWOId) { 185 std::lock_guard<std::mutex> Lock(WriterMutex); 186 if (!AddressMaps.count(DWOId)) 187 AddressMaps[DWOId] = AddressForDWOCU(); 188 189 AddressForDWOCU &Map = AddressMaps[DWOId]; 190 auto Entry = Map.find(Address); 191 if (Entry == Map.end()) { 192 auto Index = Map.getNextIndex(); 193 Entry = Map.insert(Address, Index).first; 194 } 195 return Entry->second; 196 } 197 198 // Case1) Address is not in map insert in to AddresToIndex and IndexToAddres 199 // Case2) Address is in the map but Index is higher or equal. Need to update 200 // IndexToAddrss. Case3) Address is in the map but Index is lower. Need to 201 // update AddressToIndex and IndexToAddress 202 void DebugAddrWriter::addIndexAddress(uint64_t Address, uint32_t Index, 203 uint64_t DWOId) { 204 std::lock_guard<std::mutex> Lock(WriterMutex); 205 AddressForDWOCU &Map = AddressMaps[DWOId]; 206 auto Entry = Map.find(Address); 207 if (Entry != Map.end()) { 208 if (Entry->second > Index) 209 Map.updateAddressToIndex(Address, Index); 210 Map.updateIndexToAddrss(Address, Index); 211 } else { 212 Map.insert(Address, Index); 213 } 214 } 215 216 AddressSectionBuffer DebugAddrWriter::finalize() { 217 // Need to layout all sections within .debug_addr 218 // Within each section sort Address by index. 219 AddressSectionBuffer Buffer; 220 raw_svector_ostream AddressStream(Buffer); 221 for (std::unique_ptr<DWARFUnit> &CU : BC->DwCtx->compile_units()) { 222 Optional<uint64_t> DWOId = CU->getDWOId(); 223 // Handling the case wehre debug information is a mix of Debug fission and 224 // monolitic. 225 if (!DWOId) 226 continue; 227 auto AM = AddressMaps.find(*DWOId); 228 // Adding to map even if it did not contribute to .debug_addr. 229 // The Skeleton CU will still have DW_AT_GNU_addr_base. 230 DWOIdToOffsetMap[*DWOId] = Buffer.size(); 231 // If does not exist this CUs DWO section didn't contribute to .debug_addr. 232 if (AM == AddressMaps.end()) 233 continue; 234 std::vector<IndexAddressPair> SortedMap(AM->second.indexToAddressBegin(), 235 AM->second.indexToAdddessEnd()); 236 // Sorting address in increasing order of indices. 237 std::sort(SortedMap.begin(), SortedMap.end(), 238 [](const IndexAddressPair &A, const IndexAddressPair &B) { 239 return A.first < B.first; 240 }); 241 242 uint8_t AddrSize = CU->getAddressByteSize(); 243 uint32_t Counter = 0; 244 auto WriteAddress = [&](uint64_t Address) -> void { 245 ++Counter; 246 switch (AddrSize) { 247 default: 248 assert(false && "Address Size is invalid."); 249 break; 250 case 4: 251 support::endian::write(AddressStream, static_cast<uint32_t>(Address), 252 support::little); 253 break; 254 case 8: 255 support::endian::write(AddressStream, Address, support::little); 256 break; 257 } 258 }; 259 260 for (const IndexAddressPair &Val : SortedMap) { 261 while (Val.first > Counter) 262 WriteAddress(0); 263 WriteAddress(Val.second); 264 } 265 } 266 267 return Buffer; 268 } 269 270 uint64_t DebugAddrWriter::getOffset(uint64_t DWOId) { 271 auto Iter = DWOIdToOffsetMap.find(DWOId); 272 assert(Iter != DWOIdToOffsetMap.end() && 273 "Offset in to.debug_addr was not found for DWO ID."); 274 return Iter->second; 275 } 276 277 DebugLocWriter::DebugLocWriter(BinaryContext *BC) { 278 LocBuffer = std::make_unique<DebugBufferVector>(); 279 LocStream = std::make_unique<raw_svector_ostream>(*LocBuffer); 280 } 281 282 void DebugLocWriter::addList(uint64_t AttrOffset, 283 DebugLocationsVector &&LocList) { 284 if (LocList.empty()) { 285 EmptyAttrLists.push_back(AttrOffset); 286 return; 287 } 288 // Since there is a separate DebugLocWriter for each thread, 289 // we don't need a lock to read the SectionOffset and update it. 290 const uint32_t EntryOffset = SectionOffset; 291 292 for (const DebugLocationEntry &Entry : LocList) { 293 support::endian::write(*LocStream, static_cast<uint64_t>(Entry.LowPC), 294 support::little); 295 support::endian::write(*LocStream, static_cast<uint64_t>(Entry.HighPC), 296 support::little); 297 support::endian::write(*LocStream, static_cast<uint16_t>(Entry.Expr.size()), 298 support::little); 299 *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()), 300 Entry.Expr.size()); 301 SectionOffset += 2 * 8 + 2 + Entry.Expr.size(); 302 } 303 LocStream->write_zeros(16); 304 SectionOffset += 16; 305 LocListDebugInfoPatches.push_back({AttrOffset, EntryOffset}); 306 } 307 308 void DebugLoclistWriter::addList(uint64_t AttrOffset, 309 DebugLocationsVector &&LocList) { 310 Patches.push_back({AttrOffset, std::move(LocList)}); 311 } 312 313 std::unique_ptr<DebugBufferVector> DebugLocWriter::getBuffer() { 314 return std::move(LocBuffer); 315 } 316 317 // DWARF 4: 2.6.2 318 void DebugLocWriter::finalize(uint64_t SectionOffset, 319 SimpleBinaryPatcher &DebugInfoPatcher) { 320 for (const auto LocListDebugInfoPatchType : LocListDebugInfoPatches) { 321 uint64_t Offset = SectionOffset + LocListDebugInfoPatchType.LocListOffset; 322 DebugInfoPatcher.addLE32Patch(LocListDebugInfoPatchType.DebugInfoAttrOffset, 323 Offset); 324 } 325 326 for (uint64_t DebugInfoAttrOffset : EmptyAttrLists) 327 DebugInfoPatcher.addLE32Patch(DebugInfoAttrOffset, 328 DebugLocWriter::EmptyListOffset); 329 } 330 331 void DebugLoclistWriter::finalize(uint64_t SectionOffset, 332 SimpleBinaryPatcher &DebugInfoPatcher) { 333 for (LocPatch &Patch : Patches) { 334 if (Patch.LocList.empty()) { 335 DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, 336 DebugLocWriter::EmptyListOffset); 337 continue; 338 } 339 const uint32_t EntryOffset = LocBuffer->size(); 340 for (const DebugLocationEntry &Entry : Patch.LocList) { 341 support::endian::write(*LocStream, 342 static_cast<uint8_t>(dwarf::DW_LLE_startx_length), 343 support::little); 344 uint32_t Index = AddrWriter->getIndexFromAddress(Entry.LowPC, DWOId); 345 encodeULEB128(Index, *LocStream); 346 347 // TODO: Support DWARF5 348 support::endian::write(*LocStream, 349 static_cast<uint32_t>(Entry.HighPC - Entry.LowPC), 350 support::little); 351 support::endian::write(*LocStream, 352 static_cast<uint16_t>(Entry.Expr.size()), 353 support::little); 354 *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()), 355 Entry.Expr.size()); 356 } 357 support::endian::write(*LocStream, 358 static_cast<uint8_t>(dwarf::DW_LLE_end_of_list), 359 support::little); 360 DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, EntryOffset); 361 clearList(Patch.LocList); 362 } 363 clearList(Patches); 364 } 365 366 DebugAddrWriter *DebugLoclistWriter::AddrWriter = nullptr; 367 368 void DebugInfoBinaryPatcher::addUnitBaseOffsetLabel(uint64_t Offset) { 369 Offset -= DWPUnitOffset; 370 std::lock_guard<std::mutex> Lock(WriterMutex); 371 DebugPatches.emplace_back(new DWARFUnitOffsetBaseLabel(Offset)); 372 } 373 374 void DebugInfoBinaryPatcher::addDestinationReferenceLabel(uint64_t Offset) { 375 Offset -= DWPUnitOffset; 376 std::lock_guard<std::mutex> Lock(WriterMutex); 377 auto RetVal = DestinationLabels.insert(Offset); 378 if (!RetVal.second) 379 return; 380 381 DebugPatches.emplace_back(new DestinationReferenceLabel(Offset)); 382 } 383 384 void DebugInfoBinaryPatcher::addReferenceToPatch(uint64_t Offset, 385 uint32_t DestinationOffset, 386 uint32_t OldValueSize, 387 dwarf::Form Form) { 388 Offset -= DWPUnitOffset; 389 DestinationOffset -= DWPUnitOffset; 390 std::lock_guard<std::mutex> Lock(WriterMutex); 391 DebugPatches.emplace_back( 392 new DebugPatchReference(Offset, OldValueSize, DestinationOffset, Form)); 393 } 394 395 void DebugInfoBinaryPatcher::addUDataPatch(uint64_t Offset, uint64_t NewValue, 396 uint32_t OldValueSize) { 397 Offset -= DWPUnitOffset; 398 std::lock_guard<std::mutex> Lock(WriterMutex); 399 DebugPatches.emplace_back( 400 new DebugPatchVariableSize(Offset, OldValueSize, NewValue)); 401 } 402 403 void DebugInfoBinaryPatcher::addLE64Patch(uint64_t Offset, uint64_t NewValue) { 404 Offset -= DWPUnitOffset; 405 std::lock_guard<std::mutex> Lock(WriterMutex); 406 DebugPatches.emplace_back(new DebugPatch64(Offset, NewValue)); 407 } 408 409 void DebugInfoBinaryPatcher::addLE32Patch(uint64_t Offset, uint32_t NewValue, 410 uint32_t OldValueSize) { 411 Offset -= DWPUnitOffset; 412 std::lock_guard<std::mutex> Lock(WriterMutex); 413 if (OldValueSize == 4) 414 DebugPatches.emplace_back(new DebugPatch32(Offset, NewValue)); 415 else 416 DebugPatches.emplace_back(new DebugPatch64to32(Offset, NewValue)); 417 } 418 419 void SimpleBinaryPatcher::addBinaryPatch(uint64_t Offset, 420 std::string &&NewValue, 421 uint32_t OldValueSize) { 422 Patches.emplace_back(Offset, std::move(NewValue)); 423 } 424 425 void SimpleBinaryPatcher::addBytePatch(uint64_t Offset, uint8_t Value) { 426 auto Str = std::string(1, Value); 427 Patches.emplace_back(Offset, std::move(Str)); 428 } 429 430 static std::string encodeLE(size_t ByteSize, uint64_t NewValue) { 431 std::string LE64(ByteSize, 0); 432 for (size_t I = 0; I < ByteSize; ++I) { 433 LE64[I] = NewValue & 0xff; 434 NewValue >>= 8; 435 } 436 return LE64; 437 } 438 439 void SimpleBinaryPatcher::addLEPatch(uint64_t Offset, uint64_t NewValue, 440 size_t ByteSize) { 441 Patches.emplace_back(Offset, encodeLE(ByteSize, NewValue)); 442 } 443 444 void SimpleBinaryPatcher::addUDataPatch(uint64_t Offset, uint64_t Value, 445 uint32_t OldValueSize) { 446 std::string Buff; 447 raw_string_ostream OS(Buff); 448 encodeULEB128(Value, OS, OldValueSize); 449 450 Patches.emplace_back(Offset, std::move(Buff)); 451 } 452 453 void SimpleBinaryPatcher::addLE64Patch(uint64_t Offset, uint64_t NewValue) { 454 addLEPatch(Offset, NewValue, 8); 455 } 456 457 void SimpleBinaryPatcher::addLE32Patch(uint64_t Offset, uint32_t NewValue, 458 uint32_t OldValueSize) { 459 addLEPatch(Offset, NewValue, 4); 460 } 461 462 std::string SimpleBinaryPatcher::patchBinary(StringRef BinaryContents) { 463 std::string BinaryContentsStr = std::string(BinaryContents); 464 for (const auto &Patch : Patches) { 465 uint32_t Offset = Patch.first; 466 const std::string &ByteSequence = Patch.second; 467 assert(Offset + ByteSequence.size() <= BinaryContents.size() && 468 "Applied patch runs over binary size."); 469 for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I) { 470 BinaryContentsStr[Offset + I] = ByteSequence[I]; 471 } 472 } 473 return BinaryContentsStr; 474 } 475 476 CUOffsetMap DebugInfoBinaryPatcher::computeNewOffsets(DWARFContext &DWCtx, 477 bool IsDWOContext) { 478 CUOffsetMap CUMap; 479 std::sort(DebugPatches.begin(), DebugPatches.end(), 480 [](const UniquePatchPtrType &V1, const UniquePatchPtrType &V2) { 481 return V1.get()->Offset < V2.get()->Offset; 482 }); 483 484 DWARFUnitVector::compile_unit_range CompileUnits = 485 IsDWOContext ? DWCtx.dwo_compile_units() : DWCtx.compile_units(); 486 487 for (const std::unique_ptr<DWARFUnit> &CU : CompileUnits) 488 CUMap[CU->getOffset()] = {static_cast<uint32_t>(CU->getOffset()), 489 static_cast<uint32_t>(CU->getLength())}; 490 491 // Calculating changes in .debug_info size from Patches to build a map of old 492 // to updated reference destination offsets. 493 uint32_t PreviousOffset = 0; 494 int32_t PreviousChangeInSize = 0; 495 for (UniquePatchPtrType &PatchBase : DebugPatches) { 496 Patch *P = PatchBase.get(); 497 switch (P->Kind) { 498 default: 499 continue; 500 case DebugPatchKind::PatchValue64to32: { 501 PreviousChangeInSize -= 4; 502 break; 503 } 504 case DebugPatchKind::PatchValueVariable: { 505 DebugPatchVariableSize *DPV = 506 reinterpret_cast<DebugPatchVariableSize *>(P); 507 std::string Temp; 508 raw_string_ostream OS(Temp); 509 encodeULEB128(DPV->Value, OS); 510 PreviousChangeInSize += Temp.size() - DPV->OldValueSize; 511 break; 512 } 513 case DebugPatchKind::DestinationReferenceLabel: { 514 DestinationReferenceLabel *DRL = 515 reinterpret_cast<DestinationReferenceLabel *>(P); 516 OldToNewOffset[DRL->Offset] = 517 DRL->Offset + ChangeInSize + PreviousChangeInSize; 518 break; 519 } 520 case DebugPatchKind::ReferencePatchValue: { 521 // This doesn't look to be a common case, so will always encode as 4 bytes 522 // to reduce algorithmic complexity. 523 DebugPatchReference *RDP = reinterpret_cast<DebugPatchReference *>(P); 524 if (RDP->PatchInfo.IndirectRelative) { 525 PreviousChangeInSize += 4 - RDP->PatchInfo.OldValueSize; 526 assert(RDP->PatchInfo.OldValueSize <= 4 && 527 "Variable encoding reference greater than 4 bytes."); 528 } 529 break; 530 } 531 case DebugPatchKind::DWARFUnitOffsetBaseLabel: { 532 DWARFUnitOffsetBaseLabel *BaseLabel = 533 reinterpret_cast<DWARFUnitOffsetBaseLabel *>(P); 534 uint32_t CUOffset = BaseLabel->Offset; 535 ChangeInSize += PreviousChangeInSize; 536 uint32_t CUOffsetUpdate = CUOffset + ChangeInSize; 537 CUMap[CUOffset].Offset = CUOffsetUpdate; 538 CUMap[PreviousOffset].Length += PreviousChangeInSize; 539 PreviousChangeInSize = 0; 540 PreviousOffset = CUOffset; 541 } 542 } 543 } 544 CUMap[PreviousOffset].Length += PreviousChangeInSize; 545 return CUMap; 546 } 547 548 std::string DebugInfoBinaryPatcher::patchBinary(StringRef BinaryContents) { 549 std::string NewBinaryContents; 550 NewBinaryContents.reserve(BinaryContents.size() + ChangeInSize); 551 uint32_t StartOffset = 0; 552 uint32_t DwarfUnitBaseOffset = 0; 553 uint32_t OldValueSize = 0; 554 uint32_t Offset = 0; 555 std::string ByteSequence; 556 std::vector<std::pair<uint32_t, uint32_t>> LengthPatches; 557 // Wasting one entry to avoid checks for first. 558 LengthPatches.push_back({0, 0}); 559 560 // Applying all the patches replacing current entry. 561 // This might change the size of .debug_info section. 562 for (const UniquePatchPtrType &PatchBase : DebugPatches) { 563 Patch *P = PatchBase.get(); 564 switch (P->Kind) { 565 default: 566 continue; 567 case DebugPatchKind::ReferencePatchValue: { 568 DebugPatchReference *RDP = reinterpret_cast<DebugPatchReference *>(P); 569 uint32_t DestinationOffset = RDP->DestinationOffset; 570 assert(OldToNewOffset.count(DestinationOffset) && 571 "Destination Offset for reference not updated."); 572 uint32_t UpdatedOffset = OldToNewOffset[DestinationOffset]; 573 Offset = RDP->Offset; 574 OldValueSize = RDP->PatchInfo.OldValueSize; 575 if (RDP->PatchInfo.DirectRelative) { 576 UpdatedOffset -= DwarfUnitBaseOffset; 577 ByteSequence = encodeLE(OldValueSize, UpdatedOffset); 578 // In theory reference for DW_FORM_ref{1,2,4,8} can be right on the edge 579 // and overflow if later debug information grows. 580 if (ByteSequence.size() > OldValueSize) 581 errs() << "BOLT-ERROR: Relative reference of size " 582 << Twine::utohexstr(OldValueSize) 583 << " overflows with the new encoding.\n"; 584 } else if (RDP->PatchInfo.DirectAbsolute) { 585 ByteSequence = encodeLE(OldValueSize, UpdatedOffset); 586 } else if (RDP->PatchInfo.IndirectRelative) { 587 UpdatedOffset -= DwarfUnitBaseOffset; 588 ByteSequence.clear(); 589 raw_string_ostream OS(ByteSequence); 590 encodeULEB128(UpdatedOffset, OS, 4); 591 } else { 592 llvm_unreachable("Invalid Reference form."); 593 } 594 break; 595 } 596 case DebugPatchKind::PatchValue32: { 597 DebugPatch32 *P32 = reinterpret_cast<DebugPatch32 *>(P); 598 Offset = P32->Offset; 599 OldValueSize = 4; 600 ByteSequence = encodeLE(4, P32->Value); 601 break; 602 } 603 case DebugPatchKind::PatchValue64to32: { 604 DebugPatch64to32 *P64to32 = reinterpret_cast<DebugPatch64to32 *>(P); 605 Offset = P64to32->Offset; 606 OldValueSize = 8; 607 ByteSequence = encodeLE(4, P64to32->Value); 608 break; 609 } 610 case DebugPatchKind::PatchValueVariable: { 611 DebugPatchVariableSize *PV = 612 reinterpret_cast<DebugPatchVariableSize *>(P); 613 Offset = PV->Offset; 614 OldValueSize = PV->OldValueSize; 615 ByteSequence.clear(); 616 raw_string_ostream OS(ByteSequence); 617 encodeULEB128(PV->Value, OS); 618 break; 619 } 620 case DebugPatchKind::PatchValue64: { 621 DebugPatch64 *P64 = reinterpret_cast<DebugPatch64 *>(P); 622 Offset = P64->Offset; 623 OldValueSize = 8; 624 ByteSequence = encodeLE(8, P64->Value); 625 break; 626 } 627 case DebugPatchKind::DWARFUnitOffsetBaseLabel: { 628 DWARFUnitOffsetBaseLabel *BaseLabel = 629 reinterpret_cast<DWARFUnitOffsetBaseLabel *>(P); 630 Offset = BaseLabel->Offset; 631 OldValueSize = 0; 632 ByteSequence.clear(); 633 auto &Patch = LengthPatches.back(); 634 // Length to copy between last patch entry and next compile unit. 635 uint32_t RemainingLength = Offset - StartOffset; 636 uint32_t NewCUOffset = NewBinaryContents.size() + RemainingLength; 637 DwarfUnitBaseOffset = NewCUOffset; 638 // Length of previous CU = This CU Offset - sizeof(length) - last CU 639 // Offset. 640 Patch.second = NewCUOffset - 4 - Patch.first; 641 LengthPatches.push_back({NewCUOffset, 0}); 642 break; 643 } 644 } 645 646 assert(Offset + ByteSequence.size() <= BinaryContents.size() && 647 "Applied patch runs over binary size."); 648 uint32_t Length = Offset - StartOffset; 649 NewBinaryContents.append(BinaryContents.substr(StartOffset, Length).data(), 650 Length); 651 NewBinaryContents.append(ByteSequence.data(), ByteSequence.size()); 652 StartOffset = Offset + OldValueSize; 653 } 654 uint32_t Length = BinaryContents.size() - StartOffset; 655 NewBinaryContents.append(BinaryContents.substr(StartOffset, Length).data(), 656 Length); 657 DebugPatches.clear(); 658 659 // Patching lengths of CUs 660 auto &Patch = LengthPatches.back(); 661 Patch.second = NewBinaryContents.size() - 4 - Patch.first; 662 for (uint32_t J = 1, Size = LengthPatches.size(); J < Size; ++J) { 663 const auto &Patch = LengthPatches[J]; 664 ByteSequence = encodeLE(4, Patch.second); 665 Offset = Patch.first; 666 for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I) 667 NewBinaryContents[Offset + I] = ByteSequence[I]; 668 } 669 670 return NewBinaryContents; 671 } 672 673 void DebugStrWriter::create() { 674 StrBuffer = std::make_unique<DebugStrBufferVector>(); 675 StrStream = std::make_unique<raw_svector_ostream>(*StrBuffer); 676 } 677 678 void DebugStrWriter::initialize() { 679 auto StrSection = BC->DwCtx->getDWARFObj().getStrSection(); 680 (*StrStream) << StrSection; 681 } 682 683 uint32_t DebugStrWriter::addString(StringRef Str) { 684 std::lock_guard<std::mutex> Lock(WriterMutex); 685 if (StrBuffer->empty()) 686 initialize(); 687 auto Offset = StrBuffer->size(); 688 (*StrStream) << Str; 689 StrStream->write_zeros(1); 690 return Offset; 691 } 692 693 void DebugAbbrevWriter::addUnitAbbreviations(DWARFUnit &Unit) { 694 const DWARFAbbreviationDeclarationSet *Abbrevs = Unit.getAbbreviations(); 695 if (!Abbrevs) 696 return; 697 698 const PatchesTy &UnitPatches = Patches[&Unit]; 699 700 // We are duplicating abbrev sections, to handle the case where for one CU we 701 // modify it, but for another we don't. 702 auto UnitDataPtr = std::make_unique<AbbrevData>(); 703 AbbrevData &UnitData = *UnitDataPtr.get(); 704 UnitData.Buffer = std::make_unique<DebugBufferVector>(); 705 UnitData.Stream = std::make_unique<raw_svector_ostream>(*UnitData.Buffer); 706 raw_svector_ostream &OS = *UnitData.Stream.get(); 707 708 // Returns true if AbbrevData is re-used, false otherwise. 709 auto hashAndAddAbbrev = [&](StringRef AbbrevData) -> bool { 710 llvm::SHA1 Hasher; 711 Hasher.update(AbbrevData); 712 StringRef Key = Hasher.final(); 713 auto Iter = AbbrevDataCache.find(Key); 714 if (Iter != AbbrevDataCache.end()) { 715 UnitsAbbrevData[&Unit] = Iter->second.get(); 716 return true; 717 } 718 AbbrevDataCache[Key] = std::move(UnitDataPtr); 719 UnitsAbbrevData[&Unit] = &UnitData; 720 return false; 721 }; 722 // Take a fast path if there are no patches to apply. Simply copy the original 723 // contents. 724 if (UnitPatches.empty()) { 725 StringRef AbbrevSectionContents = 726 Unit.isDWOUnit() ? Unit.getContext().getDWARFObj().getAbbrevDWOSection() 727 : Unit.getContext().getDWARFObj().getAbbrevSection(); 728 StringRef AbbrevContents; 729 730 const DWARFUnitIndex &CUIndex = Unit.getContext().getCUIndex(); 731 if (!CUIndex.getRows().empty()) { 732 // Handle DWP section contribution. 733 const DWARFUnitIndex::Entry *DWOEntry = 734 CUIndex.getFromHash(*Unit.getDWOId()); 735 if (!DWOEntry) 736 return; 737 738 const DWARFUnitIndex::Entry::SectionContribution *DWOContrubution = 739 DWOEntry->getContribution(DWARFSectionKind::DW_SECT_ABBREV); 740 AbbrevContents = AbbrevSectionContents.substr(DWOContrubution->Offset, 741 DWOContrubution->Length); 742 } else if (!Unit.isDWOUnit()) { 743 const uint64_t StartOffset = Unit.getAbbreviationsOffset(); 744 745 // We know where the unit's abbreviation set starts, but not where it ends 746 // as such data is not readily available. Hence, we have to build a sorted 747 // list of start addresses and find the next starting address to determine 748 // the set boundaries. 749 // 750 // FIXME: if we had a full access to DWARFDebugAbbrev::AbbrDeclSets 751 // we wouldn't have to build our own sorted list for the quick lookup. 752 if (AbbrevSetOffsets.empty()) { 753 for_each( 754 *Unit.getContext().getDebugAbbrev(), 755 [&](const std::pair<uint64_t, DWARFAbbreviationDeclarationSet> &P) { 756 AbbrevSetOffsets.push_back(P.first); 757 }); 758 sort(AbbrevSetOffsets); 759 } 760 auto It = upper_bound(AbbrevSetOffsets, StartOffset); 761 const uint64_t EndOffset = 762 It == AbbrevSetOffsets.end() ? AbbrevSectionContents.size() : *It; 763 AbbrevContents = AbbrevSectionContents.slice(StartOffset, EndOffset); 764 } else { 765 // For DWO unit outside of DWP, we expect the entire section to hold 766 // abbreviations for this unit only. 767 AbbrevContents = AbbrevSectionContents; 768 } 769 770 if (!hashAndAddAbbrev(AbbrevContents)) { 771 OS.reserveExtraSpace(AbbrevContents.size()); 772 OS << AbbrevContents; 773 } 774 return; 775 } 776 777 for (auto I = Abbrevs->begin(), E = Abbrevs->end(); I != E; ++I) { 778 const DWARFAbbreviationDeclaration &Abbrev = *I; 779 auto Patch = UnitPatches.find(&Abbrev); 780 781 encodeULEB128(Abbrev.getCode(), OS); 782 encodeULEB128(Abbrev.getTag(), OS); 783 encodeULEB128(Abbrev.hasChildren(), OS); 784 for (const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec : 785 Abbrev.attributes()) { 786 if (Patch != UnitPatches.end()) { 787 bool Patched = false; 788 // Patches added later take a precedence over earlier ones. 789 for (auto I = Patch->second.rbegin(), E = Patch->second.rend(); I != E; 790 ++I) { 791 if (I->OldAttr != AttrSpec.Attr) 792 continue; 793 794 encodeULEB128(I->NewAttr, OS); 795 encodeULEB128(I->NewAttrForm, OS); 796 Patched = true; 797 break; 798 } 799 if (Patched) 800 continue; 801 } 802 803 encodeULEB128(AttrSpec.Attr, OS); 804 encodeULEB128(AttrSpec.Form, OS); 805 if (AttrSpec.isImplicitConst()) 806 encodeSLEB128(AttrSpec.getImplicitConstValue(), OS); 807 } 808 809 encodeULEB128(0, OS); 810 encodeULEB128(0, OS); 811 } 812 encodeULEB128(0, OS); 813 814 hashAndAddAbbrev(OS.str()); 815 } 816 817 std::unique_ptr<DebugBufferVector> DebugAbbrevWriter::finalize() { 818 // Used to create determinism for writing out abbrevs. 819 std::vector<AbbrevData *> Abbrevs; 820 if (DWOId) { 821 // We expect abbrev_offset to always be zero for DWO units as there 822 // should be one CU per DWO, and TUs should share the same abbreviation 823 // set with the CU. 824 // For DWP AbbreviationsOffset is an Abbrev contribution in the DWP file, so 825 // can be none zero. Thus we are skipping the check for DWP. 826 bool IsDWP = !Context.getCUIndex().getRows().empty(); 827 if (!IsDWP) { 828 for (const std::unique_ptr<DWARFUnit> &Unit : Context.dwo_units()) { 829 if (Unit->getAbbreviationsOffset() != 0) { 830 errs() << "BOLT-ERROR: detected DWO unit with non-zero abbr_offset. " 831 "Unable to update debug info.\n"; 832 exit(1); 833 } 834 } 835 } 836 837 DWARFUnit *Unit = Context.getDWOCompileUnitForHash(*DWOId); 838 // Issue abbreviations for the DWO CU only. 839 addUnitAbbreviations(*Unit); 840 AbbrevData *Abbrev = UnitsAbbrevData[Unit]; 841 Abbrevs.push_back(Abbrev); 842 } else { 843 Abbrevs.reserve(Context.getNumCompileUnits() + Context.getNumTypeUnits()); 844 std::unordered_set<AbbrevData *> ProcessedAbbrevs; 845 // Add abbreviations from compile and type non-DWO units. 846 for (const std::unique_ptr<DWARFUnit> &Unit : Context.normal_units()) { 847 addUnitAbbreviations(*Unit); 848 AbbrevData *Abbrev = UnitsAbbrevData[Unit.get()]; 849 if (!ProcessedAbbrevs.insert(Abbrev).second) 850 continue; 851 Abbrevs.push_back(Abbrev); 852 } 853 } 854 855 DebugBufferVector ReturnBuffer; 856 // Pre-calculate the total size of abbrev section. 857 uint64_t Size = 0; 858 for (const AbbrevData *UnitData : Abbrevs) 859 Size += UnitData->Buffer->size(); 860 861 ReturnBuffer.reserve(Size); 862 863 uint64_t Pos = 0; 864 for (AbbrevData *UnitData : Abbrevs) { 865 ReturnBuffer.append(*UnitData->Buffer); 866 UnitData->Offset = Pos; 867 Pos += UnitData->Buffer->size(); 868 869 UnitData->Buffer.reset(); 870 UnitData->Stream.reset(); 871 } 872 873 return std::make_unique<DebugBufferVector>(ReturnBuffer); 874 } 875 876 static void emitDwarfSetLineAddrAbs(MCStreamer &OS, 877 MCDwarfLineTableParams Params, 878 int64_t LineDelta, uint64_t Address, 879 int PointerSize) { 880 // emit the sequence to set the address 881 OS.emitIntValue(dwarf::DW_LNS_extended_op, 1); 882 OS.emitULEB128IntValue(PointerSize + 1); 883 OS.emitIntValue(dwarf::DW_LNE_set_address, 1); 884 OS.emitIntValue(Address, PointerSize); 885 886 // emit the sequence for the LineDelta (from 1) and a zero address delta. 887 MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0); 888 } 889 890 static inline void emitBinaryDwarfLineTable( 891 MCStreamer *MCOS, MCDwarfLineTableParams Params, 892 const DWARFDebugLine::LineTable *Table, 893 const std::vector<DwarfLineTable::RowSequence> &InputSequences) { 894 if (InputSequences.empty()) 895 return; 896 897 constexpr uint64_t InvalidAddress = UINT64_MAX; 898 unsigned FileNum = 1; 899 unsigned LastLine = 1; 900 unsigned Column = 0; 901 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 902 unsigned Isa = 0; 903 unsigned Discriminator = 0; 904 uint64_t LastAddress = InvalidAddress; 905 uint64_t PrevEndOfSequence = InvalidAddress; 906 const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo(); 907 908 auto emitEndOfSequence = [&](uint64_t Address) { 909 MCDwarfLineAddr::Emit(MCOS, Params, INT64_MAX, Address - LastAddress); 910 FileNum = 1; 911 LastLine = 1; 912 Column = 0; 913 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 914 Isa = 0; 915 Discriminator = 0; 916 LastAddress = InvalidAddress; 917 }; 918 919 for (const DwarfLineTable::RowSequence &Sequence : InputSequences) { 920 const uint64_t SequenceStart = 921 Table->Rows[Sequence.FirstIndex].Address.Address; 922 923 // Check if we need to mark the end of the sequence. 924 if (PrevEndOfSequence != InvalidAddress && LastAddress != InvalidAddress && 925 PrevEndOfSequence != SequenceStart) { 926 emitEndOfSequence(PrevEndOfSequence); 927 } 928 929 for (uint32_t RowIndex = Sequence.FirstIndex; 930 RowIndex <= Sequence.LastIndex; ++RowIndex) { 931 const DWARFDebugLine::Row &Row = Table->Rows[RowIndex]; 932 int64_t LineDelta = static_cast<int64_t>(Row.Line) - LastLine; 933 const uint64_t Address = Row.Address.Address; 934 935 if (FileNum != Row.File) { 936 FileNum = Row.File; 937 MCOS->emitInt8(dwarf::DW_LNS_set_file); 938 MCOS->emitULEB128IntValue(FileNum); 939 } 940 if (Column != Row.Column) { 941 Column = Row.Column; 942 MCOS->emitInt8(dwarf::DW_LNS_set_column); 943 MCOS->emitULEB128IntValue(Column); 944 } 945 if (Discriminator != Row.Discriminator && 946 MCOS->getContext().getDwarfVersion() >= 4) { 947 Discriminator = Row.Discriminator; 948 unsigned Size = getULEB128Size(Discriminator); 949 MCOS->emitInt8(dwarf::DW_LNS_extended_op); 950 MCOS->emitULEB128IntValue(Size + 1); 951 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator); 952 MCOS->emitULEB128IntValue(Discriminator); 953 } 954 if (Isa != Row.Isa) { 955 Isa = Row.Isa; 956 MCOS->emitInt8(dwarf::DW_LNS_set_isa); 957 MCOS->emitULEB128IntValue(Isa); 958 } 959 if (Row.IsStmt != Flags) { 960 Flags = Row.IsStmt; 961 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt); 962 } 963 if (Row.BasicBlock) 964 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block); 965 if (Row.PrologueEnd) 966 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end); 967 if (Row.EpilogueBegin) 968 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin); 969 970 // The end of the sequence is not normal in the middle of the input 971 // sequence, but could happen, e.g. for assembly code. 972 if (Row.EndSequence) { 973 emitEndOfSequence(Address); 974 } else { 975 if (LastAddress == InvalidAddress) 976 emitDwarfSetLineAddrAbs(*MCOS, Params, LineDelta, Address, 977 AsmInfo->getCodePointerSize()); 978 else 979 MCDwarfLineAddr::Emit(MCOS, Params, LineDelta, Address - LastAddress); 980 981 LastAddress = Address; 982 LastLine = Row.Line; 983 } 984 985 Discriminator = 0; 986 } 987 PrevEndOfSequence = Sequence.EndAddress; 988 } 989 990 // Finish with the end of the sequence. 991 if (LastAddress != InvalidAddress) 992 emitEndOfSequence(PrevEndOfSequence); 993 } 994 995 // This function is similar to the one from MCDwarfLineTable, except it handles 996 // end-of-sequence entries differently by utilizing line entries with 997 // DWARF2_FLAG_END_SEQUENCE flag. 998 static inline void emitDwarfLineTable( 999 MCStreamer *MCOS, MCSection *Section, 1000 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) { 1001 unsigned FileNum = 1; 1002 unsigned LastLine = 1; 1003 unsigned Column = 0; 1004 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 1005 unsigned Isa = 0; 1006 unsigned Discriminator = 0; 1007 MCSymbol *LastLabel = nullptr; 1008 const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo(); 1009 1010 // Loop through each MCDwarfLineEntry and encode the dwarf line number table. 1011 for (const MCDwarfLineEntry &LineEntry : LineEntries) { 1012 if (LineEntry.getFlags() & DWARF2_FLAG_END_SEQUENCE) { 1013 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, LineEntry.getLabel(), 1014 AsmInfo->getCodePointerSize()); 1015 FileNum = 1; 1016 LastLine = 1; 1017 Column = 0; 1018 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 1019 Isa = 0; 1020 Discriminator = 0; 1021 LastLabel = nullptr; 1022 continue; 1023 } 1024 1025 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine; 1026 1027 if (FileNum != LineEntry.getFileNum()) { 1028 FileNum = LineEntry.getFileNum(); 1029 MCOS->emitInt8(dwarf::DW_LNS_set_file); 1030 MCOS->emitULEB128IntValue(FileNum); 1031 } 1032 if (Column != LineEntry.getColumn()) { 1033 Column = LineEntry.getColumn(); 1034 MCOS->emitInt8(dwarf::DW_LNS_set_column); 1035 MCOS->emitULEB128IntValue(Column); 1036 } 1037 if (Discriminator != LineEntry.getDiscriminator() && 1038 MCOS->getContext().getDwarfVersion() >= 4) { 1039 Discriminator = LineEntry.getDiscriminator(); 1040 unsigned Size = getULEB128Size(Discriminator); 1041 MCOS->emitInt8(dwarf::DW_LNS_extended_op); 1042 MCOS->emitULEB128IntValue(Size + 1); 1043 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator); 1044 MCOS->emitULEB128IntValue(Discriminator); 1045 } 1046 if (Isa != LineEntry.getIsa()) { 1047 Isa = LineEntry.getIsa(); 1048 MCOS->emitInt8(dwarf::DW_LNS_set_isa); 1049 MCOS->emitULEB128IntValue(Isa); 1050 } 1051 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 1052 Flags = LineEntry.getFlags(); 1053 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt); 1054 } 1055 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK) 1056 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block); 1057 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END) 1058 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end); 1059 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 1060 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin); 1061 1062 MCSymbol *Label = LineEntry.getLabel(); 1063 1064 // At this point we want to emit/create the sequence to encode the delta 1065 // in line numbers and the increment of the address from the previous 1066 // Label and the current Label. 1067 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 1068 AsmInfo->getCodePointerSize()); 1069 Discriminator = 0; 1070 LastLine = LineEntry.getLine(); 1071 LastLabel = Label; 1072 } 1073 1074 assert(LastLabel == nullptr && "end of sequence expected"); 1075 } 1076 1077 void DwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params, 1078 Optional<MCDwarfLineStr> &LineStr, 1079 BinaryContext &BC) const { 1080 if (!RawData.empty()) { 1081 assert(MCLineSections.getMCLineEntries().empty() && 1082 InputSequences.empty() && 1083 "cannot combine raw data with new line entries"); 1084 MCOS->emitLabel(getLabel()); 1085 MCOS->emitBytes(RawData); 1086 1087 // Emit fake relocation for RuntimeDyld to always allocate the section. 1088 // 1089 // FIXME: remove this once RuntimeDyld stops skipping allocatable sections 1090 // without relocations. 1091 MCOS->emitRelocDirective( 1092 *MCConstantExpr::create(0, *BC.Ctx), "BFD_RELOC_NONE", 1093 MCSymbolRefExpr::create(getLabel(), *BC.Ctx), SMLoc(), *BC.STI); 1094 1095 return; 1096 } 1097 1098 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second; 1099 1100 // Put out the line tables. 1101 for (const auto &LineSec : MCLineSections.getMCLineEntries()) 1102 emitDwarfLineTable(MCOS, LineSec.first, LineSec.second); 1103 1104 // Emit line tables for the original code. 1105 emitBinaryDwarfLineTable(MCOS, Params, InputTable, InputSequences); 1106 1107 // This is the end of the section, so set the value of the symbol at the end 1108 // of this section (that was used in a previous expression). 1109 MCOS->emitLabel(LineEndSym); 1110 } 1111 1112 void DwarfLineTable::emit(BinaryContext &BC, MCStreamer &Streamer) { 1113 MCAssembler &Assembler = 1114 static_cast<MCObjectStreamer *>(&Streamer)->getAssembler(); 1115 1116 MCDwarfLineTableParams Params = Assembler.getDWARFLinetableParams(); 1117 1118 auto &LineTables = BC.getDwarfLineTables(); 1119 1120 // Bail out early so we don't switch to the debug_line section needlessly and 1121 // in doing so create an unnecessary (if empty) section. 1122 if (LineTables.empty()) 1123 return; 1124 1125 // In a v5 non-split line table, put the strings in a separate section. 1126 Optional<MCDwarfLineStr> LineStr(None); 1127 if (BC.Ctx->getDwarfVersion() >= 5) 1128 LineStr = MCDwarfLineStr(*BC.Ctx); 1129 1130 // Switch to the section where the table will be emitted into. 1131 Streamer.SwitchSection(BC.MOFI->getDwarfLineSection()); 1132 1133 // Handle the rest of the Compile Units. 1134 for (auto &CUIDTablePair : LineTables) { 1135 CUIDTablePair.second.emitCU(&Streamer, Params, LineStr, BC); 1136 } 1137 } 1138 1139 } // namespace bolt 1140 } // namespace llvm 1141