1 //===------ utils/wasm2yaml.cpp - obj2yaml conversion tool ------*- C++ -*-===//
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 "obj2yaml.h"
10 #include "llvm/Object/COFF.h"
11 #include "llvm/ObjectYAML/WasmYAML.h"
12 #include "llvm/Support/ErrorHandling.h"
13 #include "llvm/Support/YAMLTraits.h"
14 
15 using namespace llvm;
16 using object::WasmSection;
17 
18 namespace {
19 
20 class WasmDumper {
21   const object::WasmObjectFile &Obj;
22 
23 public:
24   WasmDumper(const object::WasmObjectFile &O) : Obj(O) {}
25 
26   ErrorOr<WasmYAML::Object *> dump();
27 
28   std::unique_ptr<WasmYAML::CustomSection>
29   dumpCustomSection(const WasmSection &WasmSec);
30 };
31 
32 } // namespace
33 
34 static WasmYAML::Limits makeLimits(const wasm::WasmLimits &Limits) {
35   WasmYAML::Limits L;
36   L.Flags = Limits.Flags;
37   L.Initial = Limits.Initial;
38   L.Maximum = Limits.Maximum;
39   return L;
40 }
41 
42 static WasmYAML::Table makeTable(uint32_t Index,
43                                  const wasm::WasmTableType &Type) {
44   WasmYAML::Table T;
45   T.Index = Index;
46   T.ElemType = Type.ElemType;
47   T.TableLimits = makeLimits(Type.Limits);
48   return T;
49 }
50 
51 std::unique_ptr<WasmYAML::CustomSection>
52 WasmDumper::dumpCustomSection(const WasmSection &WasmSec) {
53   std::unique_ptr<WasmYAML::CustomSection> CustomSec;
54   if (WasmSec.Name == "dylink") {
55     std::unique_ptr<WasmYAML::DylinkSection> DylinkSec =
56         std::make_unique<WasmYAML::DylinkSection>();
57     const wasm::WasmDylinkInfo& Info = Obj.dylinkInfo();
58     DylinkSec->MemorySize = Info.MemorySize;
59     DylinkSec->MemoryAlignment = Info.MemoryAlignment;
60     DylinkSec->TableSize = Info.TableSize;
61     DylinkSec->TableAlignment = Info.TableAlignment;
62     DylinkSec->Needed = Info.Needed;
63     CustomSec = std::move(DylinkSec);
64   } else if (WasmSec.Name == "name") {
65     std::unique_ptr<WasmYAML::NameSection> NameSec =
66         std::make_unique<WasmYAML::NameSection>();
67     for (const llvm::wasm::WasmDebugName &Name : Obj.debugNames()) {
68       WasmYAML::NameEntry NameEntry;
69       NameEntry.Name = Name.Name;
70       NameEntry.Index = Name.Index;
71       if (Name.Type == llvm::wasm::NameType::FUNCTION) {
72         NameSec->FunctionNames.push_back(NameEntry);
73       } else {
74         assert(Name.Type == llvm::wasm::NameType::GLOBAL);
75         NameSec->GlobalNames.push_back(NameEntry);
76       }
77     }
78     CustomSec = std::move(NameSec);
79   } else if (WasmSec.Name == "linking") {
80     std::unique_ptr<WasmYAML::LinkingSection> LinkingSec =
81         std::make_unique<WasmYAML::LinkingSection>();
82     LinkingSec->Version = Obj.linkingData().Version;
83 
84     ArrayRef<StringRef> Comdats = Obj.linkingData().Comdats;
85     for (StringRef ComdatName : Comdats)
86       LinkingSec->Comdats.emplace_back(WasmYAML::Comdat{ComdatName, {}});
87     for (auto &Func : Obj.functions()) {
88       if (Func.Comdat != UINT32_MAX) {
89         LinkingSec->Comdats[Func.Comdat].Entries.emplace_back(
90             WasmYAML::ComdatEntry{wasm::WASM_COMDAT_FUNCTION, Func.Index});
91       }
92     }
93 
94     uint32_t SegmentIndex = 0;
95     for (const object::WasmSegment &Segment : Obj.dataSegments()) {
96       if (!Segment.Data.Name.empty()) {
97         WasmYAML::SegmentInfo SegmentInfo;
98         SegmentInfo.Name = Segment.Data.Name;
99         SegmentInfo.Index = SegmentIndex;
100         SegmentInfo.Alignment = Segment.Data.Alignment;
101         SegmentInfo.Flags = Segment.Data.LinkerFlags;
102         LinkingSec->SegmentInfos.push_back(SegmentInfo);
103       }
104       if (Segment.Data.Comdat != UINT32_MAX) {
105         LinkingSec->Comdats[Segment.Data.Comdat].Entries.emplace_back(
106             WasmYAML::ComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
107       }
108       SegmentIndex++;
109     }
110     uint32_t SectionIndex = 0;
111     for (const auto &Sec : Obj.sections()) {
112       const WasmSection &WasmSec = Obj.getWasmSection(Sec);
113       if (WasmSec.Comdat != UINT32_MAX)
114         LinkingSec->Comdats[WasmSec.Comdat].Entries.emplace_back(
115             WasmYAML::ComdatEntry{wasm::WASM_COMDAT_SECTION, SectionIndex});
116       SectionIndex++;
117     }
118 
119     uint32_t SymbolIndex = 0;
120     for (const wasm::WasmSymbolInfo &Symbol : Obj.linkingData().SymbolTable) {
121       WasmYAML::SymbolInfo Info;
122       Info.Index = SymbolIndex++;
123       Info.Kind = static_cast<uint32_t>(Symbol.Kind);
124       Info.Name = Symbol.Name;
125       Info.Flags = Symbol.Flags;
126       switch (Symbol.Kind) {
127       case wasm::WASM_SYMBOL_TYPE_DATA:
128         Info.DataRef = Symbol.DataRef;
129         break;
130       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
131       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
132       case wasm::WASM_SYMBOL_TYPE_TABLE:
133       case wasm::WASM_SYMBOL_TYPE_EVENT:
134         Info.ElementIndex = Symbol.ElementIndex;
135         break;
136       case wasm::WASM_SYMBOL_TYPE_SECTION:
137         Info.ElementIndex = Symbol.ElementIndex;
138         break;
139       }
140       LinkingSec->SymbolTable.emplace_back(Info);
141     }
142 
143     for (const wasm::WasmInitFunc &Func : Obj.linkingData().InitFunctions) {
144       WasmYAML::InitFunction F{Func.Priority, Func.Symbol};
145       LinkingSec->InitFunctions.emplace_back(F);
146     }
147 
148     CustomSec = std::move(LinkingSec);
149   } else if (WasmSec.Name == "producers") {
150     std::unique_ptr<WasmYAML::ProducersSection> ProducersSec =
151         std::make_unique<WasmYAML::ProducersSection>();
152     const llvm::wasm::WasmProducerInfo &Info = Obj.getProducerInfo();
153     for (auto &E : Info.Languages) {
154       WasmYAML::ProducerEntry Producer;
155       Producer.Name = E.first;
156       Producer.Version = E.second;
157       ProducersSec->Languages.push_back(Producer);
158     }
159     for (auto &E : Info.Tools) {
160       WasmYAML::ProducerEntry Producer;
161       Producer.Name = E.first;
162       Producer.Version = E.second;
163       ProducersSec->Tools.push_back(Producer);
164     }
165     for (auto &E : Info.SDKs) {
166       WasmYAML::ProducerEntry Producer;
167       Producer.Name = E.first;
168       Producer.Version = E.second;
169       ProducersSec->SDKs.push_back(Producer);
170     }
171     CustomSec = std::move(ProducersSec);
172   } else if (WasmSec.Name == "target_features") {
173     std::unique_ptr<WasmYAML::TargetFeaturesSection> TargetFeaturesSec =
174         std::make_unique<WasmYAML::TargetFeaturesSection>();
175     for (auto &E : Obj.getTargetFeatures()) {
176       WasmYAML::FeatureEntry Feature;
177       Feature.Prefix = E.Prefix;
178       Feature.Name = E.Name;
179       TargetFeaturesSec->Features.push_back(Feature);
180     }
181     CustomSec = std::move(TargetFeaturesSec);
182   } else {
183     CustomSec = std::make_unique<WasmYAML::CustomSection>(WasmSec.Name);
184   }
185   CustomSec->Payload = yaml::BinaryRef(WasmSec.Content);
186   return CustomSec;
187 }
188 
189 ErrorOr<WasmYAML::Object *> WasmDumper::dump() {
190   auto Y = std::make_unique<WasmYAML::Object>();
191 
192   // Dump header
193   Y->Header.Version = Obj.getHeader().Version;
194 
195   // Dump sections
196   for (const auto &Sec : Obj.sections()) {
197     const WasmSection &WasmSec = Obj.getWasmSection(Sec);
198     std::unique_ptr<WasmYAML::Section> S;
199     switch (WasmSec.Type) {
200     case wasm::WASM_SEC_CUSTOM: {
201       if (WasmSec.Name.startswith("reloc.")) {
202         // Relocations are attached the sections they apply to rather than
203         // being represented as a custom section in the YAML output.
204         continue;
205       }
206       S = dumpCustomSection(WasmSec);
207       break;
208     }
209     case wasm::WASM_SEC_TYPE: {
210       auto TypeSec = std::make_unique<WasmYAML::TypeSection>();
211       uint32_t Index = 0;
212       for (const auto &FunctionSig : Obj.types()) {
213         WasmYAML::Signature Sig;
214         Sig.Index = Index++;
215         for (const auto &ParamType : FunctionSig.Params)
216           Sig.ParamTypes.emplace_back(static_cast<uint32_t>(ParamType));
217         for (const auto &ReturnType : FunctionSig.Returns)
218           Sig.ReturnTypes.emplace_back(static_cast<uint32_t>(ReturnType));
219         TypeSec->Signatures.push_back(Sig);
220       }
221       S = std::move(TypeSec);
222       break;
223     }
224     case wasm::WASM_SEC_IMPORT: {
225       auto ImportSec = std::make_unique<WasmYAML::ImportSection>();
226       for (auto &Import : Obj.imports()) {
227         WasmYAML::Import Im;
228         Im.Module = Import.Module;
229         Im.Field = Import.Field;
230         Im.Kind = Import.Kind;
231         switch (Im.Kind) {
232         case wasm::WASM_EXTERNAL_FUNCTION:
233           Im.SigIndex = Import.SigIndex;
234           break;
235         case wasm::WASM_EXTERNAL_GLOBAL:
236           Im.GlobalImport.Type = Import.Global.Type;
237           Im.GlobalImport.Mutable = Import.Global.Mutable;
238           break;
239         case wasm::WASM_EXTERNAL_EVENT:
240           Im.EventImport.Attribute = Import.Event.Attribute;
241           Im.EventImport.SigIndex = Import.Event.SigIndex;
242           break;
243         case wasm::WASM_EXTERNAL_TABLE:
244           // FIXME: Currently we always output an index of 0 for any imported
245           // table.
246           Im.TableImport = makeTable(0, Import.Table);
247           break;
248         case wasm::WASM_EXTERNAL_MEMORY:
249           Im.Memory = makeLimits(Import.Memory);
250           break;
251         }
252         ImportSec->Imports.push_back(Im);
253       }
254       S = std::move(ImportSec);
255       break;
256     }
257     case wasm::WASM_SEC_FUNCTION: {
258       auto FuncSec = std::make_unique<WasmYAML::FunctionSection>();
259       for (const auto &Func : Obj.functionTypes()) {
260         FuncSec->FunctionTypes.push_back(Func);
261       }
262       S = std::move(FuncSec);
263       break;
264     }
265     case wasm::WASM_SEC_TABLE: {
266       auto TableSec = std::make_unique<WasmYAML::TableSection>();
267       for (const wasm::WasmTable &Table : Obj.tables()) {
268         TableSec->Tables.push_back(makeTable(Table.Index, Table.Type));
269       }
270       S = std::move(TableSec);
271       break;
272     }
273     case wasm::WASM_SEC_MEMORY: {
274       auto MemorySec = std::make_unique<WasmYAML::MemorySection>();
275       for (const wasm::WasmLimits &Memory : Obj.memories()) {
276         MemorySec->Memories.push_back(makeLimits(Memory));
277       }
278       S = std::move(MemorySec);
279       break;
280     }
281     case wasm::WASM_SEC_EVENT: {
282       auto EventSec = std::make_unique<WasmYAML::EventSection>();
283       for (auto &Event : Obj.events()) {
284         WasmYAML::Event E;
285         E.Index = Event.Index;
286         E.Attribute = Event.Type.Attribute;
287         E.SigIndex = Event.Type.SigIndex;
288         EventSec->Events.push_back(E);
289       }
290       S = std::move(EventSec);
291       break;
292     }
293     case wasm::WASM_SEC_GLOBAL: {
294       auto GlobalSec = std::make_unique<WasmYAML::GlobalSection>();
295       for (auto &Global : Obj.globals()) {
296         WasmYAML::Global G;
297         G.Index = Global.Index;
298         G.Type = Global.Type.Type;
299         G.Mutable = Global.Type.Mutable;
300         G.InitExpr = Global.InitExpr;
301         GlobalSec->Globals.push_back(G);
302       }
303       S = std::move(GlobalSec);
304       break;
305     }
306     case wasm::WASM_SEC_START: {
307       auto StartSec = std::make_unique<WasmYAML::StartSection>();
308       StartSec->StartFunction = Obj.startFunction();
309       S = std::move(StartSec);
310       break;
311     }
312     case wasm::WASM_SEC_EXPORT: {
313       auto ExportSec = std::make_unique<WasmYAML::ExportSection>();
314       for (auto &Export : Obj.exports()) {
315         WasmYAML::Export Ex;
316         Ex.Name = Export.Name;
317         Ex.Kind = Export.Kind;
318         Ex.Index = Export.Index;
319         ExportSec->Exports.push_back(Ex);
320       }
321       S = std::move(ExportSec);
322       break;
323     }
324     case wasm::WASM_SEC_ELEM: {
325       auto ElemSec = std::make_unique<WasmYAML::ElemSection>();
326       for (auto &Segment : Obj.elements()) {
327         WasmYAML::ElemSegment Seg;
328         Seg.TableIndex = Segment.TableIndex;
329         Seg.Offset = Segment.Offset;
330         for (auto &Func : Segment.Functions) {
331           Seg.Functions.push_back(Func);
332         }
333         ElemSec->Segments.push_back(Seg);
334       }
335       S = std::move(ElemSec);
336       break;
337     }
338     case wasm::WASM_SEC_CODE: {
339       auto CodeSec = std::make_unique<WasmYAML::CodeSection>();
340       for (auto &Func : Obj.functions()) {
341         WasmYAML::Function Function;
342         Function.Index = Func.Index;
343         for (auto &Local : Func.Locals) {
344           WasmYAML::LocalDecl LocalDecl;
345           LocalDecl.Type = Local.Type;
346           LocalDecl.Count = Local.Count;
347           Function.Locals.push_back(LocalDecl);
348         }
349         Function.Body = yaml::BinaryRef(Func.Body);
350         CodeSec->Functions.push_back(Function);
351       }
352       S = std::move(CodeSec);
353       break;
354     }
355     case wasm::WASM_SEC_DATA: {
356       auto DataSec = std::make_unique<WasmYAML::DataSection>();
357       for (const object::WasmSegment &Segment : Obj.dataSegments()) {
358         WasmYAML::DataSegment Seg;
359         Seg.SectionOffset = Segment.SectionOffset;
360         Seg.InitFlags = Segment.Data.InitFlags;
361         Seg.MemoryIndex = Segment.Data.MemoryIndex;
362         Seg.Offset = Segment.Data.Offset;
363         Seg.Content = yaml::BinaryRef(Segment.Data.Content);
364         DataSec->Segments.push_back(Seg);
365       }
366       S = std::move(DataSec);
367       break;
368     }
369     case wasm::WASM_SEC_DATACOUNT: {
370       auto DataCountSec = std::make_unique<WasmYAML::DataCountSection>();
371       DataCountSec->Count = Obj.dataSegments().size();
372       S = std::move(DataCountSec);
373       break;
374     }
375     default:
376       llvm_unreachable("Unknown section type");
377       break;
378     }
379     for (const wasm::WasmRelocation &Reloc : WasmSec.Relocations) {
380       WasmYAML::Relocation R;
381       R.Type = Reloc.Type;
382       R.Index = Reloc.Index;
383       R.Offset = Reloc.Offset;
384       R.Addend = Reloc.Addend;
385       S->Relocations.push_back(R);
386     }
387     Y->Sections.push_back(std::move(S));
388   }
389 
390   return Y.release();
391 }
392 
393 std::error_code wasm2yaml(raw_ostream &Out, const object::WasmObjectFile &Obj) {
394   WasmDumper Dumper(Obj);
395   ErrorOr<WasmYAML::Object *> YAMLOrErr = Dumper.dump();
396   if (std::error_code EC = YAMLOrErr.getError())
397     return EC;
398 
399   std::unique_ptr<WasmYAML::Object> YAML(YAMLOrErr.get());
400   yaml::Output Yout(Out);
401   Yout << *YAML;
402 
403   return std::error_code();
404 }
405