xref: /freebsd/contrib/llvm-project/llvm/lib/ObjectYAML/WasmEmitter.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
1 //===- yaml2wasm - Convert YAML to a Wasm object file --------------------===//
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 /// \file
10 /// The Wasm component of yaml2obj.
11 ///
12 //===----------------------------------------------------------------------===//
13 //
14 
15 #include "llvm/Object/Wasm.h"
16 #include "llvm/ObjectYAML/ObjectYAML.h"
17 #include "llvm/ObjectYAML/yaml2obj.h"
18 #include "llvm/Support/Endian.h"
19 #include "llvm/Support/LEB128.h"
20 
21 using namespace llvm;
22 
23 namespace {
24 /// This parses a yaml stream that represents a Wasm object file.
25 /// See docs/yaml2obj for the yaml scheema.
26 class WasmWriter {
27 public:
28   WasmWriter(WasmYAML::Object &Obj, yaml::ErrorHandler EH)
29       : Obj(Obj), ErrHandler(EH) {}
30   bool writeWasm(raw_ostream &OS);
31 
32 private:
33   void writeRelocSection(raw_ostream &OS, WasmYAML::Section &Sec,
34                          uint32_t SectionIndex);
35 
36   void writeInitExpr(raw_ostream &OS, const wasm::WasmInitExpr &InitExpr);
37 
38   void writeSectionContent(raw_ostream &OS, WasmYAML::CustomSection &Section);
39   void writeSectionContent(raw_ostream &OS, WasmYAML::TypeSection &Section);
40   void writeSectionContent(raw_ostream &OS, WasmYAML::ImportSection &Section);
41   void writeSectionContent(raw_ostream &OS, WasmYAML::FunctionSection &Section);
42   void writeSectionContent(raw_ostream &OS, WasmYAML::TableSection &Section);
43   void writeSectionContent(raw_ostream &OS, WasmYAML::MemorySection &Section);
44   void writeSectionContent(raw_ostream &OS, WasmYAML::TagSection &Section);
45   void writeSectionContent(raw_ostream &OS, WasmYAML::GlobalSection &Section);
46   void writeSectionContent(raw_ostream &OS, WasmYAML::ExportSection &Section);
47   void writeSectionContent(raw_ostream &OS, WasmYAML::StartSection &Section);
48   void writeSectionContent(raw_ostream &OS, WasmYAML::ElemSection &Section);
49   void writeSectionContent(raw_ostream &OS, WasmYAML::CodeSection &Section);
50   void writeSectionContent(raw_ostream &OS, WasmYAML::DataSection &Section);
51   void writeSectionContent(raw_ostream &OS, WasmYAML::DataCountSection &Section);
52 
53   // Custom section types
54   void writeSectionContent(raw_ostream &OS, WasmYAML::DylinkSection &Section);
55   void writeSectionContent(raw_ostream &OS, WasmYAML::NameSection &Section);
56   void writeSectionContent(raw_ostream &OS, WasmYAML::LinkingSection &Section);
57   void writeSectionContent(raw_ostream &OS, WasmYAML::ProducersSection &Section);
58   void writeSectionContent(raw_ostream &OS,
59                           WasmYAML::TargetFeaturesSection &Section);
60   WasmYAML::Object &Obj;
61   uint32_t NumImportedFunctions = 0;
62   uint32_t NumImportedGlobals = 0;
63   uint32_t NumImportedTables = 0;
64   uint32_t NumImportedTags = 0;
65 
66   bool HasError = false;
67   yaml::ErrorHandler ErrHandler;
68   void reportError(const Twine &Msg);
69 };
70 
71 class SubSectionWriter {
72   raw_ostream &OS;
73   std::string OutString;
74   raw_string_ostream StringStream;
75 
76 public:
77   SubSectionWriter(raw_ostream &OS) : OS(OS), StringStream(OutString) {}
78 
79   void done() {
80     StringStream.flush();
81     encodeULEB128(OutString.size(), OS);
82     OS << OutString;
83     OutString.clear();
84   }
85 
86   raw_ostream &getStream() { return StringStream; }
87 };
88 
89 } // end anonymous namespace
90 
91 static int writeUint64(raw_ostream &OS, uint64_t Value) {
92   char Data[sizeof(Value)];
93   support::endian::write64le(Data, Value);
94   OS.write(Data, sizeof(Data));
95   return 0;
96 }
97 
98 static int writeUint32(raw_ostream &OS, uint32_t Value) {
99   char Data[sizeof(Value)];
100   support::endian::write32le(Data, Value);
101   OS.write(Data, sizeof(Data));
102   return 0;
103 }
104 
105 static int writeUint8(raw_ostream &OS, uint8_t Value) {
106   char Data[sizeof(Value)];
107   memcpy(Data, &Value, sizeof(Data));
108   OS.write(Data, sizeof(Data));
109   return 0;
110 }
111 
112 static int writeStringRef(const StringRef &Str, raw_ostream &OS) {
113   encodeULEB128(Str.size(), OS);
114   OS << Str;
115   return 0;
116 }
117 
118 static int writeLimits(const WasmYAML::Limits &Lim, raw_ostream &OS) {
119   writeUint8(OS, Lim.Flags);
120   encodeULEB128(Lim.Minimum, OS);
121   if (Lim.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
122     encodeULEB128(Lim.Maximum, OS);
123   return 0;
124 }
125 
126 void WasmWriter::reportError(const Twine &Msg) {
127   ErrHandler(Msg);
128   HasError = true;
129 }
130 
131 void WasmWriter::writeInitExpr(raw_ostream &OS,
132                                const wasm::WasmInitExpr &InitExpr) {
133   writeUint8(OS, InitExpr.Opcode);
134   switch (InitExpr.Opcode) {
135   case wasm::WASM_OPCODE_I32_CONST:
136     encodeSLEB128(InitExpr.Value.Int32, OS);
137     break;
138   case wasm::WASM_OPCODE_I64_CONST:
139     encodeSLEB128(InitExpr.Value.Int64, OS);
140     break;
141   case wasm::WASM_OPCODE_F32_CONST:
142     writeUint32(OS, InitExpr.Value.Float32);
143     break;
144   case wasm::WASM_OPCODE_F64_CONST:
145     writeUint64(OS, InitExpr.Value.Float64);
146     break;
147   case wasm::WASM_OPCODE_GLOBAL_GET:
148     encodeULEB128(InitExpr.Value.Global, OS);
149     break;
150   default:
151     reportError("unknown opcode in init_expr: " + Twine(InitExpr.Opcode));
152     return;
153   }
154   writeUint8(OS, wasm::WASM_OPCODE_END);
155 }
156 
157 void WasmWriter::writeSectionContent(raw_ostream &OS,
158                                      WasmYAML::DylinkSection &Section) {
159   writeStringRef(Section.Name, OS);
160 
161   writeUint8(OS, wasm::WASM_DYLINK_MEM_INFO);
162   SubSectionWriter SubSection(OS);
163   raw_ostream &SubOS = SubSection.getStream();
164   encodeULEB128(Section.MemorySize, SubOS);
165   encodeULEB128(Section.MemoryAlignment, SubOS);
166   encodeULEB128(Section.TableSize, SubOS);
167   encodeULEB128(Section.TableAlignment, SubOS);
168   SubSection.done();
169 
170   if (Section.Needed.size()) {
171     writeUint8(OS, wasm::WASM_DYLINK_NEEDED);
172     raw_ostream &SubOS = SubSection.getStream();
173     encodeULEB128(Section.Needed.size(), SubOS);
174     for (StringRef Needed : Section.Needed)
175       writeStringRef(Needed, SubOS);
176     SubSection.done();
177   }
178 }
179 
180 void WasmWriter::writeSectionContent(raw_ostream &OS,
181                                      WasmYAML::LinkingSection &Section) {
182   writeStringRef(Section.Name, OS);
183   encodeULEB128(Section.Version, OS);
184 
185   SubSectionWriter SubSection(OS);
186 
187   // SYMBOL_TABLE subsection
188   if (Section.SymbolTable.size()) {
189     writeUint8(OS, wasm::WASM_SYMBOL_TABLE);
190 
191     encodeULEB128(Section.SymbolTable.size(), SubSection.getStream());
192 #ifndef NDEBUG
193     uint32_t SymbolIndex = 0;
194 #endif
195     for (const WasmYAML::SymbolInfo &Info : Section.SymbolTable) {
196       assert(Info.Index == SymbolIndex++);
197       writeUint8(SubSection.getStream(), Info.Kind);
198       encodeULEB128(Info.Flags, SubSection.getStream());
199       switch (Info.Kind) {
200       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
201       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
202       case wasm::WASM_SYMBOL_TYPE_TABLE:
203       case wasm::WASM_SYMBOL_TYPE_TAG:
204         encodeULEB128(Info.ElementIndex, SubSection.getStream());
205         if ((Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
206             (Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
207           writeStringRef(Info.Name, SubSection.getStream());
208         break;
209       case wasm::WASM_SYMBOL_TYPE_DATA:
210         writeStringRef(Info.Name, SubSection.getStream());
211         if ((Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
212           encodeULEB128(Info.DataRef.Segment, SubSection.getStream());
213           encodeULEB128(Info.DataRef.Offset, SubSection.getStream());
214           encodeULEB128(Info.DataRef.Size, SubSection.getStream());
215         }
216         break;
217       case wasm::WASM_SYMBOL_TYPE_SECTION:
218         encodeULEB128(Info.ElementIndex, SubSection.getStream());
219         break;
220       default:
221         llvm_unreachable("unexpected kind");
222       }
223     }
224 
225     SubSection.done();
226   }
227 
228   // SEGMENT_NAMES subsection
229   if (Section.SegmentInfos.size()) {
230     writeUint8(OS, wasm::WASM_SEGMENT_INFO);
231     encodeULEB128(Section.SegmentInfos.size(), SubSection.getStream());
232     for (const WasmYAML::SegmentInfo &SegmentInfo : Section.SegmentInfos) {
233       writeStringRef(SegmentInfo.Name, SubSection.getStream());
234       encodeULEB128(SegmentInfo.Alignment, SubSection.getStream());
235       encodeULEB128(SegmentInfo.Flags, SubSection.getStream());
236     }
237     SubSection.done();
238   }
239 
240   // INIT_FUNCS subsection
241   if (Section.InitFunctions.size()) {
242     writeUint8(OS, wasm::WASM_INIT_FUNCS);
243     encodeULEB128(Section.InitFunctions.size(), SubSection.getStream());
244     for (const WasmYAML::InitFunction &Func : Section.InitFunctions) {
245       encodeULEB128(Func.Priority, SubSection.getStream());
246       encodeULEB128(Func.Symbol, SubSection.getStream());
247     }
248     SubSection.done();
249   }
250 
251   // COMDAT_INFO subsection
252   if (Section.Comdats.size()) {
253     writeUint8(OS, wasm::WASM_COMDAT_INFO);
254     encodeULEB128(Section.Comdats.size(), SubSection.getStream());
255     for (const auto &C : Section.Comdats) {
256       writeStringRef(C.Name, SubSection.getStream());
257       encodeULEB128(0, SubSection.getStream()); // flags for future use
258       encodeULEB128(C.Entries.size(), SubSection.getStream());
259       for (const WasmYAML::ComdatEntry &Entry : C.Entries) {
260         writeUint8(SubSection.getStream(), Entry.Kind);
261         encodeULEB128(Entry.Index, SubSection.getStream());
262       }
263     }
264     SubSection.done();
265   }
266 }
267 
268 void WasmWriter::writeSectionContent(raw_ostream &OS,
269                                      WasmYAML::NameSection &Section) {
270   writeStringRef(Section.Name, OS);
271   if (Section.FunctionNames.size()) {
272     writeUint8(OS, wasm::WASM_NAMES_FUNCTION);
273 
274     SubSectionWriter SubSection(OS);
275 
276     encodeULEB128(Section.FunctionNames.size(), SubSection.getStream());
277     for (const WasmYAML::NameEntry &NameEntry : Section.FunctionNames) {
278       encodeULEB128(NameEntry.Index, SubSection.getStream());
279       writeStringRef(NameEntry.Name, SubSection.getStream());
280     }
281 
282     SubSection.done();
283   }
284   if (Section.GlobalNames.size()) {
285     writeUint8(OS, wasm::WASM_NAMES_GLOBAL);
286 
287     SubSectionWriter SubSection(OS);
288 
289     encodeULEB128(Section.GlobalNames.size(), SubSection.getStream());
290     for (const WasmYAML::NameEntry &NameEntry : Section.GlobalNames) {
291       encodeULEB128(NameEntry.Index, SubSection.getStream());
292       writeStringRef(NameEntry.Name, SubSection.getStream());
293     }
294 
295     SubSection.done();
296   }
297   if (Section.DataSegmentNames.size()) {
298     writeUint8(OS, wasm::WASM_NAMES_DATA_SEGMENT);
299 
300     SubSectionWriter SubSection(OS);
301 
302     encodeULEB128(Section.DataSegmentNames.size(), SubSection.getStream());
303     for (const WasmYAML::NameEntry &NameEntry : Section.DataSegmentNames) {
304       encodeULEB128(NameEntry.Index, SubSection.getStream());
305       writeStringRef(NameEntry.Name, SubSection.getStream());
306     }
307 
308     SubSection.done();
309   }
310 }
311 
312 void WasmWriter::writeSectionContent(raw_ostream &OS,
313                                      WasmYAML::ProducersSection &Section) {
314   writeStringRef(Section.Name, OS);
315   int Fields = int(!Section.Languages.empty()) + int(!Section.Tools.empty()) +
316                int(!Section.SDKs.empty());
317   if (Fields == 0)
318     return;
319   encodeULEB128(Fields, OS);
320   for (auto &Field : {std::make_pair(StringRef("language"), &Section.Languages),
321                       std::make_pair(StringRef("processed-by"), &Section.Tools),
322                       std::make_pair(StringRef("sdk"), &Section.SDKs)}) {
323     if (Field.second->empty())
324       continue;
325     writeStringRef(Field.first, OS);
326     encodeULEB128(Field.second->size(), OS);
327     for (auto &Entry : *Field.second) {
328       writeStringRef(Entry.Name, OS);
329       writeStringRef(Entry.Version, OS);
330     }
331   }
332 }
333 
334 void WasmWriter::writeSectionContent(raw_ostream &OS,
335                                      WasmYAML::TargetFeaturesSection &Section) {
336   writeStringRef(Section.Name, OS);
337   encodeULEB128(Section.Features.size(), OS);
338   for (auto &E : Section.Features) {
339     writeUint8(OS, E.Prefix);
340     writeStringRef(E.Name, OS);
341   }
342 }
343 
344 void WasmWriter::writeSectionContent(raw_ostream &OS,
345                                      WasmYAML::CustomSection &Section) {
346   if (auto S = dyn_cast<WasmYAML::DylinkSection>(&Section)) {
347     writeSectionContent(OS, *S);
348   } else if (auto S = dyn_cast<WasmYAML::NameSection>(&Section)) {
349     writeSectionContent(OS, *S);
350   } else if (auto S = dyn_cast<WasmYAML::LinkingSection>(&Section)) {
351     writeSectionContent(OS, *S);
352   } else if (auto S = dyn_cast<WasmYAML::ProducersSection>(&Section)) {
353     writeSectionContent(OS, *S);
354   } else if (auto S = dyn_cast<WasmYAML::TargetFeaturesSection>(&Section)) {
355     writeSectionContent(OS, *S);
356   } else {
357     writeStringRef(Section.Name, OS);
358     Section.Payload.writeAsBinary(OS);
359   }
360 }
361 
362 void WasmWriter::writeSectionContent(raw_ostream &OS,
363                                     WasmYAML::TypeSection &Section) {
364   encodeULEB128(Section.Signatures.size(), OS);
365   uint32_t ExpectedIndex = 0;
366   for (const WasmYAML::Signature &Sig : Section.Signatures) {
367     if (Sig.Index != ExpectedIndex) {
368       reportError("unexpected type index: " + Twine(Sig.Index));
369       return;
370     }
371     ++ExpectedIndex;
372     writeUint8(OS, Sig.Form);
373     encodeULEB128(Sig.ParamTypes.size(), OS);
374     for (auto ParamType : Sig.ParamTypes)
375       writeUint8(OS, ParamType);
376     encodeULEB128(Sig.ReturnTypes.size(), OS);
377     for (auto ReturnType : Sig.ReturnTypes)
378       writeUint8(OS, ReturnType);
379   }
380 }
381 
382 void WasmWriter::writeSectionContent(raw_ostream &OS,
383                                     WasmYAML::ImportSection &Section) {
384   encodeULEB128(Section.Imports.size(), OS);
385   for (const WasmYAML::Import &Import : Section.Imports) {
386     writeStringRef(Import.Module, OS);
387     writeStringRef(Import.Field, OS);
388     writeUint8(OS, Import.Kind);
389     switch (Import.Kind) {
390     case wasm::WASM_EXTERNAL_FUNCTION:
391       encodeULEB128(Import.SigIndex, OS);
392       NumImportedFunctions++;
393       break;
394     case wasm::WASM_EXTERNAL_GLOBAL:
395       writeUint8(OS, Import.GlobalImport.Type);
396       writeUint8(OS, Import.GlobalImport.Mutable);
397       NumImportedGlobals++;
398       break;
399     case wasm::WASM_EXTERNAL_TAG:
400       writeUint8(OS, 0); // Reserved 'attribute' field
401       encodeULEB128(Import.SigIndex, OS);
402       NumImportedTags++;
403       break;
404     case wasm::WASM_EXTERNAL_MEMORY:
405       writeLimits(Import.Memory, OS);
406       break;
407     case wasm::WASM_EXTERNAL_TABLE:
408       writeUint8(OS, Import.TableImport.ElemType);
409       writeLimits(Import.TableImport.TableLimits, OS);
410       NumImportedTables++;
411       break;
412     default:
413       reportError("unknown import type: " +Twine(Import.Kind));
414       return;
415     }
416   }
417 }
418 
419 void WasmWriter::writeSectionContent(raw_ostream &OS,
420                                      WasmYAML::FunctionSection &Section) {
421   encodeULEB128(Section.FunctionTypes.size(), OS);
422   for (uint32_t FuncType : Section.FunctionTypes)
423     encodeULEB128(FuncType, OS);
424 }
425 
426 void WasmWriter::writeSectionContent(raw_ostream &OS,
427                                     WasmYAML::ExportSection &Section) {
428   encodeULEB128(Section.Exports.size(), OS);
429   for (const WasmYAML::Export &Export : Section.Exports) {
430     writeStringRef(Export.Name, OS);
431     writeUint8(OS, Export.Kind);
432     encodeULEB128(Export.Index, OS);
433   }
434 }
435 
436 void WasmWriter::writeSectionContent(raw_ostream &OS,
437                                      WasmYAML::StartSection &Section) {
438   encodeULEB128(Section.StartFunction, OS);
439 }
440 
441 void WasmWriter::writeSectionContent(raw_ostream &OS,
442                                      WasmYAML::TableSection &Section) {
443   encodeULEB128(Section.Tables.size(), OS);
444   uint32_t ExpectedIndex = NumImportedTables;
445   for (auto &Table : Section.Tables) {
446     if (Table.Index != ExpectedIndex) {
447       reportError("unexpected table index: " + Twine(Table.Index));
448       return;
449     }
450     ++ExpectedIndex;
451     writeUint8(OS, Table.ElemType);
452     writeLimits(Table.TableLimits, OS);
453   }
454 }
455 
456 void WasmWriter::writeSectionContent(raw_ostream &OS,
457                                      WasmYAML::MemorySection &Section) {
458   encodeULEB128(Section.Memories.size(), OS);
459   for (const WasmYAML::Limits &Mem : Section.Memories)
460     writeLimits(Mem, OS);
461 }
462 
463 void WasmWriter::writeSectionContent(raw_ostream &OS,
464                                      WasmYAML::TagSection &Section) {
465   encodeULEB128(Section.TagTypes.size(), OS);
466   for (uint32_t TagType : Section.TagTypes) {
467     writeUint8(OS, 0); // Reserved 'attribute' field
468     encodeULEB128(TagType, OS);
469   }
470 }
471 
472 void WasmWriter::writeSectionContent(raw_ostream &OS,
473                                      WasmYAML::GlobalSection &Section) {
474   encodeULEB128(Section.Globals.size(), OS);
475   uint32_t ExpectedIndex = NumImportedGlobals;
476   for (auto &Global : Section.Globals) {
477     if (Global.Index != ExpectedIndex) {
478       reportError("unexpected global index: " + Twine(Global.Index));
479       return;
480     }
481     ++ExpectedIndex;
482     writeUint8(OS, Global.Type);
483     writeUint8(OS, Global.Mutable);
484     writeInitExpr(OS, Global.InitExpr);
485   }
486 }
487 
488 void WasmWriter::writeSectionContent(raw_ostream &OS,
489                                      WasmYAML::ElemSection &Section) {
490   encodeULEB128(Section.Segments.size(), OS);
491   for (auto &Segment : Section.Segments) {
492     encodeULEB128(Segment.Flags, OS);
493     if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
494       encodeULEB128(Segment.TableNumber, OS);
495 
496     writeInitExpr(OS, Segment.Offset);
497 
498     if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
499       // We only support active function table initializers, for which the elem
500       // kind is specified to be written as 0x00 and interpreted to mean
501       // "funcref".
502       if (Segment.ElemKind != uint32_t(wasm::ValType::FUNCREF)) {
503         reportError("unexpected elemkind: " + Twine(Segment.ElemKind));
504         return;
505       }
506       const uint8_t ElemKind = 0;
507       writeUint8(OS, ElemKind);
508     }
509 
510     encodeULEB128(Segment.Functions.size(), OS);
511     for (auto &Function : Segment.Functions)
512       encodeULEB128(Function, OS);
513   }
514 }
515 
516 void WasmWriter::writeSectionContent(raw_ostream &OS,
517                                     WasmYAML::CodeSection &Section) {
518   encodeULEB128(Section.Functions.size(), OS);
519   uint32_t ExpectedIndex = NumImportedFunctions;
520   for (auto &Func : Section.Functions) {
521     std::string OutString;
522     raw_string_ostream StringStream(OutString);
523     if (Func.Index != ExpectedIndex) {
524       reportError("unexpected function index: " + Twine(Func.Index));
525       return;
526     }
527     ++ExpectedIndex;
528 
529     encodeULEB128(Func.Locals.size(), StringStream);
530     for (auto &LocalDecl : Func.Locals) {
531       encodeULEB128(LocalDecl.Count, StringStream);
532       writeUint8(StringStream, LocalDecl.Type);
533     }
534 
535     Func.Body.writeAsBinary(StringStream);
536 
537     // Write the section size followed by the content
538     StringStream.flush();
539     encodeULEB128(OutString.size(), OS);
540     OS << OutString;
541   }
542 }
543 
544 void WasmWriter::writeSectionContent(raw_ostream &OS,
545                                      WasmYAML::DataSection &Section) {
546   encodeULEB128(Section.Segments.size(), OS);
547   for (auto &Segment : Section.Segments) {
548     encodeULEB128(Segment.InitFlags, OS);
549     if (Segment.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
550       encodeULEB128(Segment.MemoryIndex, OS);
551     if ((Segment.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0)
552       writeInitExpr(OS, Segment.Offset);
553     encodeULEB128(Segment.Content.binary_size(), OS);
554     Segment.Content.writeAsBinary(OS);
555   }
556 }
557 
558 void WasmWriter::writeSectionContent(raw_ostream &OS,
559                                      WasmYAML::DataCountSection &Section) {
560   encodeULEB128(Section.Count, OS);
561 }
562 
563 void WasmWriter::writeRelocSection(raw_ostream &OS, WasmYAML::Section &Sec,
564                                   uint32_t SectionIndex) {
565   switch (Sec.Type) {
566   case wasm::WASM_SEC_CODE:
567     writeStringRef("reloc.CODE", OS);
568     break;
569   case wasm::WASM_SEC_DATA:
570     writeStringRef("reloc.DATA", OS);
571     break;
572   case wasm::WASM_SEC_CUSTOM: {
573     auto *CustomSection = cast<WasmYAML::CustomSection>(&Sec);
574     writeStringRef(("reloc." + CustomSection->Name).str(), OS);
575     break;
576   }
577   default:
578     llvm_unreachable("not yet implemented");
579   }
580 
581   encodeULEB128(SectionIndex, OS);
582   encodeULEB128(Sec.Relocations.size(), OS);
583 
584   for (auto Reloc : Sec.Relocations) {
585     writeUint8(OS, Reloc.Type);
586     encodeULEB128(Reloc.Offset, OS);
587     encodeULEB128(Reloc.Index, OS);
588     if (wasm::relocTypeHasAddend(Reloc.Type))
589       encodeSLEB128(Reloc.Addend, OS);
590   }
591 }
592 
593 bool WasmWriter::writeWasm(raw_ostream &OS) {
594   // Write headers
595   OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
596   writeUint32(OS, Obj.Header.Version);
597 
598   // Write each section
599   llvm::object::WasmSectionOrderChecker Checker;
600   for (const std::unique_ptr<WasmYAML::Section> &Sec : Obj.Sections) {
601     StringRef SecName = "";
602     if (auto S = dyn_cast<WasmYAML::CustomSection>(Sec.get()))
603       SecName = S->Name;
604     if (!Checker.isValidSectionOrder(Sec->Type, SecName)) {
605       reportError("out of order section type: " + Twine(Sec->Type));
606       return false;
607     }
608     encodeULEB128(Sec->Type, OS);
609     std::string OutString;
610     raw_string_ostream StringStream(OutString);
611     if (auto S = dyn_cast<WasmYAML::CustomSection>(Sec.get()))
612       writeSectionContent(StringStream, *S);
613     else if (auto S = dyn_cast<WasmYAML::TypeSection>(Sec.get()))
614       writeSectionContent(StringStream, *S);
615     else if (auto S = dyn_cast<WasmYAML::ImportSection>(Sec.get()))
616       writeSectionContent(StringStream, *S);
617     else if (auto S = dyn_cast<WasmYAML::FunctionSection>(Sec.get()))
618       writeSectionContent(StringStream, *S);
619     else if (auto S = dyn_cast<WasmYAML::TableSection>(Sec.get()))
620       writeSectionContent(StringStream, *S);
621     else if (auto S = dyn_cast<WasmYAML::MemorySection>(Sec.get()))
622       writeSectionContent(StringStream, *S);
623     else if (auto S = dyn_cast<WasmYAML::TagSection>(Sec.get()))
624       writeSectionContent(StringStream, *S);
625     else if (auto S = dyn_cast<WasmYAML::GlobalSection>(Sec.get()))
626       writeSectionContent(StringStream, *S);
627     else if (auto S = dyn_cast<WasmYAML::ExportSection>(Sec.get()))
628       writeSectionContent(StringStream, *S);
629     else if (auto S = dyn_cast<WasmYAML::StartSection>(Sec.get()))
630       writeSectionContent(StringStream, *S);
631     else if (auto S = dyn_cast<WasmYAML::ElemSection>(Sec.get()))
632       writeSectionContent(StringStream, *S);
633     else if (auto S = dyn_cast<WasmYAML::CodeSection>(Sec.get()))
634       writeSectionContent(StringStream, *S);
635     else if (auto S = dyn_cast<WasmYAML::DataSection>(Sec.get()))
636       writeSectionContent(StringStream, *S);
637     else if (auto S = dyn_cast<WasmYAML::DataCountSection>(Sec.get()))
638       writeSectionContent(StringStream, *S);
639     else
640       reportError("unknown section type: " + Twine(Sec->Type));
641 
642     if (HasError)
643       return false;
644 
645     StringStream.flush();
646 
647     // Write the section size followed by the content
648     encodeULEB128(OutString.size(), OS);
649     OS << OutString;
650   }
651 
652   // write reloc sections for any section that have relocations
653   uint32_t SectionIndex = 0;
654   for (const std::unique_ptr<WasmYAML::Section> &Sec : Obj.Sections) {
655     if (Sec->Relocations.empty()) {
656       SectionIndex++;
657       continue;
658     }
659 
660     writeUint8(OS, wasm::WASM_SEC_CUSTOM);
661     std::string OutString;
662     raw_string_ostream StringStream(OutString);
663     writeRelocSection(StringStream, *Sec, SectionIndex++);
664     StringStream.flush();
665 
666     encodeULEB128(OutString.size(), OS);
667     OS << OutString;
668   }
669 
670   return true;
671 }
672 
673 namespace llvm {
674 namespace yaml {
675 
676 bool yaml2wasm(WasmYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH) {
677   WasmWriter Writer(Doc, EH);
678   return Writer.writeWasm(Out);
679 }
680 
681 } // namespace yaml
682 } // namespace llvm
683