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