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