1 //===- MCCodeView.h - Machine Code CodeView support -------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Holds state from .cv_file and .cv_loc directives for later emission. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/MC/MCCodeView.h" 15 #include "llvm/MC/MCAsmLayout.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/DebugInfo/CodeView/CodeView.h" 18 #include "llvm/DebugInfo/CodeView/Line.h" 19 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 20 #include "llvm/MC/MCContext.h" 21 #include "llvm/MC/MCObjectStreamer.h" 22 #include "llvm/MC/MCValue.h" 23 #include "llvm/Support/COFF.h" 24 #include "llvm/Support/EndianStream.h" 25 26 using namespace llvm; 27 using namespace llvm::codeview; 28 29 CodeViewContext::CodeViewContext() {} 30 31 CodeViewContext::~CodeViewContext() { 32 // If someone inserted strings into the string table but never actually 33 // emitted them somewhere, clean up the fragment. 34 if (!InsertedStrTabFragment) 35 delete StrTabFragment; 36 } 37 38 /// This is a valid number for use with .cv_loc if we've already seen a .cv_file 39 /// for it. 40 bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const { 41 unsigned Idx = FileNumber - 1; 42 if (Idx < Filenames.size()) 43 return !Filenames[Idx].empty(); 44 return false; 45 } 46 47 bool CodeViewContext::addFile(unsigned FileNumber, StringRef Filename) { 48 assert(FileNumber > 0); 49 Filename = addToStringTable(Filename); 50 unsigned Idx = FileNumber - 1; 51 if (Idx >= Filenames.size()) 52 Filenames.resize(Idx + 1); 53 54 if (Filename.empty()) 55 Filename = "<stdin>"; 56 57 if (!Filenames[Idx].empty()) 58 return false; 59 60 // FIXME: We should store the string table offset of the filename, rather than 61 // the filename itself for efficiency. 62 Filename = addToStringTable(Filename); 63 64 Filenames[Idx] = Filename; 65 return true; 66 } 67 68 MCDataFragment *CodeViewContext::getStringTableFragment() { 69 if (!StrTabFragment) { 70 StrTabFragment = new MCDataFragment(); 71 // Start a new string table out with a null byte. 72 StrTabFragment->getContents().push_back('\0'); 73 } 74 return StrTabFragment; 75 } 76 77 StringRef CodeViewContext::addToStringTable(StringRef S) { 78 SmallVectorImpl<char> &Contents = getStringTableFragment()->getContents(); 79 auto Insertion = 80 StringTable.insert(std::make_pair(S, unsigned(Contents.size()))); 81 // Return the string from the table, since it is stable. 82 S = Insertion.first->first(); 83 if (Insertion.second) { 84 // The string map key is always null terminated. 85 Contents.append(S.begin(), S.end() + 1); 86 } 87 return S; 88 } 89 90 unsigned CodeViewContext::getStringTableOffset(StringRef S) { 91 // A string table offset of zero is always the empty string. 92 if (S.empty()) 93 return 0; 94 auto I = StringTable.find(S); 95 assert(I != StringTable.end()); 96 return I->second; 97 } 98 99 void CodeViewContext::emitStringTable(MCObjectStreamer &OS) { 100 MCContext &Ctx = OS.getContext(); 101 MCSymbol *StringBegin = Ctx.createTempSymbol("strtab_begin", false), 102 *StringEnd = Ctx.createTempSymbol("strtab_end", false); 103 104 OS.EmitIntValue(unsigned(ModuleSubstreamKind::StringTable), 4); 105 OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4); 106 OS.EmitLabel(StringBegin); 107 108 // Put the string table data fragment here, if we haven't already put it 109 // somewhere else. If somebody wants two string tables in their .s file, one 110 // will just be empty. 111 if (!InsertedStrTabFragment) { 112 OS.insert(getStringTableFragment()); 113 InsertedStrTabFragment = true; 114 } 115 116 OS.EmitValueToAlignment(4, 0); 117 118 OS.EmitLabel(StringEnd); 119 } 120 121 void CodeViewContext::emitFileChecksums(MCObjectStreamer &OS) { 122 // Do nothing if there are no file checksums. Microsoft's linker rejects empty 123 // CodeView substreams. 124 if (Filenames.empty()) 125 return; 126 127 MCContext &Ctx = OS.getContext(); 128 MCSymbol *FileBegin = Ctx.createTempSymbol("filechecksums_begin", false), 129 *FileEnd = Ctx.createTempSymbol("filechecksums_end", false); 130 131 OS.EmitIntValue(unsigned(ModuleSubstreamKind::FileChecksums), 4); 132 OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4); 133 OS.EmitLabel(FileBegin); 134 135 // Emit an array of FileChecksum entries. We index into this table using the 136 // user-provided file number. Each entry is currently 8 bytes, as we don't 137 // emit checksums. 138 for (StringRef Filename : Filenames) { 139 OS.EmitIntValue(getStringTableOffset(Filename), 4); 140 // Zero the next two fields and align back to 4 bytes. This indicates that 141 // no checksum is present. 142 OS.EmitIntValue(0, 4); 143 } 144 145 OS.EmitLabel(FileEnd); 146 } 147 148 void CodeViewContext::emitLineTableForFunction(MCObjectStreamer &OS, 149 unsigned FuncId, 150 const MCSymbol *FuncBegin, 151 const MCSymbol *FuncEnd) { 152 MCContext &Ctx = OS.getContext(); 153 MCSymbol *LineBegin = Ctx.createTempSymbol("linetable_begin", false), 154 *LineEnd = Ctx.createTempSymbol("linetable_end", false); 155 156 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Lines), 4); 157 OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4); 158 OS.EmitLabel(LineBegin); 159 OS.EmitCOFFSecRel32(FuncBegin); 160 OS.EmitCOFFSectionIndex(FuncBegin); 161 162 // Actual line info. 163 std::vector<MCCVLineEntry> Locs = getFunctionLineEntries(FuncId); 164 bool HaveColumns = any_of(Locs, [](const MCCVLineEntry &LineEntry) { 165 return LineEntry.getColumn() != 0; 166 }); 167 OS.EmitIntValue(HaveColumns ? int(LineFlags::HaveColumns) : 0, 2); 168 OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 4); 169 170 for (auto I = Locs.begin(), E = Locs.end(); I != E;) { 171 // Emit a file segment for the run of locations that share a file id. 172 unsigned CurFileNum = I->getFileNum(); 173 auto FileSegEnd = 174 std::find_if(I, E, [CurFileNum](const MCCVLineEntry &Loc) { 175 return Loc.getFileNum() != CurFileNum; 176 }); 177 unsigned EntryCount = FileSegEnd - I; 178 OS.AddComment("Segment for file '" + Twine(Filenames[CurFileNum - 1]) + 179 "' begins"); 180 OS.EmitIntValue(8 * (CurFileNum - 1), 4); 181 OS.EmitIntValue(EntryCount, 4); 182 uint32_t SegmentSize = 12; 183 SegmentSize += 8 * EntryCount; 184 if (HaveColumns) 185 SegmentSize += 4 * EntryCount; 186 OS.EmitIntValue(SegmentSize, 4); 187 188 for (auto J = I; J != FileSegEnd; ++J) { 189 OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4); 190 unsigned LineData = J->getLine(); 191 if (J->isStmt()) 192 LineData |= LineInfo::StatementFlag; 193 OS.EmitIntValue(LineData, 4); 194 } 195 if (HaveColumns) { 196 for (auto J = I; J != FileSegEnd; ++J) { 197 OS.EmitIntValue(J->getColumn(), 2); 198 OS.EmitIntValue(0, 2); 199 } 200 } 201 I = FileSegEnd; 202 } 203 OS.EmitLabel(LineEnd); 204 } 205 206 static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) { 207 if (isUInt<7>(Data)) { 208 Buffer.push_back(Data); 209 return true; 210 } 211 212 if (isUInt<14>(Data)) { 213 Buffer.push_back((Data >> 8) | 0x80); 214 Buffer.push_back(Data & 0xff); 215 return true; 216 } 217 218 if (isUInt<29>(Data)) { 219 Buffer.push_back((Data >> 24) | 0xC0); 220 Buffer.push_back((Data >> 16) & 0xff); 221 Buffer.push_back((Data >> 8) & 0xff); 222 Buffer.push_back(Data & 0xff); 223 return true; 224 } 225 226 return false; 227 } 228 229 static bool compressAnnotation(BinaryAnnotationsOpCode Annotation, 230 SmallVectorImpl<char> &Buffer) { 231 return compressAnnotation(static_cast<uint32_t>(Annotation), Buffer); 232 } 233 234 static uint32_t encodeSignedNumber(uint32_t Data) { 235 if (Data >> 31) 236 return ((-Data) << 1) | 1; 237 return Data << 1; 238 } 239 240 void CodeViewContext::emitInlineLineTableForFunction( 241 MCObjectStreamer &OS, unsigned PrimaryFunctionId, unsigned SourceFileId, 242 unsigned SourceLineNum, const MCSymbol *FnStartSym, 243 const MCSymbol *FnEndSym, ArrayRef<unsigned> SecondaryFunctionIds) { 244 // Create and insert a fragment into the current section that will be encoded 245 // later. 246 new MCCVInlineLineTableFragment( 247 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym, 248 SecondaryFunctionIds, OS.getCurrentSectionOnly()); 249 } 250 251 void CodeViewContext::emitDefRange( 252 MCObjectStreamer &OS, 253 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 254 StringRef FixedSizePortion) { 255 // Create and insert a fragment into the current section that will be encoded 256 // later. 257 new MCCVDefRangeFragment(Ranges, FixedSizePortion, 258 OS.getCurrentSectionOnly()); 259 } 260 261 static unsigned computeLabelDiff(MCAsmLayout &Layout, const MCSymbol *Begin, 262 const MCSymbol *End) { 263 MCContext &Ctx = Layout.getAssembler().getContext(); 264 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 265 const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx), 266 *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx); 267 const MCExpr *AddrDelta = 268 MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx); 269 int64_t Result; 270 bool Success = AddrDelta->evaluateKnownAbsolute(Result, Layout); 271 assert(Success && "failed to evaluate label difference as absolute"); 272 (void)Success; 273 assert(Result >= 0 && "negative label difference requested"); 274 assert(Result < UINT_MAX && "label difference greater than 2GB"); 275 return unsigned(Result); 276 } 277 278 void CodeViewContext::encodeInlineLineTable(MCAsmLayout &Layout, 279 MCCVInlineLineTableFragment &Frag) { 280 size_t LocBegin; 281 size_t LocEnd; 282 std::tie(LocBegin, LocEnd) = getLineExtent(Frag.SiteFuncId); 283 for (unsigned SecondaryId : Frag.SecondaryFuncs) { 284 auto Extent = getLineExtent(SecondaryId); 285 LocBegin = std::min(LocBegin, Extent.first); 286 LocEnd = std::max(LocEnd, Extent.second); 287 } 288 if (LocBegin >= LocEnd) 289 return; 290 ArrayRef<MCCVLineEntry> Locs = getLinesForExtent(LocBegin, LocEnd); 291 if (Locs.empty()) 292 return; 293 294 SmallSet<unsigned, 8> InlinedFuncIds; 295 InlinedFuncIds.insert(Frag.SiteFuncId); 296 InlinedFuncIds.insert(Frag.SecondaryFuncs.begin(), Frag.SecondaryFuncs.end()); 297 298 // Make an artificial start location using the function start and the inlinee 299 // lines start location information. All deltas start relative to this 300 // location. 301 MCCVLineEntry StartLoc(Frag.getFnStartSym(), MCCVLoc(Locs.front())); 302 StartLoc.setFileNum(Frag.StartFileId); 303 StartLoc.setLine(Frag.StartLineNum); 304 const MCCVLineEntry *LastLoc = &StartLoc; 305 bool HaveOpenRange = false; 306 307 SmallVectorImpl<char> &Buffer = Frag.getContents(); 308 Buffer.clear(); // Clear old contents if we went through relaxation. 309 for (const MCCVLineEntry &Loc : Locs) { 310 if (!InlinedFuncIds.count(Loc.getFunctionId())) { 311 // We've hit a cv_loc not attributed to this inline call site. Use this 312 // label to end the PC range. 313 if (HaveOpenRange) { 314 unsigned Length = 315 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel()); 316 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer); 317 compressAnnotation(Length, Buffer); 318 } 319 HaveOpenRange = false; 320 continue; 321 } 322 323 // If we've already opened the function and we're at an indirectly inlined 324 // location, continue until the next directly inlined location. 325 bool DirectlyInlined = Loc.getFunctionId() == Frag.SiteFuncId; 326 if (!DirectlyInlined && HaveOpenRange) 327 continue; 328 HaveOpenRange = true; 329 330 if (Loc.getFileNum() != LastLoc->getFileNum()) { 331 // File ids are 1 based, and each file checksum table entry is 8 bytes 332 // long. See emitFileChecksums above. 333 unsigned FileOffset = 8 * (Loc.getFileNum() - 1); 334 compressAnnotation(BinaryAnnotationsOpCode::ChangeFile, Buffer); 335 compressAnnotation(FileOffset, Buffer); 336 } 337 338 int LineDelta = Loc.getLine() - LastLoc->getLine(); 339 if (LineDelta == 0) 340 continue; 341 342 unsigned EncodedLineDelta = encodeSignedNumber(LineDelta); 343 unsigned CodeDelta = 344 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel()); 345 if (CodeDelta == 0) { 346 compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer); 347 compressAnnotation(EncodedLineDelta, Buffer); 348 } else if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) { 349 // The ChangeCodeOffsetAndLineOffset combination opcode is used when the 350 // encoded line delta uses 3 or fewer set bits and the code offset fits 351 // in one nibble. 352 unsigned Operand = (EncodedLineDelta << 4) | CodeDelta; 353 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset, 354 Buffer); 355 compressAnnotation(Operand, Buffer); 356 } else { 357 // Otherwise use the separate line and code deltas. 358 compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer); 359 compressAnnotation(EncodedLineDelta, Buffer); 360 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffset, Buffer); 361 compressAnnotation(CodeDelta, Buffer); 362 } 363 364 LastLoc = &Loc; 365 } 366 367 assert(HaveOpenRange); 368 369 unsigned EndSymLength = 370 computeLabelDiff(Layout, LastLoc->getLabel(), Frag.getFnEndSym()); 371 unsigned LocAfterLength = ~0U; 372 ArrayRef<MCCVLineEntry> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1); 373 if (!LocAfter.empty()) { 374 // Only try to compute this difference if we're in the same section. 375 const MCCVLineEntry &Loc = LocAfter[0]; 376 if (&Loc.getLabel()->getSection(false) == 377 &LastLoc->getLabel()->getSection(false)) { 378 LocAfterLength = 379 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel()); 380 } 381 } 382 383 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer); 384 compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer); 385 } 386 387 void CodeViewContext::encodeDefRange(MCAsmLayout &Layout, 388 MCCVDefRangeFragment &Frag) { 389 MCContext &Ctx = Layout.getAssembler().getContext(); 390 SmallVectorImpl<char> &Contents = Frag.getContents(); 391 Contents.clear(); 392 SmallVectorImpl<MCFixup> &Fixups = Frag.getFixups(); 393 Fixups.clear(); 394 raw_svector_ostream OS(Contents); 395 396 // Write down each range where the variable is defined. 397 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Frag.getRanges()) { 398 unsigned RangeSize = computeLabelDiff(Layout, Range.first, Range.second); 399 unsigned Bias = 0; 400 // We must split the range into chunks of MaxDefRange, this is a fundamental 401 // limitation of the file format. 402 do { 403 uint16_t Chunk = std::min((uint32_t)MaxDefRange, RangeSize); 404 405 const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Range.first, Ctx); 406 const MCBinaryExpr *BE = 407 MCBinaryExpr::createAdd(SRE, MCConstantExpr::create(Bias, Ctx), Ctx); 408 MCValue Res; 409 BE->evaluateAsRelocatable(Res, &Layout, /*Fixup=*/nullptr); 410 411 // Each record begins with a 2-byte number indicating how large the record 412 // is. 413 StringRef FixedSizePortion = Frag.getFixedSizePortion(); 414 // Our record is a fixed sized prefix and a LocalVariableAddrRange that we 415 // are artificially constructing. 416 size_t RecordSize = 417 FixedSizePortion.size() + sizeof(LocalVariableAddrRange); 418 // Write out the recrod size. 419 support::endian::Writer<support::little>(OS).write<uint16_t>(RecordSize); 420 // Write out the fixed size prefix. 421 OS << FixedSizePortion; 422 // Make space for a fixup that will eventually have a section relative 423 // relocation pointing at the offset where the variable becomes live. 424 Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_4)); 425 Contents.resize(Contents.size() + 4); // Fixup for code start. 426 // Make space for a fixup that will record the section index for the code. 427 Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_2)); 428 Contents.resize(Contents.size() + 2); // Fixup for section index. 429 // Write down the range's extent. 430 support::endian::Writer<support::little>(OS).write<uint16_t>(Chunk); 431 432 // Move on to the next range. 433 Bias += Chunk; 434 RangeSize -= Chunk; 435 } while (RangeSize > 0); 436 } 437 } 438 439 // 440 // This is called when an instruction is assembled into the specified section 441 // and if there is information from the last .cv_loc directive that has yet to have 442 // a line entry made for it is made. 443 // 444 void MCCVLineEntry::Make(MCObjectStreamer *MCOS) { 445 if (!MCOS->getContext().getCVLocSeen()) 446 return; 447 448 // Create a symbol at in the current section for use in the line entry. 449 MCSymbol *LineSym = MCOS->getContext().createTempSymbol(); 450 // Set the value of the symbol to use for the MCCVLineEntry. 451 MCOS->EmitLabel(LineSym); 452 453 // Get the current .loc info saved in the context. 454 const MCCVLoc &CVLoc = MCOS->getContext().getCurrentCVLoc(); 455 456 // Create a (local) line entry with the symbol and the current .loc info. 457 MCCVLineEntry LineEntry(LineSym, CVLoc); 458 459 // clear CVLocSeen saying the current .loc info is now used. 460 MCOS->getContext().clearCVLocSeen(); 461 462 // Add the line entry to this section's entries. 463 MCOS->getContext().getCVContext().addLineEntry(LineEntry); 464 } 465