1 //===- CodeViewYAMLDebugSections.cpp - CodeView YAMLIO debug sections -----===//
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 // This file defines classes for handling the YAML representation of CodeView
11 // Debug Info.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ObjectYAML/CodeViewYAMLDebugSections.h"
16 
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/DebugInfo/CodeView/CodeViewError.h"
20 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
21 #include "llvm/DebugInfo/CodeView/DebugCrossExSubsection.h"
22 #include "llvm/DebugInfo/CodeView/DebugCrossImpSubsection.h"
23 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
24 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
25 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
26 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h"
28 #include "llvm/DebugInfo/CodeView/DebugSymbolRVASubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugSymbolsSubsection.h"
30 #include "llvm/DebugInfo/CodeView/EnumTables.h"
31 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
32 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
33 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
34 #include "llvm/ObjectYAML/CodeViewYAMLSymbols.h"
35 #include "llvm/Support/BinaryStreamWriter.h"
36 using namespace llvm;
37 using namespace llvm::codeview;
38 using namespace llvm::CodeViewYAML;
39 using namespace llvm::CodeViewYAML::detail;
40 using namespace llvm::yaml;
41 
42 LLVM_YAML_IS_SEQUENCE_VECTOR(SourceFileChecksumEntry)
43 LLVM_YAML_IS_SEQUENCE_VECTOR(SourceLineEntry)
44 LLVM_YAML_IS_SEQUENCE_VECTOR(SourceColumnEntry)
45 LLVM_YAML_IS_SEQUENCE_VECTOR(SourceLineBlock)
46 LLVM_YAML_IS_SEQUENCE_VECTOR(SourceLineInfo)
47 LLVM_YAML_IS_SEQUENCE_VECTOR(InlineeSite)
48 LLVM_YAML_IS_SEQUENCE_VECTOR(InlineeInfo)
49 LLVM_YAML_IS_SEQUENCE_VECTOR(CrossModuleExport)
50 LLVM_YAML_IS_SEQUENCE_VECTOR(YAMLCrossModuleImport)
51 LLVM_YAML_IS_SEQUENCE_VECTOR(StringRef)
52 LLVM_YAML_IS_SEQUENCE_VECTOR(YAMLFrameData)
53 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(uint32_t)
54 
55 LLVM_YAML_DECLARE_SCALAR_TRAITS(HexFormattedString, false)
56 LLVM_YAML_DECLARE_ENUM_TRAITS(DebugSubsectionKind)
57 LLVM_YAML_DECLARE_ENUM_TRAITS(FileChecksumKind)
58 LLVM_YAML_DECLARE_BITSET_TRAITS(LineFlags)
59 
60 LLVM_YAML_DECLARE_MAPPING_TRAITS(CrossModuleExport)
61 LLVM_YAML_DECLARE_MAPPING_TRAITS(YAMLFrameData)
62 LLVM_YAML_DECLARE_MAPPING_TRAITS(YAMLCrossModuleImport)
63 LLVM_YAML_DECLARE_MAPPING_TRAITS(CrossModuleImportItem)
64 LLVM_YAML_DECLARE_MAPPING_TRAITS(SourceLineEntry)
65 LLVM_YAML_DECLARE_MAPPING_TRAITS(SourceColumnEntry)
66 LLVM_YAML_DECLARE_MAPPING_TRAITS(SourceFileChecksumEntry)
67 LLVM_YAML_DECLARE_MAPPING_TRAITS(SourceLineBlock)
68 LLVM_YAML_DECLARE_MAPPING_TRAITS(InlineeSite)
69 
70 namespace llvm {
71 namespace CodeViewYAML {
72 namespace detail {
73 struct YAMLSubsectionBase {
74   explicit YAMLSubsectionBase(DebugSubsectionKind Kind) : Kind(Kind) {}
75   DebugSubsectionKind Kind;
76   virtual ~YAMLSubsectionBase() {}
77 
78   virtual void map(IO &IO) = 0;
79   virtual std::shared_ptr<DebugSubsection>
80   toCodeViewSubsection(BumpPtrAllocator &Allocator,
81                        const codeview::StringsAndChecksums &SC) const = 0;
82 };
83 }
84 }
85 }
86 
87 namespace {
88 struct YAMLChecksumsSubsection : public YAMLSubsectionBase {
89   YAMLChecksumsSubsection()
90       : YAMLSubsectionBase(DebugSubsectionKind::FileChecksums) {}
91 
92   void map(IO &IO) override;
93   std::shared_ptr<DebugSubsection>
94   toCodeViewSubsection(BumpPtrAllocator &Allocator,
95                        const codeview::StringsAndChecksums &SC) const override;
96   static Expected<std::shared_ptr<YAMLChecksumsSubsection>>
97   fromCodeViewSubsection(const DebugStringTableSubsectionRef &Strings,
98                          const DebugChecksumsSubsectionRef &FC);
99 
100   std::vector<SourceFileChecksumEntry> Checksums;
101 };
102 
103 struct YAMLLinesSubsection : public YAMLSubsectionBase {
104   YAMLLinesSubsection() : YAMLSubsectionBase(DebugSubsectionKind::Lines) {}
105 
106   void map(IO &IO) override;
107   std::shared_ptr<DebugSubsection>
108   toCodeViewSubsection(BumpPtrAllocator &Allocator,
109                        const codeview::StringsAndChecksums &SC) const override;
110   static Expected<std::shared_ptr<YAMLLinesSubsection>>
111   fromCodeViewSubsection(const DebugStringTableSubsectionRef &Strings,
112                          const DebugChecksumsSubsectionRef &Checksums,
113                          const DebugLinesSubsectionRef &Lines);
114 
115   SourceLineInfo Lines;
116 };
117 
118 struct YAMLInlineeLinesSubsection : public YAMLSubsectionBase {
119   YAMLInlineeLinesSubsection()
120       : YAMLSubsectionBase(DebugSubsectionKind::InlineeLines) {}
121 
122   void map(IO &IO) override;
123   std::shared_ptr<DebugSubsection>
124   toCodeViewSubsection(BumpPtrAllocator &Allocator,
125                        const codeview::StringsAndChecksums &SC) const override;
126   static Expected<std::shared_ptr<YAMLInlineeLinesSubsection>>
127   fromCodeViewSubsection(const DebugStringTableSubsectionRef &Strings,
128                          const DebugChecksumsSubsectionRef &Checksums,
129                          const DebugInlineeLinesSubsectionRef &Lines);
130 
131   InlineeInfo InlineeLines;
132 };
133 
134 struct YAMLCrossModuleExportsSubsection : public YAMLSubsectionBase {
135   YAMLCrossModuleExportsSubsection()
136       : YAMLSubsectionBase(DebugSubsectionKind::CrossScopeExports) {}
137 
138   void map(IO &IO) override;
139   std::shared_ptr<DebugSubsection>
140   toCodeViewSubsection(BumpPtrAllocator &Allocator,
141                        const codeview::StringsAndChecksums &SC) const override;
142   static Expected<std::shared_ptr<YAMLCrossModuleExportsSubsection>>
143   fromCodeViewSubsection(const DebugCrossModuleExportsSubsectionRef &Exports);
144 
145   std::vector<CrossModuleExport> Exports;
146 };
147 
148 struct YAMLCrossModuleImportsSubsection : public YAMLSubsectionBase {
149   YAMLCrossModuleImportsSubsection()
150       : YAMLSubsectionBase(DebugSubsectionKind::CrossScopeImports) {}
151 
152   void map(IO &IO) override;
153   std::shared_ptr<DebugSubsection>
154   toCodeViewSubsection(BumpPtrAllocator &Allocator,
155                        const codeview::StringsAndChecksums &SC) const override;
156   static Expected<std::shared_ptr<YAMLCrossModuleImportsSubsection>>
157   fromCodeViewSubsection(const DebugStringTableSubsectionRef &Strings,
158                          const DebugCrossModuleImportsSubsectionRef &Imports);
159 
160   std::vector<YAMLCrossModuleImport> Imports;
161 };
162 
163 struct YAMLSymbolsSubsection : public YAMLSubsectionBase {
164   YAMLSymbolsSubsection() : YAMLSubsectionBase(DebugSubsectionKind::Symbols) {}
165 
166   void map(IO &IO) override;
167   std::shared_ptr<DebugSubsection>
168   toCodeViewSubsection(BumpPtrAllocator &Allocator,
169                        const codeview::StringsAndChecksums &SC) const override;
170   static Expected<std::shared_ptr<YAMLSymbolsSubsection>>
171   fromCodeViewSubsection(const DebugSymbolsSubsectionRef &Symbols);
172 
173   std::vector<CodeViewYAML::SymbolRecord> Symbols;
174 };
175 
176 struct YAMLStringTableSubsection : public YAMLSubsectionBase {
177   YAMLStringTableSubsection()
178       : YAMLSubsectionBase(DebugSubsectionKind::StringTable) {}
179 
180   void map(IO &IO) override;
181   std::shared_ptr<DebugSubsection>
182   toCodeViewSubsection(BumpPtrAllocator &Allocator,
183                        const codeview::StringsAndChecksums &SC) const override;
184   static Expected<std::shared_ptr<YAMLStringTableSubsection>>
185   fromCodeViewSubsection(const DebugStringTableSubsectionRef &Strings);
186 
187   std::vector<StringRef> Strings;
188 };
189 
190 struct YAMLFrameDataSubsection : public YAMLSubsectionBase {
191   YAMLFrameDataSubsection()
192       : YAMLSubsectionBase(DebugSubsectionKind::FrameData) {}
193 
194   void map(IO &IO) override;
195   std::shared_ptr<DebugSubsection>
196   toCodeViewSubsection(BumpPtrAllocator &Allocator,
197                        const codeview::StringsAndChecksums &SC) const override;
198   static Expected<std::shared_ptr<YAMLFrameDataSubsection>>
199   fromCodeViewSubsection(const DebugStringTableSubsectionRef &Strings,
200                          const DebugFrameDataSubsectionRef &Frames);
201 
202   std::vector<YAMLFrameData> Frames;
203 };
204 
205 struct YAMLCoffSymbolRVASubsection : public YAMLSubsectionBase {
206   YAMLCoffSymbolRVASubsection()
207       : YAMLSubsectionBase(DebugSubsectionKind::CoffSymbolRVA) {}
208 
209   void map(IO &IO) override;
210   std::shared_ptr<DebugSubsection>
211   toCodeViewSubsection(BumpPtrAllocator &Allocator,
212                        const codeview::StringsAndChecksums &SC) const override;
213   static Expected<std::shared_ptr<YAMLCoffSymbolRVASubsection>>
214   fromCodeViewSubsection(const DebugSymbolRVASubsectionRef &RVAs);
215 
216   std::vector<uint32_t> RVAs;
217 };
218 }
219 
220 void ScalarBitSetTraits<LineFlags>::bitset(IO &io, LineFlags &Flags) {
221   io.bitSetCase(Flags, "HasColumnInfo", LF_HaveColumns);
222   io.enumFallback<Hex16>(Flags);
223 }
224 
225 void ScalarEnumerationTraits<FileChecksumKind>::enumeration(
226     IO &io, FileChecksumKind &Kind) {
227   io.enumCase(Kind, "None", FileChecksumKind::None);
228   io.enumCase(Kind, "MD5", FileChecksumKind::MD5);
229   io.enumCase(Kind, "SHA1", FileChecksumKind::SHA1);
230   io.enumCase(Kind, "SHA256", FileChecksumKind::SHA256);
231 }
232 
233 void ScalarTraits<HexFormattedString>::output(const HexFormattedString &Value,
234                                               void *ctx, raw_ostream &Out) {
235   StringRef Bytes(reinterpret_cast<const char *>(Value.Bytes.data()),
236                   Value.Bytes.size());
237   Out << toHex(Bytes);
238 }
239 
240 StringRef ScalarTraits<HexFormattedString>::input(StringRef Scalar, void *ctxt,
241                                                   HexFormattedString &Value) {
242   std::string H = fromHex(Scalar);
243   Value.Bytes.assign(H.begin(), H.end());
244   return StringRef();
245 }
246 
247 void MappingTraits<SourceLineEntry>::mapping(IO &IO, SourceLineEntry &Obj) {
248   IO.mapRequired("Offset", Obj.Offset);
249   IO.mapRequired("LineStart", Obj.LineStart);
250   IO.mapRequired("IsStatement", Obj.IsStatement);
251   IO.mapRequired("EndDelta", Obj.EndDelta);
252 }
253 
254 void MappingTraits<SourceColumnEntry>::mapping(IO &IO, SourceColumnEntry &Obj) {
255   IO.mapRequired("StartColumn", Obj.StartColumn);
256   IO.mapRequired("EndColumn", Obj.EndColumn);
257 }
258 
259 void MappingTraits<SourceLineBlock>::mapping(IO &IO, SourceLineBlock &Obj) {
260   IO.mapRequired("FileName", Obj.FileName);
261   IO.mapRequired("Lines", Obj.Lines);
262   IO.mapRequired("Columns", Obj.Columns);
263 }
264 
265 void MappingTraits<CrossModuleExport>::mapping(IO &IO, CrossModuleExport &Obj) {
266   IO.mapRequired("LocalId", Obj.Local);
267   IO.mapRequired("GlobalId", Obj.Global);
268 }
269 
270 void MappingTraits<YAMLCrossModuleImport>::mapping(IO &IO,
271                                                    YAMLCrossModuleImport &Obj) {
272   IO.mapRequired("Module", Obj.ModuleName);
273   IO.mapRequired("Imports", Obj.ImportIds);
274 }
275 
276 void MappingTraits<SourceFileChecksumEntry>::mapping(
277     IO &IO, SourceFileChecksumEntry &Obj) {
278   IO.mapRequired("FileName", Obj.FileName);
279   IO.mapRequired("Kind", Obj.Kind);
280   IO.mapRequired("Checksum", Obj.ChecksumBytes);
281 }
282 
283 void MappingTraits<InlineeSite>::mapping(IO &IO, InlineeSite &Obj) {
284   IO.mapRequired("FileName", Obj.FileName);
285   IO.mapRequired("LineNum", Obj.SourceLineNum);
286   IO.mapRequired("Inlinee", Obj.Inlinee);
287   IO.mapOptional("ExtraFiles", Obj.ExtraFiles);
288 }
289 
290 void MappingTraits<YAMLFrameData>::mapping(IO &IO, YAMLFrameData &Obj) {
291   IO.mapRequired("CodeSize", Obj.CodeSize);
292   IO.mapRequired("FrameFunc", Obj.FrameFunc);
293   IO.mapRequired("LocalSize", Obj.LocalSize);
294   IO.mapOptional("MaxStackSize", Obj.MaxStackSize);
295   IO.mapOptional("ParamsSize", Obj.ParamsSize);
296   IO.mapOptional("PrologSize", Obj.PrologSize);
297   IO.mapOptional("RvaStart", Obj.RvaStart);
298   IO.mapOptional("SavedRegsSize", Obj.SavedRegsSize);
299 }
300 
301 void YAMLChecksumsSubsection::map(IO &IO) {
302   IO.mapTag("!FileChecksums", true);
303   IO.mapRequired("Checksums", Checksums);
304 }
305 
306 void YAMLLinesSubsection::map(IO &IO) {
307   IO.mapTag("!Lines", true);
308   IO.mapRequired("CodeSize", Lines.CodeSize);
309 
310   IO.mapRequired("Flags", Lines.Flags);
311   IO.mapRequired("RelocOffset", Lines.RelocOffset);
312   IO.mapRequired("RelocSegment", Lines.RelocSegment);
313   IO.mapRequired("Blocks", Lines.Blocks);
314 }
315 
316 void YAMLInlineeLinesSubsection::map(IO &IO) {
317   IO.mapTag("!InlineeLines", true);
318   IO.mapRequired("HasExtraFiles", InlineeLines.HasExtraFiles);
319   IO.mapRequired("Sites", InlineeLines.Sites);
320 }
321 
322 void YAMLCrossModuleExportsSubsection::map(IO &IO) {
323   IO.mapTag("!CrossModuleExports", true);
324   IO.mapOptional("Exports", Exports);
325 }
326 
327 void YAMLCrossModuleImportsSubsection::map(IO &IO) {
328   IO.mapTag("!CrossModuleImports", true);
329   IO.mapOptional("Imports", Imports);
330 }
331 
332 void YAMLSymbolsSubsection::map(IO &IO) {
333   IO.mapTag("!Symbols", true);
334   IO.mapRequired("Records", Symbols);
335 }
336 
337 void YAMLStringTableSubsection::map(IO &IO) {
338   IO.mapTag("!StringTable", true);
339   IO.mapRequired("Strings", Strings);
340 }
341 
342 void YAMLFrameDataSubsection::map(IO &IO) {
343   IO.mapTag("!FrameData", true);
344   IO.mapRequired("Frames", Frames);
345 }
346 
347 void YAMLCoffSymbolRVASubsection::map(IO &IO) {
348   IO.mapTag("!COFFSymbolRVAs", true);
349   IO.mapRequired("RVAs", RVAs);
350 }
351 
352 void MappingTraits<YAMLDebugSubsection>::mapping(
353     IO &IO, YAMLDebugSubsection &Subsection) {
354   if (!IO.outputting()) {
355     if (IO.mapTag("!FileChecksums")) {
356       auto SS = std::make_shared<YAMLChecksumsSubsection>();
357       Subsection.Subsection = SS;
358     } else if (IO.mapTag("!Lines")) {
359       Subsection.Subsection = std::make_shared<YAMLLinesSubsection>();
360     } else if (IO.mapTag("!InlineeLines")) {
361       Subsection.Subsection = std::make_shared<YAMLInlineeLinesSubsection>();
362     } else if (IO.mapTag("!CrossModuleExports")) {
363       Subsection.Subsection =
364           std::make_shared<YAMLCrossModuleExportsSubsection>();
365     } else if (IO.mapTag("!CrossModuleImports")) {
366       Subsection.Subsection =
367           std::make_shared<YAMLCrossModuleImportsSubsection>();
368     } else if (IO.mapTag("!Symbols")) {
369       Subsection.Subsection = std::make_shared<YAMLSymbolsSubsection>();
370     } else if (IO.mapTag("!StringTable")) {
371       Subsection.Subsection = std::make_shared<YAMLStringTableSubsection>();
372     } else if (IO.mapTag("!FrameData")) {
373       Subsection.Subsection = std::make_shared<YAMLFrameDataSubsection>();
374     } else if (IO.mapTag("!COFFSymbolRVAs")) {
375       Subsection.Subsection = std::make_shared<YAMLCoffSymbolRVASubsection>();
376     } else {
377       llvm_unreachable("Unexpected subsection tag!");
378     }
379   }
380   Subsection.Subsection->map(IO);
381 }
382 
383 std::shared_ptr<DebugSubsection> YAMLChecksumsSubsection::toCodeViewSubsection(
384     BumpPtrAllocator &Allocator,
385     const codeview::StringsAndChecksums &SC) const {
386   assert(SC.hasStrings());
387   auto Result = std::make_shared<DebugChecksumsSubsection>(*SC.strings());
388   for (const auto &CS : Checksums) {
389     Result->addChecksum(CS.FileName, CS.Kind, CS.ChecksumBytes.Bytes);
390   }
391   return Result;
392 }
393 
394 std::shared_ptr<DebugSubsection> YAMLLinesSubsection::toCodeViewSubsection(
395     BumpPtrAllocator &Allocator,
396     const codeview::StringsAndChecksums &SC) const {
397   assert(SC.hasStrings() && SC.hasChecksums());
398   auto Result =
399       std::make_shared<DebugLinesSubsection>(*SC.checksums(), *SC.strings());
400   Result->setCodeSize(Lines.CodeSize);
401   Result->setRelocationAddress(Lines.RelocSegment, Lines.RelocOffset);
402   Result->setFlags(Lines.Flags);
403   for (const auto &LC : Lines.Blocks) {
404     Result->createBlock(LC.FileName);
405     if (Result->hasColumnInfo()) {
406       for (const auto &Item : zip(LC.Lines, LC.Columns)) {
407         auto &L = std::get<0>(Item);
408         auto &C = std::get<1>(Item);
409         uint32_t LE = L.LineStart + L.EndDelta;
410         Result->addLineAndColumnInfo(L.Offset,
411                                      LineInfo(L.LineStart, LE, L.IsStatement),
412                                      C.StartColumn, C.EndColumn);
413       }
414     } else {
415       for (const auto &L : LC.Lines) {
416         uint32_t LE = L.LineStart + L.EndDelta;
417         Result->addLineInfo(L.Offset, LineInfo(L.LineStart, LE, L.IsStatement));
418       }
419     }
420   }
421   return Result;
422 }
423 
424 std::shared_ptr<DebugSubsection>
425 YAMLInlineeLinesSubsection::toCodeViewSubsection(
426     BumpPtrAllocator &Allocator,
427     const codeview::StringsAndChecksums &SC) const {
428   assert(SC.hasChecksums());
429   auto Result = std::make_shared<DebugInlineeLinesSubsection>(
430       *SC.checksums(), InlineeLines.HasExtraFiles);
431 
432   for (const auto &Site : InlineeLines.Sites) {
433     Result->addInlineSite(TypeIndex(Site.Inlinee), Site.FileName,
434                           Site.SourceLineNum);
435     if (!InlineeLines.HasExtraFiles)
436       continue;
437 
438     for (auto EF : Site.ExtraFiles) {
439       Result->addExtraFile(EF);
440     }
441   }
442   return Result;
443 }
444 
445 std::shared_ptr<DebugSubsection>
446 YAMLCrossModuleExportsSubsection::toCodeViewSubsection(
447     BumpPtrAllocator &Allocator,
448     const codeview::StringsAndChecksums &SC) const {
449   auto Result = std::make_shared<DebugCrossModuleExportsSubsection>();
450   for (const auto &M : Exports)
451     Result->addMapping(M.Local, M.Global);
452   return Result;
453 }
454 
455 std::shared_ptr<DebugSubsection>
456 YAMLCrossModuleImportsSubsection::toCodeViewSubsection(
457     BumpPtrAllocator &Allocator,
458     const codeview::StringsAndChecksums &SC) const {
459   assert(SC.hasStrings());
460 
461   auto Result =
462       std::make_shared<DebugCrossModuleImportsSubsection>(*SC.strings());
463   for (const auto &M : Imports) {
464     for (const auto Id : M.ImportIds)
465       Result->addImport(M.ModuleName, Id);
466   }
467   return Result;
468 }
469 
470 std::shared_ptr<DebugSubsection> YAMLSymbolsSubsection::toCodeViewSubsection(
471     BumpPtrAllocator &Allocator,
472     const codeview::StringsAndChecksums &SC) const {
473   auto Result = std::make_shared<DebugSymbolsSubsection>();
474   for (const auto &Sym : Symbols)
475     Result->addSymbol(
476         Sym.toCodeViewSymbol(Allocator, CodeViewContainer::ObjectFile));
477   return Result;
478 }
479 
480 std::shared_ptr<DebugSubsection>
481 YAMLStringTableSubsection::toCodeViewSubsection(
482     BumpPtrAllocator &Allocator,
483     const codeview::StringsAndChecksums &SC) const {
484   auto Result = std::make_shared<DebugStringTableSubsection>();
485   for (const auto &Str : this->Strings)
486     Result->insert(Str);
487   return Result;
488 }
489 
490 std::shared_ptr<DebugSubsection> YAMLFrameDataSubsection::toCodeViewSubsection(
491     BumpPtrAllocator &Allocator,
492     const codeview::StringsAndChecksums &SC) const {
493   assert(SC.hasStrings());
494 
495   auto Result = std::make_shared<DebugFrameDataSubsection>();
496   for (const auto &YF : Frames) {
497     codeview::FrameData F;
498     F.CodeSize = YF.CodeSize;
499     F.Flags = YF.Flags;
500     F.LocalSize = YF.LocalSize;
501     F.MaxStackSize = YF.MaxStackSize;
502     F.ParamsSize = YF.ParamsSize;
503     F.PrologSize = YF.PrologSize;
504     F.RvaStart = YF.RvaStart;
505     F.SavedRegsSize = YF.SavedRegsSize;
506     F.FrameFunc = SC.strings()->insert(YF.FrameFunc);
507     Result->addFrameData(F);
508   }
509   return Result;
510 }
511 
512 std::shared_ptr<DebugSubsection>
513 YAMLCoffSymbolRVASubsection::toCodeViewSubsection(
514     BumpPtrAllocator &Allocator,
515     const codeview::StringsAndChecksums &SC) const {
516   auto Result = std::make_shared<DebugSymbolRVASubsection>();
517   for (const auto &RVA : RVAs)
518     Result->addRVA(RVA);
519   return Result;
520 }
521 
522 static Expected<SourceFileChecksumEntry>
523 convertOneChecksum(const DebugStringTableSubsectionRef &Strings,
524                    const FileChecksumEntry &CS) {
525   auto ExpectedString = Strings.getString(CS.FileNameOffset);
526   if (!ExpectedString)
527     return ExpectedString.takeError();
528 
529   SourceFileChecksumEntry Result;
530   Result.ChecksumBytes.Bytes = CS.Checksum;
531   Result.Kind = CS.Kind;
532   Result.FileName = *ExpectedString;
533   return Result;
534 }
535 
536 static Expected<StringRef>
537 getFileName(const DebugStringTableSubsectionRef &Strings,
538             const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID) {
539   auto Iter = Checksums.getArray().at(FileID);
540   if (Iter == Checksums.getArray().end())
541     return make_error<CodeViewError>(cv_error_code::no_records);
542   uint32_t Offset = Iter->FileNameOffset;
543   return Strings.getString(Offset);
544 }
545 
546 Expected<std::shared_ptr<YAMLChecksumsSubsection>>
547 YAMLChecksumsSubsection::fromCodeViewSubsection(
548     const DebugStringTableSubsectionRef &Strings,
549     const DebugChecksumsSubsectionRef &FC) {
550   auto Result = std::make_shared<YAMLChecksumsSubsection>();
551 
552   for (const auto &CS : FC) {
553     auto ConvertedCS = convertOneChecksum(Strings, CS);
554     if (!ConvertedCS)
555       return ConvertedCS.takeError();
556     Result->Checksums.push_back(*ConvertedCS);
557   }
558   return Result;
559 }
560 
561 Expected<std::shared_ptr<YAMLLinesSubsection>>
562 YAMLLinesSubsection::fromCodeViewSubsection(
563     const DebugStringTableSubsectionRef &Strings,
564     const DebugChecksumsSubsectionRef &Checksums,
565     const DebugLinesSubsectionRef &Lines) {
566   auto Result = std::make_shared<YAMLLinesSubsection>();
567   Result->Lines.CodeSize = Lines.header()->CodeSize;
568   Result->Lines.RelocOffset = Lines.header()->RelocOffset;
569   Result->Lines.RelocSegment = Lines.header()->RelocSegment;
570   Result->Lines.Flags = static_cast<LineFlags>(uint16_t(Lines.header()->Flags));
571   for (const auto &L : Lines) {
572     SourceLineBlock Block;
573     auto EF = getFileName(Strings, Checksums, L.NameIndex);
574     if (!EF)
575       return EF.takeError();
576     Block.FileName = *EF;
577     if (Lines.hasColumnInfo()) {
578       for (const auto &C : L.Columns) {
579         SourceColumnEntry SCE;
580         SCE.EndColumn = C.EndColumn;
581         SCE.StartColumn = C.StartColumn;
582         Block.Columns.push_back(SCE);
583       }
584     }
585     for (const auto &LN : L.LineNumbers) {
586       SourceLineEntry SLE;
587       LineInfo LI(LN.Flags);
588       SLE.Offset = LN.Offset;
589       SLE.LineStart = LI.getStartLine();
590       SLE.EndDelta = LI.getLineDelta();
591       SLE.IsStatement = LI.isStatement();
592       Block.Lines.push_back(SLE);
593     }
594     Result->Lines.Blocks.push_back(Block);
595   }
596   return Result;
597 }
598 
599 Expected<std::shared_ptr<YAMLInlineeLinesSubsection>>
600 YAMLInlineeLinesSubsection::fromCodeViewSubsection(
601     const DebugStringTableSubsectionRef &Strings,
602     const DebugChecksumsSubsectionRef &Checksums,
603     const DebugInlineeLinesSubsectionRef &Lines) {
604   auto Result = std::make_shared<YAMLInlineeLinesSubsection>();
605 
606   Result->InlineeLines.HasExtraFiles = Lines.hasExtraFiles();
607   for (const auto &IL : Lines) {
608     InlineeSite Site;
609     auto ExpF = getFileName(Strings, Checksums, IL.Header->FileID);
610     if (!ExpF)
611       return ExpF.takeError();
612     Site.FileName = *ExpF;
613     Site.Inlinee = IL.Header->Inlinee.getIndex();
614     Site.SourceLineNum = IL.Header->SourceLineNum;
615     if (Lines.hasExtraFiles()) {
616       for (const auto EF : IL.ExtraFiles) {
617         auto ExpF2 = getFileName(Strings, Checksums, EF);
618         if (!ExpF2)
619           return ExpF2.takeError();
620         Site.ExtraFiles.push_back(*ExpF2);
621       }
622     }
623     Result->InlineeLines.Sites.push_back(Site);
624   }
625   return Result;
626 }
627 
628 Expected<std::shared_ptr<YAMLCrossModuleExportsSubsection>>
629 YAMLCrossModuleExportsSubsection::fromCodeViewSubsection(
630     const DebugCrossModuleExportsSubsectionRef &Exports) {
631   auto Result = std::make_shared<YAMLCrossModuleExportsSubsection>();
632   Result->Exports.assign(Exports.begin(), Exports.end());
633   return Result;
634 }
635 
636 Expected<std::shared_ptr<YAMLCrossModuleImportsSubsection>>
637 YAMLCrossModuleImportsSubsection::fromCodeViewSubsection(
638     const DebugStringTableSubsectionRef &Strings,
639     const DebugCrossModuleImportsSubsectionRef &Imports) {
640   auto Result = std::make_shared<YAMLCrossModuleImportsSubsection>();
641   for (const auto &CMI : Imports) {
642     YAMLCrossModuleImport YCMI;
643     auto ExpectedStr = Strings.getString(CMI.Header->ModuleNameOffset);
644     if (!ExpectedStr)
645       return ExpectedStr.takeError();
646     YCMI.ModuleName = *ExpectedStr;
647     YCMI.ImportIds.assign(CMI.Imports.begin(), CMI.Imports.end());
648     Result->Imports.push_back(YCMI);
649   }
650   return Result;
651 }
652 
653 Expected<std::shared_ptr<YAMLSymbolsSubsection>>
654 YAMLSymbolsSubsection::fromCodeViewSubsection(
655     const DebugSymbolsSubsectionRef &Symbols) {
656   auto Result = std::make_shared<YAMLSymbolsSubsection>();
657   for (const auto &Sym : Symbols) {
658     auto S = CodeViewYAML::SymbolRecord::fromCodeViewSymbol(Sym);
659     if (!S)
660       return joinErrors(make_error<CodeViewError>(
661                             cv_error_code::corrupt_record,
662                             "Invalid CodeView Symbol Record in SymbolRecord "
663                             "subsection of .debug$S while converting to YAML!"),
664                         S.takeError());
665 
666     Result->Symbols.push_back(*S);
667   }
668   return Result;
669 }
670 
671 Expected<std::shared_ptr<YAMLStringTableSubsection>>
672 YAMLStringTableSubsection::fromCodeViewSubsection(
673     const DebugStringTableSubsectionRef &Strings) {
674   auto Result = std::make_shared<YAMLStringTableSubsection>();
675   BinaryStreamReader Reader(Strings.getBuffer());
676   StringRef S;
677   // First item is a single null string, skip it.
678   if (auto EC = Reader.readCString(S))
679     return std::move(EC);
680   assert(S.empty());
681   while (Reader.bytesRemaining() > 0) {
682     if (auto EC = Reader.readCString(S))
683       return std::move(EC);
684     Result->Strings.push_back(S);
685   }
686   return Result;
687 }
688 
689 Expected<std::shared_ptr<YAMLFrameDataSubsection>>
690 YAMLFrameDataSubsection::fromCodeViewSubsection(
691     const DebugStringTableSubsectionRef &Strings,
692     const DebugFrameDataSubsectionRef &Frames) {
693   auto Result = std::make_shared<YAMLFrameDataSubsection>();
694   for (const auto &F : Frames) {
695     YAMLFrameData YF;
696     YF.CodeSize = F.CodeSize;
697     YF.Flags = F.Flags;
698     YF.LocalSize = F.LocalSize;
699     YF.MaxStackSize = F.MaxStackSize;
700     YF.ParamsSize = F.ParamsSize;
701     YF.PrologSize = F.PrologSize;
702     YF.RvaStart = F.RvaStart;
703     YF.SavedRegsSize = F.SavedRegsSize;
704 
705     auto ES = Strings.getString(F.FrameFunc);
706     if (!ES)
707       return joinErrors(
708           make_error<CodeViewError>(
709               cv_error_code::no_records,
710               "Could not find string for string id while mapping FrameData!"),
711           ES.takeError());
712     YF.FrameFunc = *ES;
713     Result->Frames.push_back(YF);
714   }
715   return Result;
716 }
717 
718 Expected<std::shared_ptr<YAMLCoffSymbolRVASubsection>>
719 YAMLCoffSymbolRVASubsection::fromCodeViewSubsection(
720     const DebugSymbolRVASubsectionRef &Section) {
721   auto Result = std::make_shared<YAMLCoffSymbolRVASubsection>();
722   for (const auto &RVA : Section) {
723     Result->RVAs.push_back(RVA);
724   }
725   return Result;
726 }
727 
728 Expected<std::vector<std::shared_ptr<DebugSubsection>>>
729 llvm::CodeViewYAML::toCodeViewSubsectionList(
730     BumpPtrAllocator &Allocator, ArrayRef<YAMLDebugSubsection> Subsections,
731     const codeview::StringsAndChecksums &SC) {
732   std::vector<std::shared_ptr<DebugSubsection>> Result;
733   if (Subsections.empty())
734     return std::move(Result);
735 
736   for (const auto &SS : Subsections) {
737     std::shared_ptr<DebugSubsection> CVS;
738     CVS = SS.Subsection->toCodeViewSubsection(Allocator, SC);
739     assert(CVS != nullptr);
740     Result.push_back(std::move(CVS));
741   }
742   return std::move(Result);
743 }
744 
745 namespace {
746 struct SubsectionConversionVisitor : public DebugSubsectionVisitor {
747   SubsectionConversionVisitor() {}
748 
749   Error visitUnknown(DebugUnknownSubsectionRef &Unknown) override;
750   Error visitLines(DebugLinesSubsectionRef &Lines,
751                    const StringsAndChecksumsRef &State) override;
752   Error visitFileChecksums(DebugChecksumsSubsectionRef &Checksums,
753                            const StringsAndChecksumsRef &State) override;
754   Error visitInlineeLines(DebugInlineeLinesSubsectionRef &Inlinees,
755                           const StringsAndChecksumsRef &State) override;
756   Error visitCrossModuleExports(DebugCrossModuleExportsSubsectionRef &Checksums,
757                                 const StringsAndChecksumsRef &State) override;
758   Error visitCrossModuleImports(DebugCrossModuleImportsSubsectionRef &Inlinees,
759                                 const StringsAndChecksumsRef &State) override;
760   Error visitStringTable(DebugStringTableSubsectionRef &ST,
761                          const StringsAndChecksumsRef &State) override;
762   Error visitSymbols(DebugSymbolsSubsectionRef &Symbols,
763                      const StringsAndChecksumsRef &State) override;
764   Error visitFrameData(DebugFrameDataSubsectionRef &Symbols,
765                        const StringsAndChecksumsRef &State) override;
766   Error visitCOFFSymbolRVAs(DebugSymbolRVASubsectionRef &Symbols,
767                             const StringsAndChecksumsRef &State) override;
768 
769   YAMLDebugSubsection Subsection;
770 };
771 
772 Error SubsectionConversionVisitor::visitUnknown(
773     DebugUnknownSubsectionRef &Unknown) {
774   return make_error<CodeViewError>(cv_error_code::operation_unsupported);
775 }
776 
777 Error SubsectionConversionVisitor::visitLines(
778     DebugLinesSubsectionRef &Lines, const StringsAndChecksumsRef &State) {
779   auto Result = YAMLLinesSubsection::fromCodeViewSubsection(
780       State.strings(), State.checksums(), Lines);
781   if (!Result)
782     return Result.takeError();
783   Subsection.Subsection = *Result;
784   return Error::success();
785 }
786 
787 Error SubsectionConversionVisitor::visitFileChecksums(
788     DebugChecksumsSubsectionRef &Checksums,
789     const StringsAndChecksumsRef &State) {
790   auto Result = YAMLChecksumsSubsection::fromCodeViewSubsection(State.strings(),
791                                                                 Checksums);
792   if (!Result)
793     return Result.takeError();
794   Subsection.Subsection = *Result;
795   return Error::success();
796 }
797 
798 Error SubsectionConversionVisitor::visitInlineeLines(
799     DebugInlineeLinesSubsectionRef &Inlinees,
800     const StringsAndChecksumsRef &State) {
801   auto Result = YAMLInlineeLinesSubsection::fromCodeViewSubsection(
802       State.strings(), State.checksums(), Inlinees);
803   if (!Result)
804     return Result.takeError();
805   Subsection.Subsection = *Result;
806   return Error::success();
807 }
808 
809 Error SubsectionConversionVisitor::visitCrossModuleExports(
810     DebugCrossModuleExportsSubsectionRef &Exports,
811     const StringsAndChecksumsRef &State) {
812   auto Result =
813       YAMLCrossModuleExportsSubsection::fromCodeViewSubsection(Exports);
814   if (!Result)
815     return Result.takeError();
816   Subsection.Subsection = *Result;
817   return Error::success();
818 }
819 
820 Error SubsectionConversionVisitor::visitCrossModuleImports(
821     DebugCrossModuleImportsSubsectionRef &Imports,
822     const StringsAndChecksumsRef &State) {
823   auto Result = YAMLCrossModuleImportsSubsection::fromCodeViewSubsection(
824       State.strings(), Imports);
825   if (!Result)
826     return Result.takeError();
827   Subsection.Subsection = *Result;
828   return Error::success();
829 }
830 
831 Error SubsectionConversionVisitor::visitStringTable(
832     DebugStringTableSubsectionRef &Strings,
833     const StringsAndChecksumsRef &State) {
834   auto Result = YAMLStringTableSubsection::fromCodeViewSubsection(Strings);
835   if (!Result)
836     return Result.takeError();
837   Subsection.Subsection = *Result;
838   return Error::success();
839 }
840 
841 Error SubsectionConversionVisitor::visitSymbols(
842     DebugSymbolsSubsectionRef &Symbols, const StringsAndChecksumsRef &State) {
843   auto Result = YAMLSymbolsSubsection::fromCodeViewSubsection(Symbols);
844   if (!Result)
845     return Result.takeError();
846   Subsection.Subsection = *Result;
847   return Error::success();
848 }
849 
850 Error SubsectionConversionVisitor::visitFrameData(
851     DebugFrameDataSubsectionRef &Frames, const StringsAndChecksumsRef &State) {
852   auto Result =
853       YAMLFrameDataSubsection::fromCodeViewSubsection(State.strings(), Frames);
854   if (!Result)
855     return Result.takeError();
856   Subsection.Subsection = *Result;
857   return Error::success();
858 }
859 
860 Error SubsectionConversionVisitor::visitCOFFSymbolRVAs(
861     DebugSymbolRVASubsectionRef &RVAs, const StringsAndChecksumsRef &State) {
862   auto Result = YAMLCoffSymbolRVASubsection::fromCodeViewSubsection(RVAs);
863   if (!Result)
864     return Result.takeError();
865   Subsection.Subsection = *Result;
866   return Error::success();
867 }
868 }
869 
870 Expected<YAMLDebugSubsection>
871 YAMLDebugSubsection::fromCodeViewSubection(const StringsAndChecksumsRef &SC,
872                                            const DebugSubsectionRecord &SS) {
873   SubsectionConversionVisitor V;
874   if (auto EC = visitDebugSubsection(SS, V, SC))
875     return std::move(EC);
876 
877   return V.Subsection;
878 }
879 
880 std::vector<YAMLDebugSubsection>
881 llvm::CodeViewYAML::fromDebugS(ArrayRef<uint8_t> Data,
882                                const StringsAndChecksumsRef &SC) {
883   BinaryStreamReader Reader(Data, support::little);
884   uint32_t Magic;
885 
886   ExitOnError Err("Invalid .debug$S section!");
887   Err(Reader.readInteger(Magic));
888   assert(Magic == COFF::DEBUG_SECTION_MAGIC && "Invalid .debug$S section!");
889 
890   DebugSubsectionArray Subsections;
891   Err(Reader.readArray(Subsections, Reader.bytesRemaining()));
892 
893   std::vector<YAMLDebugSubsection> Result;
894 
895   for (const auto &SS : Subsections) {
896     auto YamlSS = Err(YAMLDebugSubsection::fromCodeViewSubection(SC, SS));
897     Result.push_back(YamlSS);
898   }
899   return Result;
900 }
901 
902 void llvm::CodeViewYAML::initializeStringsAndChecksums(
903     ArrayRef<YAMLDebugSubsection> Sections, codeview::StringsAndChecksums &SC) {
904   // String Table and Checksums subsections don't use the allocator.
905   BumpPtrAllocator Allocator;
906 
907   // It's possible for checksums and strings to even appear in different debug$S
908   // sections, so we have to make this a stateful function that can build up
909   // the strings and checksums field over multiple iterations.
910 
911   // File Checksums require the string table, but may become before it, so we
912   // have to scan for strings first, then scan for checksums again from the
913   // beginning.
914   if (!SC.hasStrings()) {
915     for (const auto &SS : Sections) {
916       if (SS.Subsection->Kind != DebugSubsectionKind::StringTable)
917         continue;
918 
919       auto Result = SS.Subsection->toCodeViewSubsection(Allocator, SC);
920       SC.setStrings(
921           std::static_pointer_cast<DebugStringTableSubsection>(Result));
922       break;
923     }
924   }
925 
926   if (SC.hasStrings() && !SC.hasChecksums()) {
927     for (const auto &SS : Sections) {
928       if (SS.Subsection->Kind != DebugSubsectionKind::FileChecksums)
929         continue;
930 
931       auto Result = SS.Subsection->toCodeViewSubsection(Allocator, SC);
932       SC.setChecksums(
933           std::static_pointer_cast<DebugChecksumsSubsection>(Result));
934       break;
935     }
936   }
937 }
938