1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===// 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/MC/MCDwarf.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/DenseMap.h" 12 #include "llvm/ADT/Hashing.h" 13 #include "llvm/ADT/Optional.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/BinaryFormat/Dwarf.h" 20 #include "llvm/Config/config.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 #include "llvm/MC/MCContext.h" 23 #include "llvm/MC/MCExpr.h" 24 #include "llvm/MC/MCObjectFileInfo.h" 25 #include "llvm/MC/MCObjectStreamer.h" 26 #include "llvm/MC/MCRegisterInfo.h" 27 #include "llvm/MC/MCSection.h" 28 #include "llvm/MC/MCStreamer.h" 29 #include "llvm/MC/MCSymbol.h" 30 #include "llvm/MC/StringTableBuilder.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/Endian.h" 33 #include "llvm/Support/EndianStream.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/LEB128.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/SourceMgr.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <cassert> 41 #include <cstdint> 42 #include <string> 43 #include <utility> 44 #include <vector> 45 46 using namespace llvm; 47 48 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) { 49 MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start"); 50 MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end"); 51 auto DwarfFormat = S.getContext().getDwarfFormat(); 52 if (DwarfFormat == dwarf::DWARF64) { 53 S.AddComment("DWARF64 mark"); 54 S.emitInt32(dwarf::DW_LENGTH_DWARF64); 55 } 56 S.AddComment("Length"); 57 S.emitAbsoluteSymbolDiff(End, Start, 58 dwarf::getDwarfOffsetByteSize(DwarfFormat)); 59 S.emitLabel(Start); 60 S.AddComment("Version"); 61 S.emitInt16(S.getContext().getDwarfVersion()); 62 S.AddComment("Address size"); 63 S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize()); 64 S.AddComment("Segment selector size"); 65 S.emitInt8(0); 66 return End; 67 } 68 69 /// Manage the .debug_line_str section contents, if we use it. 70 class llvm::MCDwarfLineStr { 71 MCSymbol *LineStrLabel = nullptr; 72 StringTableBuilder LineStrings{StringTableBuilder::DWARF}; 73 bool UseRelocs = false; 74 75 public: 76 /// Construct an instance that can emit .debug_line_str (for use in a normal 77 /// v5 line table). 78 explicit MCDwarfLineStr(MCContext &Ctx) { 79 UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections(); 80 if (UseRelocs) 81 LineStrLabel = 82 Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol(); 83 } 84 85 /// Emit a reference to the string. 86 void emitRef(MCStreamer *MCOS, StringRef Path); 87 88 /// Emit the .debug_line_str section if appropriate. 89 void emitSection(MCStreamer *MCOS); 90 }; 91 92 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) { 93 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment(); 94 if (MinInsnLength == 1) 95 return AddrDelta; 96 if (AddrDelta % MinInsnLength != 0) { 97 // TODO: report this error, but really only once. 98 ; 99 } 100 return AddrDelta / MinInsnLength; 101 } 102 103 // 104 // This is called when an instruction is assembled into the specified section 105 // and if there is information from the last .loc directive that has yet to have 106 // a line entry made for it is made. 107 // 108 void MCDwarfLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) { 109 if (!MCOS->getContext().getDwarfLocSeen()) 110 return; 111 112 // Create a symbol at in the current section for use in the line entry. 113 MCSymbol *LineSym = MCOS->getContext().createTempSymbol(); 114 // Set the value of the symbol to use for the MCDwarfLineEntry. 115 MCOS->emitLabel(LineSym); 116 117 // Get the current .loc info saved in the context. 118 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); 119 120 // Create a (local) line entry with the symbol and the current .loc info. 121 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc); 122 123 // clear DwarfLocSeen saying the current .loc info is now used. 124 MCOS->getContext().clearDwarfLocSeen(); 125 126 // Add the line entry to this section's entries. 127 MCOS->getContext() 128 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID()) 129 .getMCLineSections() 130 .addLineEntry(LineEntry, Section); 131 } 132 133 // 134 // This helper routine returns an expression of End - Start + IntVal . 135 // 136 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx, 137 const MCSymbol &Start, 138 const MCSymbol &End, 139 int IntVal) { 140 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 141 const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx); 142 const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx); 143 const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx); 144 const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx); 145 const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx); 146 return Res3; 147 } 148 149 // 150 // This helper routine returns an expression of Start + IntVal . 151 // 152 static inline const MCExpr * 153 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) { 154 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 155 const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx); 156 const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx); 157 const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx); 158 return Res; 159 } 160 161 // 162 // This emits the Dwarf line table for the specified section from the entries 163 // in the LineSection. 164 // 165 static inline void emitDwarfLineTable( 166 MCObjectStreamer *MCOS, MCSection *Section, 167 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) { 168 unsigned FileNum = 1; 169 unsigned LastLine = 1; 170 unsigned Column = 0; 171 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 172 unsigned Isa = 0; 173 unsigned Discriminator = 0; 174 MCSymbol *LastLabel = nullptr; 175 176 // Loop through each MCDwarfLineEntry and encode the dwarf line number table. 177 for (const MCDwarfLineEntry &LineEntry : LineEntries) { 178 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine; 179 180 if (FileNum != LineEntry.getFileNum()) { 181 FileNum = LineEntry.getFileNum(); 182 MCOS->emitInt8(dwarf::DW_LNS_set_file); 183 MCOS->emitULEB128IntValue(FileNum); 184 } 185 if (Column != LineEntry.getColumn()) { 186 Column = LineEntry.getColumn(); 187 MCOS->emitInt8(dwarf::DW_LNS_set_column); 188 MCOS->emitULEB128IntValue(Column); 189 } 190 if (Discriminator != LineEntry.getDiscriminator() && 191 MCOS->getContext().getDwarfVersion() >= 4) { 192 Discriminator = LineEntry.getDiscriminator(); 193 unsigned Size = getULEB128Size(Discriminator); 194 MCOS->emitInt8(dwarf::DW_LNS_extended_op); 195 MCOS->emitULEB128IntValue(Size + 1); 196 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator); 197 MCOS->emitULEB128IntValue(Discriminator); 198 } 199 if (Isa != LineEntry.getIsa()) { 200 Isa = LineEntry.getIsa(); 201 MCOS->emitInt8(dwarf::DW_LNS_set_isa); 202 MCOS->emitULEB128IntValue(Isa); 203 } 204 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 205 Flags = LineEntry.getFlags(); 206 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt); 207 } 208 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK) 209 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block); 210 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END) 211 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end); 212 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 213 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin); 214 215 MCSymbol *Label = LineEntry.getLabel(); 216 217 // At this point we want to emit/create the sequence to encode the delta in 218 // line numbers and the increment of the address from the previous Label 219 // and the current Label. 220 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo(); 221 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 222 asmInfo->getCodePointerSize()); 223 224 Discriminator = 0; 225 LastLine = LineEntry.getLine(); 226 LastLabel = Label; 227 } 228 229 // Emit a DW_LNE_end_sequence for the end of the section. 230 // Use the section end label to compute the address delta and use INT64_MAX 231 // as the line delta which is the signal that this is actually a 232 // DW_LNE_end_sequence. 233 MCSymbol *SectionEnd = MCOS->endSection(Section); 234 235 // Switch back the dwarf line section, in case endSection had to switch the 236 // section. 237 MCContext &Ctx = MCOS->getContext(); 238 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection()); 239 240 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo(); 241 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd, 242 AsmInfo->getCodePointerSize()); 243 } 244 245 // 246 // This emits the Dwarf file and the line tables. 247 // 248 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS, 249 MCDwarfLineTableParams Params) { 250 MCContext &context = MCOS->getContext(); 251 252 auto &LineTables = context.getMCDwarfLineTables(); 253 254 // Bail out early so we don't switch to the debug_line section needlessly and 255 // in doing so create an unnecessary (if empty) section. 256 if (LineTables.empty()) 257 return; 258 259 // In a v5 non-split line table, put the strings in a separate section. 260 Optional<MCDwarfLineStr> LineStr; 261 if (context.getDwarfVersion() >= 5) 262 LineStr = MCDwarfLineStr(context); 263 264 // Switch to the section where the table will be emitted into. 265 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); 266 267 // Handle the rest of the Compile Units. 268 for (const auto &CUIDTablePair : LineTables) { 269 CUIDTablePair.second.EmitCU(MCOS, Params, LineStr); 270 } 271 272 if (LineStr) 273 LineStr->emitSection(MCOS); 274 } 275 276 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params, 277 MCSection *Section) const { 278 if (!HasSplitLineTable) 279 return; 280 Optional<MCDwarfLineStr> NoLineStr(None); 281 MCOS.SwitchSection(Section); 282 MCOS.emitLabel(Header.Emit(&MCOS, Params, None, NoLineStr).second); 283 } 284 285 std::pair<MCSymbol *, MCSymbol *> 286 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 287 Optional<MCDwarfLineStr> &LineStr) const { 288 static const char StandardOpcodeLengths[] = { 289 0, // length of DW_LNS_copy 290 1, // length of DW_LNS_advance_pc 291 1, // length of DW_LNS_advance_line 292 1, // length of DW_LNS_set_file 293 1, // length of DW_LNS_set_column 294 0, // length of DW_LNS_negate_stmt 295 0, // length of DW_LNS_set_basic_block 296 0, // length of DW_LNS_const_add_pc 297 1, // length of DW_LNS_fixed_advance_pc 298 0, // length of DW_LNS_set_prologue_end 299 0, // length of DW_LNS_set_epilogue_begin 300 1 // DW_LNS_set_isa 301 }; 302 assert(array_lengthof(StandardOpcodeLengths) >= 303 (Params.DWARF2LineOpcodeBase - 1U)); 304 return Emit( 305 MCOS, Params, 306 makeArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1), 307 LineStr); 308 } 309 310 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) { 311 MCContext &Context = OS.getContext(); 312 assert(!isa<MCSymbolRefExpr>(Expr)); 313 if (Context.getAsmInfo()->hasAggressiveSymbolFolding()) 314 return Expr; 315 316 MCSymbol *ABS = Context.createTempSymbol(); 317 OS.emitAssignment(ABS, Expr); 318 return MCSymbolRefExpr::create(ABS, Context); 319 } 320 321 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) { 322 const MCExpr *ABS = forceExpAbs(OS, Value); 323 OS.emitValue(ABS, Size); 324 } 325 326 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) { 327 // Switch to the .debug_line_str section. 328 MCOS->SwitchSection( 329 MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection()); 330 // Emit the strings without perturbing the offsets we used. 331 LineStrings.finalizeInOrder(); 332 SmallString<0> Data; 333 Data.resize(LineStrings.getSize()); 334 LineStrings.write((uint8_t *)Data.data()); 335 MCOS->emitBinaryData(Data.str()); 336 } 337 338 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) { 339 int RefSize = 340 dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat()); 341 size_t Offset = LineStrings.add(Path); 342 if (UseRelocs) { 343 MCContext &Ctx = MCOS->getContext(); 344 MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize); 345 } else 346 MCOS->emitIntValue(Offset, RefSize); 347 } 348 349 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const { 350 // First the directory table. 351 for (auto &Dir : MCDwarfDirs) { 352 MCOS->emitBytes(Dir); // The DirectoryName, and... 353 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 354 } 355 MCOS->emitInt8(0); // Terminate the directory list. 356 357 // Second the file table. 358 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { 359 assert(!MCDwarfFiles[i].Name.empty()); 360 MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and... 361 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 362 MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number. 363 MCOS->emitInt8(0); // Last modification timestamp (always 0). 364 MCOS->emitInt8(0); // File size (always 0). 365 } 366 MCOS->emitInt8(0); // Terminate the file list. 367 } 368 369 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile, 370 bool EmitMD5, bool HasSource, 371 Optional<MCDwarfLineStr> &LineStr) { 372 assert(!DwarfFile.Name.empty()); 373 if (LineStr) 374 LineStr->emitRef(MCOS, DwarfFile.Name); 375 else { 376 MCOS->emitBytes(DwarfFile.Name); // FileName and... 377 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 378 } 379 MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number. 380 if (EmitMD5) { 381 const MD5::MD5Result &Cksum = *DwarfFile.Checksum; 382 MCOS->emitBinaryData( 383 StringRef(reinterpret_cast<const char *>(Cksum.Bytes.data()), 384 Cksum.Bytes.size())); 385 } 386 if (HasSource) { 387 if (LineStr) 388 LineStr->emitRef(MCOS, DwarfFile.Source.getValueOr(StringRef())); 389 else { 390 MCOS->emitBytes( 391 DwarfFile.Source.getValueOr(StringRef())); // Source and... 392 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 393 } 394 } 395 } 396 397 void MCDwarfLineTableHeader::emitV5FileDirTables( 398 MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr) const { 399 // The directory format, which is just a list of the directory paths. In a 400 // non-split object, these are references to .debug_line_str; in a split 401 // object, they are inline strings. 402 MCOS->emitInt8(1); 403 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path); 404 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 405 : dwarf::DW_FORM_string); 406 MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1); 407 // Try not to emit an empty compilation directory. 408 const StringRef CompDir = CompilationDir.empty() 409 ? MCOS->getContext().getCompilationDir() 410 : StringRef(CompilationDir); 411 if (LineStr) { 412 // Record path strings, emit references here. 413 LineStr->emitRef(MCOS, CompDir); 414 for (const auto &Dir : MCDwarfDirs) 415 LineStr->emitRef(MCOS, Dir); 416 } else { 417 // The list of directory paths. Compilation directory comes first. 418 MCOS->emitBytes(CompDir); 419 MCOS->emitBytes(StringRef("\0", 1)); 420 for (const auto &Dir : MCDwarfDirs) { 421 MCOS->emitBytes(Dir); // The DirectoryName, and... 422 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 423 } 424 } 425 426 // The file format, which is the inline null-terminated filename and a 427 // directory index. We don't track file size/timestamp so don't emit them 428 // in the v5 table. Emit MD5 checksums and source if we have them. 429 uint64_t Entries = 2; 430 if (HasAllMD5) 431 Entries += 1; 432 if (HasSource) 433 Entries += 1; 434 MCOS->emitInt8(Entries); 435 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path); 436 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 437 : dwarf::DW_FORM_string); 438 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index); 439 MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata); 440 if (HasAllMD5) { 441 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5); 442 MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16); 443 } 444 if (HasSource) { 445 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source); 446 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 447 : dwarf::DW_FORM_string); 448 } 449 // Then the counted list of files. The root file is file #0, then emit the 450 // files as provide by .file directives. 451 // MCDwarfFiles has an unused element [0] so use size() not size()+1. 452 // But sometimes MCDwarfFiles is empty, in which case we still emit one file. 453 MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size()); 454 // To accommodate assembler source written for DWARF v4 but trying to emit 455 // v5: If we didn't see a root file explicitly, replicate file #1. 456 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) && 457 "No root file and no .file directives"); 458 emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile, 459 HasAllMD5, HasSource, LineStr); 460 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i) 461 emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr); 462 } 463 464 std::pair<MCSymbol *, MCSymbol *> 465 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 466 ArrayRef<char> StandardOpcodeLengths, 467 Optional<MCDwarfLineStr> &LineStr) const { 468 MCContext &context = MCOS->getContext(); 469 470 // Create a symbol at the beginning of the line table. 471 MCSymbol *LineStartSym = Label; 472 if (!LineStartSym) 473 LineStartSym = context.createTempSymbol(); 474 // Set the value of the symbol, as we are at the start of the line table. 475 MCOS->emitLabel(LineStartSym); 476 477 // Create a symbol for the end of the section (to be set when we get there). 478 MCSymbol *LineEndSym = context.createTempSymbol(); 479 480 unsigned UnitLengthBytes = 481 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 482 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 483 484 if (context.getDwarfFormat() == dwarf::DWARF64) 485 // Emit DWARF64 mark. 486 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 487 488 // The length field does not include itself and, in case of the 64-bit DWARF 489 // format, the DWARF64 mark. 490 emitAbsValue(*MCOS, 491 makeEndMinusStartExpr(context, *LineStartSym, *LineEndSym, 492 UnitLengthBytes), 493 OffsetSize); 494 495 // Next 2 bytes is the Version. 496 unsigned LineTableVersion = context.getDwarfVersion(); 497 MCOS->emitInt16(LineTableVersion); 498 499 // Keep track of the bytes between the very start and where the header length 500 // comes out. 501 unsigned PreHeaderLengthBytes = UnitLengthBytes + 2; 502 503 // In v5, we get address info next. 504 if (LineTableVersion >= 5) { 505 MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize()); 506 MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges. 507 PreHeaderLengthBytes += 2; 508 } 509 510 // Create a symbol for the end of the prologue (to be set when we get there). 511 MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end 512 513 // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is 514 // actually the length from after the length word, to the end of the prologue. 515 emitAbsValue(*MCOS, 516 makeEndMinusStartExpr(context, *LineStartSym, *ProEndSym, 517 (PreHeaderLengthBytes + OffsetSize)), 518 OffsetSize); 519 520 // Parameters of the state machine, are next. 521 MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment()); 522 // maximum_operations_per_instruction 523 // For non-VLIW architectures this field is always 1. 524 // FIXME: VLIW architectures need to update this field accordingly. 525 if (LineTableVersion >= 4) 526 MCOS->emitInt8(1); 527 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT); 528 MCOS->emitInt8(Params.DWARF2LineBase); 529 MCOS->emitInt8(Params.DWARF2LineRange); 530 MCOS->emitInt8(StandardOpcodeLengths.size() + 1); 531 532 // Standard opcode lengths 533 for (char Length : StandardOpcodeLengths) 534 MCOS->emitInt8(Length); 535 536 // Put out the directory and file tables. The formats vary depending on 537 // the version. 538 if (LineTableVersion >= 5) 539 emitV5FileDirTables(MCOS, LineStr); 540 else 541 emitV2FileDirTables(MCOS); 542 543 // This is the end of the prologue, so set the value of the symbol at the 544 // end of the prologue (that was used in a previous expression). 545 MCOS->emitLabel(ProEndSym); 546 547 return std::make_pair(LineStartSym, LineEndSym); 548 } 549 550 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS, 551 MCDwarfLineTableParams Params, 552 Optional<MCDwarfLineStr> &LineStr) const { 553 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second; 554 555 // Put out the line tables. 556 for (const auto &LineSec : MCLineSections.getMCLineEntries()) 557 emitDwarfLineTable(MCOS, LineSec.first, LineSec.second); 558 559 // This is the end of the section, so set the value of the symbol at the end 560 // of this section (that was used in a previous expression). 561 MCOS->emitLabel(LineEndSym); 562 } 563 564 Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory, 565 StringRef &FileName, 566 Optional<MD5::MD5Result> Checksum, 567 Optional<StringRef> Source, 568 uint16_t DwarfVersion, 569 unsigned FileNumber) { 570 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, 571 FileNumber); 572 } 573 574 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory, 575 StringRef &FileName, Optional<MD5::MD5Result> Checksum) { 576 if (RootFile.Name.empty() || RootFile.Name != FileName.data()) 577 return false; 578 return RootFile.Checksum == Checksum; 579 } 580 581 Expected<unsigned> 582 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, 583 StringRef &FileName, 584 Optional<MD5::MD5Result> Checksum, 585 Optional<StringRef> Source, 586 uint16_t DwarfVersion, 587 unsigned FileNumber) { 588 if (Directory == CompilationDir) 589 Directory = ""; 590 if (FileName.empty()) { 591 FileName = "<stdin>"; 592 Directory = ""; 593 } 594 assert(!FileName.empty()); 595 // Keep track of whether any or all files have an MD5 checksum. 596 // If any files have embedded source, they all must. 597 if (MCDwarfFiles.empty()) { 598 trackMD5Usage(Checksum.hasValue()); 599 HasSource = (Source != None); 600 } 601 if (isRootFile(RootFile, Directory, FileName, Checksum) && DwarfVersion >= 5) 602 return 0; 603 if (FileNumber == 0) { 604 // File numbers start with 1 and/or after any file numbers 605 // allocated by inline-assembler .file directives. 606 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size(); 607 SmallString<256> Buffer; 608 auto IterBool = SourceIdMap.insert( 609 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer), 610 FileNumber)); 611 if (!IterBool.second) 612 return IterBool.first->second; 613 } 614 // Make space for this FileNumber in the MCDwarfFiles vector if needed. 615 if (FileNumber >= MCDwarfFiles.size()) 616 MCDwarfFiles.resize(FileNumber + 1); 617 618 // Get the new MCDwarfFile slot for this FileNumber. 619 MCDwarfFile &File = MCDwarfFiles[FileNumber]; 620 621 // It is an error to see the same number more than once. 622 if (!File.Name.empty()) 623 return make_error<StringError>("file number already allocated", 624 inconvertibleErrorCode()); 625 626 // If any files have embedded source, they all must. 627 if (HasSource != (Source != None)) 628 return make_error<StringError>("inconsistent use of embedded source", 629 inconvertibleErrorCode()); 630 631 if (Directory.empty()) { 632 // Separate the directory part from the basename of the FileName. 633 StringRef tFileName = sys::path::filename(FileName); 634 if (!tFileName.empty()) { 635 Directory = sys::path::parent_path(FileName); 636 if (!Directory.empty()) 637 FileName = tFileName; 638 } 639 } 640 641 // Find or make an entry in the MCDwarfDirs vector for this Directory. 642 // Capture directory name. 643 unsigned DirIndex; 644 if (Directory.empty()) { 645 // For FileNames with no directories a DirIndex of 0 is used. 646 DirIndex = 0; 647 } else { 648 DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin(); 649 if (DirIndex >= MCDwarfDirs.size()) 650 MCDwarfDirs.push_back(std::string(Directory)); 651 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with 652 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the 653 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames 654 // are stored at MCDwarfFiles[FileNumber].Name . 655 DirIndex++; 656 } 657 658 File.Name = std::string(FileName); 659 File.DirIndex = DirIndex; 660 File.Checksum = Checksum; 661 trackMD5Usage(Checksum.hasValue()); 662 File.Source = Source; 663 if (Source) 664 HasSource = true; 665 666 // return the allocated FileNumber. 667 return FileNumber; 668 } 669 670 /// Utility function to emit the encoding to a streamer. 671 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 672 int64_t LineDelta, uint64_t AddrDelta) { 673 MCContext &Context = MCOS->getContext(); 674 SmallString<256> Tmp; 675 raw_svector_ostream OS(Tmp); 676 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS); 677 MCOS->emitBytes(OS.str()); 678 } 679 680 /// Given a special op, return the address skip amount (in units of 681 /// DWARF2_LINE_MIN_INSN_LENGTH). 682 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) { 683 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange; 684 } 685 686 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. 687 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params, 688 int64_t LineDelta, uint64_t AddrDelta, 689 raw_ostream &OS) { 690 uint64_t Temp, Opcode; 691 bool NeedCopy = false; 692 693 // The maximum address skip amount that can be encoded with a special op. 694 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255); 695 696 // Scale the address delta by the minimum instruction length. 697 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 698 699 // A LineDelta of INT64_MAX is a signal that this is actually a 700 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 701 // end_sequence to emit the matrix entry. 702 if (LineDelta == INT64_MAX) { 703 if (AddrDelta == MaxSpecialAddrDelta) 704 OS << char(dwarf::DW_LNS_const_add_pc); 705 else if (AddrDelta) { 706 OS << char(dwarf::DW_LNS_advance_pc); 707 encodeULEB128(AddrDelta, OS); 708 } 709 OS << char(dwarf::DW_LNS_extended_op); 710 OS << char(1); 711 OS << char(dwarf::DW_LNE_end_sequence); 712 return; 713 } 714 715 // Bias the line delta by the base. 716 Temp = LineDelta - Params.DWARF2LineBase; 717 718 // If the line increment is out of range of a special opcode, we must encode 719 // it with DW_LNS_advance_line. 720 if (Temp >= Params.DWARF2LineRange || 721 Temp + Params.DWARF2LineOpcodeBase > 255) { 722 OS << char(dwarf::DW_LNS_advance_line); 723 encodeSLEB128(LineDelta, OS); 724 725 LineDelta = 0; 726 Temp = 0 - Params.DWARF2LineBase; 727 NeedCopy = true; 728 } 729 730 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. 731 if (LineDelta == 0 && AddrDelta == 0) { 732 OS << char(dwarf::DW_LNS_copy); 733 return; 734 } 735 736 // Bias the opcode by the special opcode base. 737 Temp += Params.DWARF2LineOpcodeBase; 738 739 // Avoid overflow when addr_delta is large. 740 if (AddrDelta < 256 + MaxSpecialAddrDelta) { 741 // Try using a special opcode. 742 Opcode = Temp + AddrDelta * Params.DWARF2LineRange; 743 if (Opcode <= 255) { 744 OS << char(Opcode); 745 return; 746 } 747 748 // Try using DW_LNS_const_add_pc followed by special op. 749 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange; 750 if (Opcode <= 255) { 751 OS << char(dwarf::DW_LNS_const_add_pc); 752 OS << char(Opcode); 753 return; 754 } 755 } 756 757 // Otherwise use DW_LNS_advance_pc. 758 OS << char(dwarf::DW_LNS_advance_pc); 759 encodeULEB128(AddrDelta, OS); 760 761 if (NeedCopy) 762 OS << char(dwarf::DW_LNS_copy); 763 else { 764 assert(Temp <= 255 && "Buggy special opcode encoding."); 765 OS << char(Temp); 766 } 767 } 768 769 bool MCDwarfLineAddr::FixedEncode(MCContext &Context, 770 MCDwarfLineTableParams Params, 771 int64_t LineDelta, uint64_t AddrDelta, 772 raw_ostream &OS, 773 uint32_t *Offset, uint32_t *Size) { 774 if (LineDelta != INT64_MAX) { 775 OS << char(dwarf::DW_LNS_advance_line); 776 encodeSLEB128(LineDelta, OS); 777 } 778 779 // Use address delta to adjust address or use absolute address to adjust 780 // address. 781 bool SetDelta; 782 // According to DWARF spec., the DW_LNS_fixed_advance_pc opcode takes a 783 // single uhalf (unencoded) operand. So, the maximum value of AddrDelta 784 // is 65535. We set a conservative upper bound for it for relaxation. 785 if (AddrDelta > 60000) { 786 const MCAsmInfo *asmInfo = Context.getAsmInfo(); 787 unsigned AddrSize = asmInfo->getCodePointerSize(); 788 789 OS << char(dwarf::DW_LNS_extended_op); 790 encodeULEB128(1 + AddrSize, OS); 791 OS << char(dwarf::DW_LNE_set_address); 792 // Generate fixup for the address. 793 *Offset = OS.tell(); 794 *Size = AddrSize; 795 SetDelta = false; 796 OS.write_zeros(AddrSize); 797 } else { 798 OS << char(dwarf::DW_LNS_fixed_advance_pc); 799 // Generate fixup for 2-bytes address delta. 800 *Offset = OS.tell(); 801 *Size = 2; 802 SetDelta = true; 803 OS << char(0); 804 OS << char(0); 805 } 806 807 if (LineDelta == INT64_MAX) { 808 OS << char(dwarf::DW_LNS_extended_op); 809 OS << char(1); 810 OS << char(dwarf::DW_LNE_end_sequence); 811 } else { 812 OS << char(dwarf::DW_LNS_copy); 813 } 814 815 return SetDelta; 816 } 817 818 // Utility function to write a tuple for .debug_abbrev. 819 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { 820 MCOS->emitULEB128IntValue(Name); 821 MCOS->emitULEB128IntValue(Form); 822 } 823 824 // When generating dwarf for assembly source files this emits 825 // the data for .debug_abbrev section which contains three DIEs. 826 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { 827 MCContext &context = MCOS->getContext(); 828 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 829 830 // DW_TAG_compile_unit DIE abbrev (1). 831 MCOS->emitULEB128IntValue(1); 832 MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit); 833 MCOS->emitInt8(dwarf::DW_CHILDREN_yes); 834 dwarf::Form SecOffsetForm = 835 context.getDwarfVersion() >= 4 836 ? dwarf::DW_FORM_sec_offset 837 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8 838 : dwarf::DW_FORM_data4); 839 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm); 840 if (context.getGenDwarfSectionSyms().size() > 1 && 841 context.getDwarfVersion() >= 3) { 842 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm); 843 } else { 844 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 845 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); 846 } 847 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 848 if (!context.getCompilationDir().empty()) 849 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); 850 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 851 if (!DwarfDebugFlags.empty()) 852 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); 853 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); 854 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); 855 EmitAbbrev(MCOS, 0, 0); 856 857 // DW_TAG_label DIE abbrev (2). 858 MCOS->emitULEB128IntValue(2); 859 MCOS->emitULEB128IntValue(dwarf::DW_TAG_label); 860 MCOS->emitInt8(dwarf::DW_CHILDREN_no); 861 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 862 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); 863 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); 864 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 865 EmitAbbrev(MCOS, 0, 0); 866 867 // Terminate the abbreviations for this compilation unit. 868 MCOS->emitInt8(0); 869 } 870 871 // When generating dwarf for assembly source files this emits the data for 872 // .debug_aranges section. This section contains a header and a table of pairs 873 // of PointerSize'ed values for the address and size of section(s) with line 874 // table entries. 875 static void EmitGenDwarfAranges(MCStreamer *MCOS, 876 const MCSymbol *InfoSectionSymbol) { 877 MCContext &context = MCOS->getContext(); 878 879 auto &Sections = context.getGenDwarfSectionSyms(); 880 881 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 882 883 unsigned UnitLengthBytes = 884 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 885 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 886 887 // This will be the length of the .debug_aranges section, first account for 888 // the size of each item in the header (see below where we emit these items). 889 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1; 890 891 // Figure the padding after the header before the table of address and size 892 // pairs who's values are PointerSize'ed. 893 const MCAsmInfo *asmInfo = context.getAsmInfo(); 894 int AddrSize = asmInfo->getCodePointerSize(); 895 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); 896 if (Pad == 2 * AddrSize) 897 Pad = 0; 898 Length += Pad; 899 900 // Add the size of the pair of PointerSize'ed values for the address and size 901 // of each section we have in the table. 902 Length += 2 * AddrSize * Sections.size(); 903 // And the pair of terminating zeros. 904 Length += 2 * AddrSize; 905 906 // Emit the header for this section. 907 if (context.getDwarfFormat() == dwarf::DWARF64) 908 // The DWARF64 mark. 909 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 910 // The 4 (8 for DWARF64) byte length not including the length of the unit 911 // length field itself. 912 MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize); 913 // The 2 byte version, which is 2. 914 MCOS->emitInt16(2); 915 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info 916 // from the start of the .debug_info. 917 if (InfoSectionSymbol) 918 MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize, 919 asmInfo->needsDwarfSectionOffsetDirective()); 920 else 921 MCOS->emitIntValue(0, OffsetSize); 922 // The 1 byte size of an address. 923 MCOS->emitInt8(AddrSize); 924 // The 1 byte size of a segment descriptor, we use a value of zero. 925 MCOS->emitInt8(0); 926 // Align the header with the padding if needed, before we put out the table. 927 for(int i = 0; i < Pad; i++) 928 MCOS->emitInt8(0); 929 930 // Now emit the table of pairs of PointerSize'ed values for the section 931 // addresses and sizes. 932 for (MCSection *Sec : Sections) { 933 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 934 MCSymbol *EndSymbol = Sec->getEndSymbol(context); 935 assert(StartSymbol && "StartSymbol must not be NULL"); 936 assert(EndSymbol && "EndSymbol must not be NULL"); 937 938 const MCExpr *Addr = MCSymbolRefExpr::create( 939 StartSymbol, MCSymbolRefExpr::VK_None, context); 940 const MCExpr *Size = 941 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 942 MCOS->emitValue(Addr, AddrSize); 943 emitAbsValue(*MCOS, Size, AddrSize); 944 } 945 946 // And finally the pair of terminating zeros. 947 MCOS->emitIntValue(0, AddrSize); 948 MCOS->emitIntValue(0, AddrSize); 949 } 950 951 // When generating dwarf for assembly source files this emits the data for 952 // .debug_info section which contains three parts. The header, the compile_unit 953 // DIE and a list of label DIEs. 954 static void EmitGenDwarfInfo(MCStreamer *MCOS, 955 const MCSymbol *AbbrevSectionSymbol, 956 const MCSymbol *LineSectionSymbol, 957 const MCSymbol *RangesSymbol) { 958 MCContext &context = MCOS->getContext(); 959 960 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 961 962 // Create a symbol at the start and end of this section used in here for the 963 // expression to calculate the length in the header. 964 MCSymbol *InfoStart = context.createTempSymbol(); 965 MCOS->emitLabel(InfoStart); 966 MCSymbol *InfoEnd = context.createTempSymbol(); 967 968 // First part: the header. 969 970 unsigned UnitLengthBytes = 971 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 972 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 973 974 if (context.getDwarfFormat() == dwarf::DWARF64) 975 // Emit DWARF64 mark. 976 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 977 978 // The 4 (8 for DWARF64) byte total length of the information for this 979 // compilation unit, not including the unit length field itself. 980 const MCExpr *Length = 981 makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes); 982 emitAbsValue(*MCOS, Length, OffsetSize); 983 984 // The 2 byte DWARF version. 985 MCOS->emitInt16(context.getDwarfVersion()); 986 987 // The DWARF v5 header has unit type, address size, abbrev offset. 988 // Earlier versions have abbrev offset, address size. 989 const MCAsmInfo &AsmInfo = *context.getAsmInfo(); 990 int AddrSize = AsmInfo.getCodePointerSize(); 991 if (context.getDwarfVersion() >= 5) { 992 MCOS->emitInt8(dwarf::DW_UT_compile); 993 MCOS->emitInt8(AddrSize); 994 } 995 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of 996 // the .debug_abbrev. 997 if (AbbrevSectionSymbol) 998 MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize, 999 AsmInfo.needsDwarfSectionOffsetDirective()); 1000 else 1001 // Since the abbrevs are at the start of the section, the offset is zero. 1002 MCOS->emitIntValue(0, OffsetSize); 1003 if (context.getDwarfVersion() <= 4) 1004 MCOS->emitInt8(AddrSize); 1005 1006 // Second part: the compile_unit DIE. 1007 1008 // The DW_TAG_compile_unit DIE abbrev (1). 1009 MCOS->emitULEB128IntValue(1); 1010 1011 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the 1012 // .debug_line section. 1013 if (LineSectionSymbol) 1014 MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize, 1015 AsmInfo.needsDwarfSectionOffsetDirective()); 1016 else 1017 // The line table is at the start of the section, so the offset is zero. 1018 MCOS->emitIntValue(0, OffsetSize); 1019 1020 if (RangesSymbol) { 1021 // There are multiple sections containing code, so we must use 1022 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the 1023 // start of the .debug_ranges/.debug_rnglists. 1024 MCOS->emitSymbolValue(RangesSymbol, OffsetSize); 1025 } else { 1026 // If we only have one non-empty code section, we can use the simpler 1027 // AT_low_pc and AT_high_pc attributes. 1028 1029 // Find the first (and only) non-empty text section 1030 auto &Sections = context.getGenDwarfSectionSyms(); 1031 const auto TextSection = Sections.begin(); 1032 assert(TextSection != Sections.end() && "No text section found"); 1033 1034 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol(); 1035 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context); 1036 assert(StartSymbol && "StartSymbol must not be NULL"); 1037 assert(EndSymbol && "EndSymbol must not be NULL"); 1038 1039 // AT_low_pc, the first address of the default .text section. 1040 const MCExpr *Start = MCSymbolRefExpr::create( 1041 StartSymbol, MCSymbolRefExpr::VK_None, context); 1042 MCOS->emitValue(Start, AddrSize); 1043 1044 // AT_high_pc, the last address of the default .text section. 1045 const MCExpr *End = MCSymbolRefExpr::create( 1046 EndSymbol, MCSymbolRefExpr::VK_None, context); 1047 MCOS->emitValue(End, AddrSize); 1048 } 1049 1050 // AT_name, the name of the source file. Reconstruct from the first directory 1051 // and file table entries. 1052 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs(); 1053 if (MCDwarfDirs.size() > 0) { 1054 MCOS->emitBytes(MCDwarfDirs[0]); 1055 MCOS->emitBytes(sys::path::get_separator()); 1056 } 1057 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles(); 1058 // MCDwarfFiles might be empty if we have an empty source file. 1059 // If it's not empty, [0] is unused and [1] is the first actual file. 1060 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2); 1061 const MCDwarfFile &RootFile = 1062 MCDwarfFiles.empty() 1063 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile() 1064 : MCDwarfFiles[1]; 1065 MCOS->emitBytes(RootFile.Name); 1066 MCOS->emitInt8(0); // NULL byte to terminate the string. 1067 1068 // AT_comp_dir, the working directory the assembly was done in. 1069 if (!context.getCompilationDir().empty()) { 1070 MCOS->emitBytes(context.getCompilationDir()); 1071 MCOS->emitInt8(0); // NULL byte to terminate the string. 1072 } 1073 1074 // AT_APPLE_flags, the command line arguments of the assembler tool. 1075 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 1076 if (!DwarfDebugFlags.empty()){ 1077 MCOS->emitBytes(DwarfDebugFlags); 1078 MCOS->emitInt8(0); // NULL byte to terminate the string. 1079 } 1080 1081 // AT_producer, the version of the assembler tool. 1082 StringRef DwarfDebugProducer = context.getDwarfDebugProducer(); 1083 if (!DwarfDebugProducer.empty()) 1084 MCOS->emitBytes(DwarfDebugProducer); 1085 else 1086 MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")")); 1087 MCOS->emitInt8(0); // NULL byte to terminate the string. 1088 1089 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 1090 // draft has no standard code for assembler. 1091 MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler); 1092 1093 // Third part: the list of label DIEs. 1094 1095 // Loop on saved info for dwarf labels and create the DIEs for them. 1096 const std::vector<MCGenDwarfLabelEntry> &Entries = 1097 MCOS->getContext().getMCGenDwarfLabelEntries(); 1098 for (const auto &Entry : Entries) { 1099 // The DW_TAG_label DIE abbrev (2). 1100 MCOS->emitULEB128IntValue(2); 1101 1102 // AT_name, of the label without any leading underbar. 1103 MCOS->emitBytes(Entry.getName()); 1104 MCOS->emitInt8(0); // NULL byte to terminate the string. 1105 1106 // AT_decl_file, index into the file table. 1107 MCOS->emitInt32(Entry.getFileNumber()); 1108 1109 // AT_decl_line, source line number. 1110 MCOS->emitInt32(Entry.getLineNumber()); 1111 1112 // AT_low_pc, start address of the label. 1113 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(), 1114 MCSymbolRefExpr::VK_None, context); 1115 MCOS->emitValue(AT_low_pc, AddrSize); 1116 } 1117 1118 // Add the NULL DIE terminating the Compile Unit DIE's. 1119 MCOS->emitInt8(0); 1120 1121 // Now set the value of the symbol at the end of the info section. 1122 MCOS->emitLabel(InfoEnd); 1123 } 1124 1125 // When generating dwarf for assembly source files this emits the data for 1126 // .debug_ranges section. We only emit one range list, which spans all of the 1127 // executable sections of this file. 1128 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) { 1129 MCContext &context = MCOS->getContext(); 1130 auto &Sections = context.getGenDwarfSectionSyms(); 1131 1132 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 1133 int AddrSize = AsmInfo->getCodePointerSize(); 1134 MCSymbol *RangesSymbol; 1135 1136 if (MCOS->getContext().getDwarfVersion() >= 5) { 1137 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRnglistsSection()); 1138 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS); 1139 MCOS->AddComment("Offset entry count"); 1140 MCOS->emitInt32(0); 1141 RangesSymbol = context.createTempSymbol("debug_rnglist0_start"); 1142 MCOS->emitLabel(RangesSymbol); 1143 for (MCSection *Sec : Sections) { 1144 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 1145 const MCSymbol *EndSymbol = Sec->getEndSymbol(context); 1146 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 1147 StartSymbol, MCSymbolRefExpr::VK_None, context); 1148 const MCExpr *SectionSize = 1149 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 1150 MCOS->emitInt8(dwarf::DW_RLE_start_length); 1151 MCOS->emitValue(SectionStartAddr, AddrSize); 1152 MCOS->emitULEB128Value(SectionSize); 1153 } 1154 MCOS->emitInt8(dwarf::DW_RLE_end_of_list); 1155 MCOS->emitLabel(EndSymbol); 1156 } else { 1157 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection()); 1158 RangesSymbol = context.createTempSymbol("debug_ranges_start"); 1159 MCOS->emitLabel(RangesSymbol); 1160 for (MCSection *Sec : Sections) { 1161 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 1162 const MCSymbol *EndSymbol = Sec->getEndSymbol(context); 1163 1164 // Emit a base address selection entry for the section start. 1165 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 1166 StartSymbol, MCSymbolRefExpr::VK_None, context); 1167 MCOS->emitFill(AddrSize, 0xFF); 1168 MCOS->emitValue(SectionStartAddr, AddrSize); 1169 1170 // Emit a range list entry spanning this section. 1171 const MCExpr *SectionSize = 1172 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 1173 MCOS->emitIntValue(0, AddrSize); 1174 emitAbsValue(*MCOS, SectionSize, AddrSize); 1175 } 1176 1177 // Emit end of list entry 1178 MCOS->emitIntValue(0, AddrSize); 1179 MCOS->emitIntValue(0, AddrSize); 1180 } 1181 1182 return RangesSymbol; 1183 } 1184 1185 // 1186 // When generating dwarf for assembly source files this emits the Dwarf 1187 // sections. 1188 // 1189 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) { 1190 MCContext &context = MCOS->getContext(); 1191 1192 // Create the dwarf sections in this order (.debug_line already created). 1193 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 1194 bool CreateDwarfSectionSymbols = 1195 AsmInfo->doesDwarfUseRelocationsAcrossSections(); 1196 MCSymbol *LineSectionSymbol = nullptr; 1197 if (CreateDwarfSectionSymbols) 1198 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0); 1199 MCSymbol *AbbrevSectionSymbol = nullptr; 1200 MCSymbol *InfoSectionSymbol = nullptr; 1201 MCSymbol *RangesSymbol = nullptr; 1202 1203 // Create end symbols for each section, and remove empty sections 1204 MCOS->getContext().finalizeDwarfSections(*MCOS); 1205 1206 // If there are no sections to generate debug info for, we don't need 1207 // to do anything 1208 if (MCOS->getContext().getGenDwarfSectionSyms().empty()) 1209 return; 1210 1211 // We only use the .debug_ranges section if we have multiple code sections, 1212 // and we are emitting a DWARF version which supports it. 1213 const bool UseRangesSection = 1214 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 && 1215 MCOS->getContext().getDwarfVersion() >= 3; 1216 CreateDwarfSectionSymbols |= UseRangesSection; 1217 1218 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 1219 if (CreateDwarfSectionSymbols) { 1220 InfoSectionSymbol = context.createTempSymbol(); 1221 MCOS->emitLabel(InfoSectionSymbol); 1222 } 1223 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 1224 if (CreateDwarfSectionSymbols) { 1225 AbbrevSectionSymbol = context.createTempSymbol(); 1226 MCOS->emitLabel(AbbrevSectionSymbol); 1227 } 1228 1229 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 1230 1231 // Output the data for .debug_aranges section. 1232 EmitGenDwarfAranges(MCOS, InfoSectionSymbol); 1233 1234 if (UseRangesSection) { 1235 RangesSymbol = emitGenDwarfRanges(MCOS); 1236 assert(RangesSymbol); 1237 } 1238 1239 // Output the data for .debug_abbrev section. 1240 EmitGenDwarfAbbrev(MCOS); 1241 1242 // Output the data for .debug_info section. 1243 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol); 1244 } 1245 1246 // 1247 // When generating dwarf for assembly source files this is called when symbol 1248 // for a label is created. If this symbol is not a temporary and is in the 1249 // section that dwarf is being generated for, save the needed info to create 1250 // a dwarf label. 1251 // 1252 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, 1253 SourceMgr &SrcMgr, SMLoc &Loc) { 1254 // We won't create dwarf labels for temporary symbols. 1255 if (Symbol->isTemporary()) 1256 return; 1257 MCContext &context = MCOS->getContext(); 1258 // We won't create dwarf labels for symbols in sections that we are not 1259 // generating debug info for. 1260 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly())) 1261 return; 1262 1263 // The dwarf label's name does not have the symbol name's leading 1264 // underbar if any. 1265 StringRef Name = Symbol->getName(); 1266 if (Name.startswith("_")) 1267 Name = Name.substr(1, Name.size()-1); 1268 1269 // Get the dwarf file number to be used for the dwarf label. 1270 unsigned FileNumber = context.getGenDwarfFileNumber(); 1271 1272 // Finding the line number is the expensive part which is why we just don't 1273 // pass it in as for some symbols we won't create a dwarf label. 1274 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); 1275 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); 1276 1277 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc 1278 // values so that they don't have things like an ARM thumb bit from the 1279 // original symbol. So when used they won't get a low bit set after 1280 // relocation. 1281 MCSymbol *Label = context.createTempSymbol(); 1282 MCOS->emitLabel(Label); 1283 1284 // Create and entry for the info and add it to the other entries. 1285 MCOS->getContext().addMCGenDwarfLabelEntry( 1286 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label)); 1287 } 1288 1289 static int getDataAlignmentFactor(MCStreamer &streamer) { 1290 MCContext &context = streamer.getContext(); 1291 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1292 int size = asmInfo->getCalleeSaveStackSlotSize(); 1293 if (asmInfo->isStackGrowthDirectionUp()) 1294 return size; 1295 else 1296 return -size; 1297 } 1298 1299 static unsigned getSizeForEncoding(MCStreamer &streamer, 1300 unsigned symbolEncoding) { 1301 MCContext &context = streamer.getContext(); 1302 unsigned format = symbolEncoding & 0x0f; 1303 switch (format) { 1304 default: llvm_unreachable("Unknown Encoding"); 1305 case dwarf::DW_EH_PE_absptr: 1306 case dwarf::DW_EH_PE_signed: 1307 return context.getAsmInfo()->getCodePointerSize(); 1308 case dwarf::DW_EH_PE_udata2: 1309 case dwarf::DW_EH_PE_sdata2: 1310 return 2; 1311 case dwarf::DW_EH_PE_udata4: 1312 case dwarf::DW_EH_PE_sdata4: 1313 return 4; 1314 case dwarf::DW_EH_PE_udata8: 1315 case dwarf::DW_EH_PE_sdata8: 1316 return 8; 1317 } 1318 } 1319 1320 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol, 1321 unsigned symbolEncoding, bool isEH) { 1322 MCContext &context = streamer.getContext(); 1323 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1324 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol, 1325 symbolEncoding, 1326 streamer); 1327 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1328 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH) 1329 emitAbsValue(streamer, v, size); 1330 else 1331 streamer.emitValue(v, size); 1332 } 1333 1334 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, 1335 unsigned symbolEncoding) { 1336 MCContext &context = streamer.getContext(); 1337 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1338 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol, 1339 symbolEncoding, 1340 streamer); 1341 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1342 streamer.emitValue(v, size); 1343 } 1344 1345 namespace { 1346 1347 class FrameEmitterImpl { 1348 int CFAOffset = 0; 1349 int InitialCFAOffset = 0; 1350 bool IsEH; 1351 MCObjectStreamer &Streamer; 1352 1353 public: 1354 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer) 1355 : IsEH(IsEH), Streamer(Streamer) {} 1356 1357 /// Emit the unwind information in a compact way. 1358 void EmitCompactUnwind(const MCDwarfFrameInfo &frame); 1359 1360 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F); 1361 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame, 1362 bool LastInSection, const MCSymbol &SectionStart); 1363 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1364 MCSymbol *BaseLabel); 1365 void emitCFIInstruction(const MCCFIInstruction &Instr); 1366 }; 1367 1368 } // end anonymous namespace 1369 1370 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) { 1371 Streamer.emitInt8(Encoding); 1372 } 1373 1374 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) { 1375 int dataAlignmentFactor = getDataAlignmentFactor(Streamer); 1376 auto *MRI = Streamer.getContext().getRegisterInfo(); 1377 1378 switch (Instr.getOperation()) { 1379 case MCCFIInstruction::OpRegister: { 1380 unsigned Reg1 = Instr.getRegister(); 1381 unsigned Reg2 = Instr.getRegister2(); 1382 if (!IsEH) { 1383 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1); 1384 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2); 1385 } 1386 Streamer.emitInt8(dwarf::DW_CFA_register); 1387 Streamer.emitULEB128IntValue(Reg1); 1388 Streamer.emitULEB128IntValue(Reg2); 1389 return; 1390 } 1391 case MCCFIInstruction::OpWindowSave: 1392 Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save); 1393 return; 1394 1395 case MCCFIInstruction::OpNegateRAState: 1396 Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state); 1397 return; 1398 1399 case MCCFIInstruction::OpUndefined: { 1400 unsigned Reg = Instr.getRegister(); 1401 Streamer.emitInt8(dwarf::DW_CFA_undefined); 1402 Streamer.emitULEB128IntValue(Reg); 1403 return; 1404 } 1405 case MCCFIInstruction::OpAdjustCfaOffset: 1406 case MCCFIInstruction::OpDefCfaOffset: { 1407 const bool IsRelative = 1408 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset; 1409 1410 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset); 1411 1412 if (IsRelative) 1413 CFAOffset += Instr.getOffset(); 1414 else 1415 CFAOffset = Instr.getOffset(); 1416 1417 Streamer.emitULEB128IntValue(CFAOffset); 1418 1419 return; 1420 } 1421 case MCCFIInstruction::OpDefCfa: { 1422 unsigned Reg = Instr.getRegister(); 1423 if (!IsEH) 1424 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1425 Streamer.emitInt8(dwarf::DW_CFA_def_cfa); 1426 Streamer.emitULEB128IntValue(Reg); 1427 CFAOffset = Instr.getOffset(); 1428 Streamer.emitULEB128IntValue(CFAOffset); 1429 1430 return; 1431 } 1432 case MCCFIInstruction::OpDefCfaRegister: { 1433 unsigned Reg = Instr.getRegister(); 1434 if (!IsEH) 1435 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1436 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register); 1437 Streamer.emitULEB128IntValue(Reg); 1438 1439 return; 1440 } 1441 case MCCFIInstruction::OpOffset: 1442 case MCCFIInstruction::OpRelOffset: { 1443 const bool IsRelative = 1444 Instr.getOperation() == MCCFIInstruction::OpRelOffset; 1445 1446 unsigned Reg = Instr.getRegister(); 1447 if (!IsEH) 1448 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1449 1450 int Offset = Instr.getOffset(); 1451 if (IsRelative) 1452 Offset -= CFAOffset; 1453 Offset = Offset / dataAlignmentFactor; 1454 1455 if (Offset < 0) { 1456 Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf); 1457 Streamer.emitULEB128IntValue(Reg); 1458 Streamer.emitSLEB128IntValue(Offset); 1459 } else if (Reg < 64) { 1460 Streamer.emitInt8(dwarf::DW_CFA_offset + Reg); 1461 Streamer.emitULEB128IntValue(Offset); 1462 } else { 1463 Streamer.emitInt8(dwarf::DW_CFA_offset_extended); 1464 Streamer.emitULEB128IntValue(Reg); 1465 Streamer.emitULEB128IntValue(Offset); 1466 } 1467 return; 1468 } 1469 case MCCFIInstruction::OpRememberState: 1470 Streamer.emitInt8(dwarf::DW_CFA_remember_state); 1471 return; 1472 case MCCFIInstruction::OpRestoreState: 1473 Streamer.emitInt8(dwarf::DW_CFA_restore_state); 1474 return; 1475 case MCCFIInstruction::OpSameValue: { 1476 unsigned Reg = Instr.getRegister(); 1477 Streamer.emitInt8(dwarf::DW_CFA_same_value); 1478 Streamer.emitULEB128IntValue(Reg); 1479 return; 1480 } 1481 case MCCFIInstruction::OpRestore: { 1482 unsigned Reg = Instr.getRegister(); 1483 if (!IsEH) 1484 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1485 if (Reg < 64) { 1486 Streamer.emitInt8(dwarf::DW_CFA_restore | Reg); 1487 } else { 1488 Streamer.emitInt8(dwarf::DW_CFA_restore_extended); 1489 Streamer.emitULEB128IntValue(Reg); 1490 } 1491 return; 1492 } 1493 case MCCFIInstruction::OpGnuArgsSize: 1494 Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size); 1495 Streamer.emitULEB128IntValue(Instr.getOffset()); 1496 return; 1497 1498 case MCCFIInstruction::OpEscape: 1499 Streamer.emitBytes(Instr.getValues()); 1500 return; 1501 } 1502 llvm_unreachable("Unhandled case in switch"); 1503 } 1504 1505 /// Emit frame instructions to describe the layout of the frame. 1506 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1507 MCSymbol *BaseLabel) { 1508 for (const MCCFIInstruction &Instr : Instrs) { 1509 MCSymbol *Label = Instr.getLabel(); 1510 // Throw out move if the label is invalid. 1511 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. 1512 1513 // Advance row if new location. 1514 if (BaseLabel && Label) { 1515 MCSymbol *ThisSym = Label; 1516 if (ThisSym != BaseLabel) { 1517 Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); 1518 BaseLabel = ThisSym; 1519 } 1520 } 1521 1522 emitCFIInstruction(Instr); 1523 } 1524 } 1525 1526 /// Emit the unwind information in a compact way. 1527 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) { 1528 MCContext &Context = Streamer.getContext(); 1529 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1530 1531 // range-start range-length compact-unwind-enc personality-func lsda 1532 // _foo LfooEnd-_foo 0x00000023 0 0 1533 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 1534 // 1535 // .section __LD,__compact_unwind,regular,debug 1536 // 1537 // # compact unwind for _foo 1538 // .quad _foo 1539 // .set L1,LfooEnd-_foo 1540 // .long L1 1541 // .long 0x01010001 1542 // .quad 0 1543 // .quad 0 1544 // 1545 // # compact unwind for _bar 1546 // .quad _bar 1547 // .set L2,LbarEnd-_bar 1548 // .long L2 1549 // .long 0x01020011 1550 // .quad __gxx_personality 1551 // .quad except_tab1 1552 1553 uint32_t Encoding = Frame.CompactUnwindEncoding; 1554 if (!Encoding) return; 1555 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly()); 1556 1557 // The encoding needs to know we have an LSDA. 1558 if (!DwarfEHFrameOnly && Frame.Lsda) 1559 Encoding |= 0x40000000; 1560 1561 // Range Start 1562 unsigned FDEEncoding = MOFI->getFDEEncoding(); 1563 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); 1564 Streamer.emitSymbolValue(Frame.Begin, Size); 1565 1566 // Range Length 1567 const MCExpr *Range = 1568 makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0); 1569 emitAbsValue(Streamer, Range, 4); 1570 1571 // Compact Encoding 1572 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); 1573 Streamer.emitIntValue(Encoding, Size); 1574 1575 // Personality Function 1576 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); 1577 if (!DwarfEHFrameOnly && Frame.Personality) 1578 Streamer.emitSymbolValue(Frame.Personality, Size); 1579 else 1580 Streamer.emitIntValue(0, Size); // No personality fn 1581 1582 // LSDA 1583 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); 1584 if (!DwarfEHFrameOnly && Frame.Lsda) 1585 Streamer.emitSymbolValue(Frame.Lsda, Size); 1586 else 1587 Streamer.emitIntValue(0, Size); // No LSDA 1588 } 1589 1590 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) { 1591 if (IsEH) 1592 return 1; 1593 switch (DwarfVersion) { 1594 case 2: 1595 return 1; 1596 case 3: 1597 return 3; 1598 case 4: 1599 case 5: 1600 return 4; 1601 } 1602 llvm_unreachable("Unknown version"); 1603 } 1604 1605 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) { 1606 MCContext &context = Streamer.getContext(); 1607 const MCRegisterInfo *MRI = context.getRegisterInfo(); 1608 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1609 1610 MCSymbol *sectionStart = context.createTempSymbol(); 1611 Streamer.emitLabel(sectionStart); 1612 1613 MCSymbol *sectionEnd = context.createTempSymbol(); 1614 1615 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat(); 1616 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format); 1617 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format); 1618 bool IsDwarf64 = Format == dwarf::DWARF64; 1619 1620 if (IsDwarf64) 1621 // DWARF64 mark 1622 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64); 1623 1624 // Length 1625 const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart, 1626 *sectionEnd, UnitLengthBytes); 1627 emitAbsValue(Streamer, Length, OffsetSize); 1628 1629 // CIE ID 1630 uint64_t CIE_ID = 1631 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID); 1632 Streamer.emitIntValue(CIE_ID, OffsetSize); 1633 1634 // Version 1635 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion()); 1636 Streamer.emitInt8(CIEVersion); 1637 1638 if (IsEH) { 1639 SmallString<8> Augmentation; 1640 Augmentation += "z"; 1641 if (Frame.Personality) 1642 Augmentation += "P"; 1643 if (Frame.Lsda) 1644 Augmentation += "L"; 1645 Augmentation += "R"; 1646 if (Frame.IsSignalFrame) 1647 Augmentation += "S"; 1648 if (Frame.IsBKeyFrame) 1649 Augmentation += "B"; 1650 Streamer.emitBytes(Augmentation); 1651 } 1652 Streamer.emitInt8(0); 1653 1654 if (CIEVersion >= 4) { 1655 // Address Size 1656 Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize()); 1657 1658 // Segment Descriptor Size 1659 Streamer.emitInt8(0); 1660 } 1661 1662 // Code Alignment Factor 1663 Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment()); 1664 1665 // Data Alignment Factor 1666 Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer)); 1667 1668 // Return Address Register 1669 unsigned RAReg = Frame.RAReg; 1670 if (RAReg == static_cast<unsigned>(INT_MAX)) 1671 RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH); 1672 1673 if (CIEVersion == 1) { 1674 assert(RAReg <= 255 && 1675 "DWARF 2 encodes return_address_register in one byte"); 1676 Streamer.emitInt8(RAReg); 1677 } else { 1678 Streamer.emitULEB128IntValue(RAReg); 1679 } 1680 1681 // Augmentation Data Length (optional) 1682 unsigned augmentationLength = 0; 1683 if (IsEH) { 1684 if (Frame.Personality) { 1685 // Personality Encoding 1686 augmentationLength += 1; 1687 // Personality 1688 augmentationLength += 1689 getSizeForEncoding(Streamer, Frame.PersonalityEncoding); 1690 } 1691 if (Frame.Lsda) 1692 augmentationLength += 1; 1693 // Encoding of the FDE pointers 1694 augmentationLength += 1; 1695 1696 Streamer.emitULEB128IntValue(augmentationLength); 1697 1698 // Augmentation Data (optional) 1699 if (Frame.Personality) { 1700 // Personality Encoding 1701 emitEncodingByte(Streamer, Frame.PersonalityEncoding); 1702 // Personality 1703 EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding); 1704 } 1705 1706 if (Frame.Lsda) 1707 emitEncodingByte(Streamer, Frame.LsdaEncoding); 1708 1709 // Encoding of the FDE pointers 1710 emitEncodingByte(Streamer, MOFI->getFDEEncoding()); 1711 } 1712 1713 // Initial Instructions 1714 1715 const MCAsmInfo *MAI = context.getAsmInfo(); 1716 if (!Frame.IsSimple) { 1717 const std::vector<MCCFIInstruction> &Instructions = 1718 MAI->getInitialFrameState(); 1719 emitCFIInstructions(Instructions, nullptr); 1720 } 1721 1722 InitialCFAOffset = CFAOffset; 1723 1724 // Padding 1725 Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize()); 1726 1727 Streamer.emitLabel(sectionEnd); 1728 return *sectionStart; 1729 } 1730 1731 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart, 1732 const MCDwarfFrameInfo &frame, 1733 bool LastInSection, 1734 const MCSymbol &SectionStart) { 1735 MCContext &context = Streamer.getContext(); 1736 MCSymbol *fdeStart = context.createTempSymbol(); 1737 MCSymbol *fdeEnd = context.createTempSymbol(); 1738 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1739 1740 CFAOffset = InitialCFAOffset; 1741 1742 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat(); 1743 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format); 1744 1745 if (Format == dwarf::DWARF64) 1746 // DWARF64 mark 1747 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64); 1748 1749 // Length 1750 const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0); 1751 emitAbsValue(Streamer, Length, OffsetSize); 1752 1753 Streamer.emitLabel(fdeStart); 1754 1755 // CIE Pointer 1756 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1757 if (IsEH) { 1758 const MCExpr *offset = 1759 makeEndMinusStartExpr(context, cieStart, *fdeStart, 0); 1760 emitAbsValue(Streamer, offset, OffsetSize); 1761 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) { 1762 const MCExpr *offset = 1763 makeEndMinusStartExpr(context, SectionStart, cieStart, 0); 1764 emitAbsValue(Streamer, offset, OffsetSize); 1765 } else { 1766 Streamer.emitSymbolValue(&cieStart, OffsetSize, 1767 asmInfo->needsDwarfSectionOffsetDirective()); 1768 } 1769 1770 // PC Begin 1771 unsigned PCEncoding = 1772 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr; 1773 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding); 1774 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH); 1775 1776 // PC Range 1777 const MCExpr *Range = 1778 makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0); 1779 emitAbsValue(Streamer, Range, PCSize); 1780 1781 if (IsEH) { 1782 // Augmentation Data Length 1783 unsigned augmentationLength = 0; 1784 1785 if (frame.Lsda) 1786 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding); 1787 1788 Streamer.emitULEB128IntValue(augmentationLength); 1789 1790 // Augmentation Data 1791 if (frame.Lsda) 1792 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true); 1793 } 1794 1795 // Call Frame Instructions 1796 emitCFIInstructions(frame.Instructions, frame.Begin); 1797 1798 // Padding 1799 // The size of a .eh_frame section has to be a multiple of the alignment 1800 // since a null CIE is interpreted as the end. Old systems overaligned 1801 // .eh_frame, so we do too and account for it in the last FDE. 1802 unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize; 1803 Streamer.emitValueToAlignment(Align); 1804 1805 Streamer.emitLabel(fdeEnd); 1806 } 1807 1808 namespace { 1809 1810 struct CIEKey { 1811 static const CIEKey getEmptyKey() { 1812 return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX), 1813 false); 1814 } 1815 1816 static const CIEKey getTombstoneKey() { 1817 return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX), 1818 false); 1819 } 1820 1821 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding, 1822 unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple, 1823 unsigned RAReg, bool IsBKeyFrame) 1824 : Personality(Personality), PersonalityEncoding(PersonalityEncoding), 1825 LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame), 1826 IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {} 1827 1828 explicit CIEKey(const MCDwarfFrameInfo &Frame) 1829 : Personality(Frame.Personality), 1830 PersonalityEncoding(Frame.PersonalityEncoding), 1831 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame), 1832 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg), 1833 IsBKeyFrame(Frame.IsBKeyFrame) {} 1834 1835 StringRef PersonalityName() const { 1836 if (!Personality) 1837 return StringRef(); 1838 return Personality->getName(); 1839 } 1840 1841 bool operator<(const CIEKey &Other) const { 1842 return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding, 1843 IsSignalFrame, IsSimple, RAReg) < 1844 std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding, 1845 Other.LsdaEncoding, Other.IsSignalFrame, 1846 Other.IsSimple, Other.RAReg); 1847 } 1848 1849 const MCSymbol *Personality; 1850 unsigned PersonalityEncoding; 1851 unsigned LsdaEncoding; 1852 bool IsSignalFrame; 1853 bool IsSimple; 1854 unsigned RAReg; 1855 bool IsBKeyFrame; 1856 }; 1857 1858 } // end anonymous namespace 1859 1860 namespace llvm { 1861 1862 template <> struct DenseMapInfo<CIEKey> { 1863 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); } 1864 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); } 1865 1866 static unsigned getHashValue(const CIEKey &Key) { 1867 return static_cast<unsigned>(hash_combine( 1868 Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding, 1869 Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame)); 1870 } 1871 1872 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) { 1873 return LHS.Personality == RHS.Personality && 1874 LHS.PersonalityEncoding == RHS.PersonalityEncoding && 1875 LHS.LsdaEncoding == RHS.LsdaEncoding && 1876 LHS.IsSignalFrame == RHS.IsSignalFrame && 1877 LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg && 1878 LHS.IsBKeyFrame == RHS.IsBKeyFrame; 1879 } 1880 }; 1881 1882 } // end namespace llvm 1883 1884 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB, 1885 bool IsEH) { 1886 Streamer.generateCompactUnwindEncodings(MAB); 1887 1888 MCContext &Context = Streamer.getContext(); 1889 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1890 const MCAsmInfo *AsmInfo = Context.getAsmInfo(); 1891 FrameEmitterImpl Emitter(IsEH, Streamer); 1892 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos(); 1893 1894 // Emit the compact unwind info if available. 1895 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame(); 1896 if (IsEH && MOFI->getCompactUnwindSection()) { 1897 bool SectionEmitted = false; 1898 for (const MCDwarfFrameInfo &Frame : FrameArray) { 1899 if (Frame.CompactUnwindEncoding == 0) continue; 1900 if (!SectionEmitted) { 1901 Streamer.SwitchSection(MOFI->getCompactUnwindSection()); 1902 Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize()); 1903 SectionEmitted = true; 1904 } 1905 NeedsEHFrameSection |= 1906 Frame.CompactUnwindEncoding == 1907 MOFI->getCompactUnwindDwarfEHFrameOnly(); 1908 Emitter.EmitCompactUnwind(Frame); 1909 } 1910 } 1911 1912 if (!NeedsEHFrameSection) return; 1913 1914 MCSection &Section = 1915 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection() 1916 : *MOFI->getDwarfFrameSection(); 1917 1918 Streamer.SwitchSection(&Section); 1919 MCSymbol *SectionStart = Context.createTempSymbol(); 1920 Streamer.emitLabel(SectionStart); 1921 1922 DenseMap<CIEKey, const MCSymbol *> CIEStarts; 1923 1924 const MCSymbol *DummyDebugKey = nullptr; 1925 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind(); 1926 // Sort the FDEs by their corresponding CIE before we emit them. 1927 // This isn't technically necessary according to the DWARF standard, 1928 // but the Android libunwindstack rejects eh_frame sections where 1929 // an FDE refers to a CIE other than the closest previous CIE. 1930 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end()); 1931 llvm::stable_sort(FrameArrayX, 1932 [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) { 1933 return CIEKey(X) < CIEKey(Y); 1934 }); 1935 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) { 1936 const MCDwarfFrameInfo &Frame = *I; 1937 ++I; 1938 if (CanOmitDwarf && Frame.CompactUnwindEncoding != 1939 MOFI->getCompactUnwindDwarfEHFrameOnly()) 1940 // Don't generate an EH frame if we don't need one. I.e., it's taken care 1941 // of by the compact unwind encoding. 1942 continue; 1943 1944 CIEKey Key(Frame); 1945 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; 1946 if (!CIEStart) 1947 CIEStart = &Emitter.EmitCIE(Frame); 1948 1949 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart); 1950 } 1951 } 1952 1953 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer, 1954 uint64_t AddrDelta) { 1955 MCContext &Context = Streamer.getContext(); 1956 SmallString<256> Tmp; 1957 raw_svector_ostream OS(Tmp); 1958 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS); 1959 Streamer.emitBytes(OS.str()); 1960 } 1961 1962 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context, 1963 uint64_t AddrDelta, raw_ostream &OS, 1964 uint32_t *Offset, uint32_t *Size) { 1965 // Scale the address delta by the minimum instruction length. 1966 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 1967 1968 bool WithFixups = false; 1969 if (Offset && Size) 1970 WithFixups = true; 1971 1972 support::endianness E = 1973 Context.getAsmInfo()->isLittleEndian() ? support::little : support::big; 1974 if (AddrDelta == 0) { 1975 if (WithFixups) { 1976 *Offset = 0; 1977 *Size = 0; 1978 } 1979 } else if (isUIntN(6, AddrDelta)) { 1980 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; 1981 if (WithFixups) { 1982 *Offset = OS.tell(); 1983 *Size = 6; 1984 OS << uint8_t(dwarf::DW_CFA_advance_loc); 1985 } else 1986 OS << Opcode; 1987 } else if (isUInt<8>(AddrDelta)) { 1988 OS << uint8_t(dwarf::DW_CFA_advance_loc1); 1989 if (WithFixups) { 1990 *Offset = OS.tell(); 1991 *Size = 8; 1992 OS.write_zeros(1); 1993 } else 1994 OS << uint8_t(AddrDelta); 1995 } else if (isUInt<16>(AddrDelta)) { 1996 OS << uint8_t(dwarf::DW_CFA_advance_loc2); 1997 if (WithFixups) { 1998 *Offset = OS.tell(); 1999 *Size = 16; 2000 OS.write_zeros(2); 2001 } else 2002 support::endian::write<uint16_t>(OS, AddrDelta, E); 2003 } else { 2004 assert(isUInt<32>(AddrDelta)); 2005 OS << uint8_t(dwarf::DW_CFA_advance_loc4); 2006 if (WithFixups) { 2007 *Offset = OS.tell(); 2008 *Size = 32; 2009 OS.write_zeros(4); 2010 } else 2011 support::endian::write<uint32_t>(OS, AddrDelta, E); 2012 } 2013 } 2014