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::EventSection &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 NumImportedEvents = 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.Initial, 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   encodeULEB128(Section.MemorySize, OS);
161   encodeULEB128(Section.MemoryAlignment, OS);
162   encodeULEB128(Section.TableSize, OS);
163   encodeULEB128(Section.TableAlignment, OS);
164   encodeULEB128(Section.Needed.size(), OS);
165   for (StringRef Needed : Section.Needed)
166     writeStringRef(Needed, OS);
167 }
168 
169 void WasmWriter::writeSectionContent(raw_ostream &OS,
170                                      WasmYAML::LinkingSection &Section) {
171   writeStringRef(Section.Name, OS);
172   encodeULEB128(Section.Version, OS);
173 
174   SubSectionWriter SubSection(OS);
175 
176   // SYMBOL_TABLE subsection
177   if (Section.SymbolTable.size()) {
178     writeUint8(OS, wasm::WASM_SYMBOL_TABLE);
179 
180     encodeULEB128(Section.SymbolTable.size(), SubSection.getStream());
181 #ifndef NDEBUG
182     uint32_t SymbolIndex = 0;
183 #endif
184     for (const WasmYAML::SymbolInfo &Info : Section.SymbolTable) {
185       assert(Info.Index == SymbolIndex++);
186       writeUint8(SubSection.getStream(), Info.Kind);
187       encodeULEB128(Info.Flags, SubSection.getStream());
188       switch (Info.Kind) {
189       case wasm::WASM_SYMBOL_TYPE_FUNCTION:
190       case wasm::WASM_SYMBOL_TYPE_GLOBAL:
191       case wasm::WASM_SYMBOL_TYPE_TABLE:
192       case wasm::WASM_SYMBOL_TYPE_EVENT:
193         encodeULEB128(Info.ElementIndex, SubSection.getStream());
194         if ((Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
195             (Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
196           writeStringRef(Info.Name, SubSection.getStream());
197         break;
198       case wasm::WASM_SYMBOL_TYPE_DATA:
199         writeStringRef(Info.Name, SubSection.getStream());
200         if ((Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
201           encodeULEB128(Info.DataRef.Segment, SubSection.getStream());
202           encodeULEB128(Info.DataRef.Offset, SubSection.getStream());
203           encodeULEB128(Info.DataRef.Size, SubSection.getStream());
204         }
205         break;
206       case wasm::WASM_SYMBOL_TYPE_SECTION:
207         encodeULEB128(Info.ElementIndex, SubSection.getStream());
208         break;
209       default:
210         llvm_unreachable("unexpected kind");
211       }
212     }
213 
214     SubSection.done();
215   }
216 
217   // SEGMENT_NAMES subsection
218   if (Section.SegmentInfos.size()) {
219     writeUint8(OS, wasm::WASM_SEGMENT_INFO);
220     encodeULEB128(Section.SegmentInfos.size(), SubSection.getStream());
221     for (const WasmYAML::SegmentInfo &SegmentInfo : Section.SegmentInfos) {
222       writeStringRef(SegmentInfo.Name, SubSection.getStream());
223       encodeULEB128(SegmentInfo.Alignment, SubSection.getStream());
224       encodeULEB128(SegmentInfo.Flags, SubSection.getStream());
225     }
226     SubSection.done();
227   }
228 
229   // INIT_FUNCS subsection
230   if (Section.InitFunctions.size()) {
231     writeUint8(OS, wasm::WASM_INIT_FUNCS);
232     encodeULEB128(Section.InitFunctions.size(), SubSection.getStream());
233     for (const WasmYAML::InitFunction &Func : Section.InitFunctions) {
234       encodeULEB128(Func.Priority, SubSection.getStream());
235       encodeULEB128(Func.Symbol, SubSection.getStream());
236     }
237     SubSection.done();
238   }
239 
240   // COMDAT_INFO subsection
241   if (Section.Comdats.size()) {
242     writeUint8(OS, wasm::WASM_COMDAT_INFO);
243     encodeULEB128(Section.Comdats.size(), SubSection.getStream());
244     for (const auto &C : Section.Comdats) {
245       writeStringRef(C.Name, SubSection.getStream());
246       encodeULEB128(0, SubSection.getStream()); // flags for future use
247       encodeULEB128(C.Entries.size(), SubSection.getStream());
248       for (const WasmYAML::ComdatEntry &Entry : C.Entries) {
249         writeUint8(SubSection.getStream(), Entry.Kind);
250         encodeULEB128(Entry.Index, SubSection.getStream());
251       }
252     }
253     SubSection.done();
254   }
255 }
256 
257 void WasmWriter::writeSectionContent(raw_ostream &OS,
258                                      WasmYAML::NameSection &Section) {
259   writeStringRef(Section.Name, OS);
260   if (Section.FunctionNames.size()) {
261     writeUint8(OS, wasm::WASM_NAMES_FUNCTION);
262 
263     SubSectionWriter SubSection(OS);
264 
265     encodeULEB128(Section.FunctionNames.size(), SubSection.getStream());
266     for (const WasmYAML::NameEntry &NameEntry : Section.FunctionNames) {
267       encodeULEB128(NameEntry.Index, SubSection.getStream());
268       writeStringRef(NameEntry.Name, SubSection.getStream());
269     }
270 
271     SubSection.done();
272   }
273   if (Section.GlobalNames.size()) {
274     writeUint8(OS, wasm::WASM_NAMES_GLOBAL);
275 
276     SubSectionWriter SubSection(OS);
277 
278     encodeULEB128(Section.GlobalNames.size(), SubSection.getStream());
279     for (const WasmYAML::NameEntry &NameEntry : Section.GlobalNames) {
280       encodeULEB128(NameEntry.Index, SubSection.getStream());
281       writeStringRef(NameEntry.Name, SubSection.getStream());
282     }
283 
284     SubSection.done();
285   }
286 }
287 
288 void WasmWriter::writeSectionContent(raw_ostream &OS,
289                                      WasmYAML::ProducersSection &Section) {
290   writeStringRef(Section.Name, OS);
291   int Fields = int(!Section.Languages.empty()) + int(!Section.Tools.empty()) +
292                int(!Section.SDKs.empty());
293   if (Fields == 0)
294     return;
295   encodeULEB128(Fields, OS);
296   for (auto &Field : {std::make_pair(StringRef("language"), &Section.Languages),
297                       std::make_pair(StringRef("processed-by"), &Section.Tools),
298                       std::make_pair(StringRef("sdk"), &Section.SDKs)}) {
299     if (Field.second->empty())
300       continue;
301     writeStringRef(Field.first, OS);
302     encodeULEB128(Field.second->size(), OS);
303     for (auto &Entry : *Field.second) {
304       writeStringRef(Entry.Name, OS);
305       writeStringRef(Entry.Version, OS);
306     }
307   }
308 }
309 
310 void WasmWriter::writeSectionContent(raw_ostream &OS,
311                                      WasmYAML::TargetFeaturesSection &Section) {
312   writeStringRef(Section.Name, OS);
313   encodeULEB128(Section.Features.size(), OS);
314   for (auto &E : Section.Features) {
315     writeUint8(OS, E.Prefix);
316     writeStringRef(E.Name, OS);
317   }
318 }
319 
320 void WasmWriter::writeSectionContent(raw_ostream &OS,
321                                      WasmYAML::CustomSection &Section) {
322   if (auto S = dyn_cast<WasmYAML::DylinkSection>(&Section)) {
323     writeSectionContent(OS, *S);
324   } else if (auto S = dyn_cast<WasmYAML::NameSection>(&Section)) {
325     writeSectionContent(OS, *S);
326   } else if (auto S = dyn_cast<WasmYAML::LinkingSection>(&Section)) {
327     writeSectionContent(OS, *S);
328   } else if (auto S = dyn_cast<WasmYAML::ProducersSection>(&Section)) {
329     writeSectionContent(OS, *S);
330   } else if (auto S = dyn_cast<WasmYAML::TargetFeaturesSection>(&Section)) {
331     writeSectionContent(OS, *S);
332   } else {
333     writeStringRef(Section.Name, OS);
334     Section.Payload.writeAsBinary(OS);
335   }
336 }
337 
338 void WasmWriter::writeSectionContent(raw_ostream &OS,
339                                     WasmYAML::TypeSection &Section) {
340   encodeULEB128(Section.Signatures.size(), OS);
341   uint32_t ExpectedIndex = 0;
342   for (const WasmYAML::Signature &Sig : Section.Signatures) {
343     if (Sig.Index != ExpectedIndex) {
344       reportError("unexpected type index: " + Twine(Sig.Index));
345       return;
346     }
347     ++ExpectedIndex;
348     writeUint8(OS, Sig.Form);
349     encodeULEB128(Sig.ParamTypes.size(), OS);
350     for (auto ParamType : Sig.ParamTypes)
351       writeUint8(OS, ParamType);
352     encodeULEB128(Sig.ReturnTypes.size(), OS);
353     for (auto ReturnType : Sig.ReturnTypes)
354       writeUint8(OS, ReturnType);
355   }
356 }
357 
358 void WasmWriter::writeSectionContent(raw_ostream &OS,
359                                     WasmYAML::ImportSection &Section) {
360   encodeULEB128(Section.Imports.size(), OS);
361   for (const WasmYAML::Import &Import : Section.Imports) {
362     writeStringRef(Import.Module, OS);
363     writeStringRef(Import.Field, OS);
364     writeUint8(OS, Import.Kind);
365     switch (Import.Kind) {
366     case wasm::WASM_EXTERNAL_FUNCTION:
367       encodeULEB128(Import.SigIndex, OS);
368       NumImportedFunctions++;
369       break;
370     case wasm::WASM_EXTERNAL_GLOBAL:
371       writeUint8(OS, Import.GlobalImport.Type);
372       writeUint8(OS, Import.GlobalImport.Mutable);
373       NumImportedGlobals++;
374       break;
375     case wasm::WASM_EXTERNAL_EVENT:
376       writeUint32(OS, Import.EventImport.Attribute);
377       writeUint32(OS, Import.EventImport.SigIndex);
378       NumImportedEvents++;
379       break;
380     case wasm::WASM_EXTERNAL_MEMORY:
381       writeLimits(Import.Memory, OS);
382       break;
383     case wasm::WASM_EXTERNAL_TABLE:
384       writeUint8(OS, Import.TableImport.ElemType);
385       writeLimits(Import.TableImport.TableLimits, OS);
386       NumImportedTables++;
387       break;
388     default:
389       reportError("unknown import type: " +Twine(Import.Kind));
390       return;
391     }
392   }
393 }
394 
395 void WasmWriter::writeSectionContent(raw_ostream &OS,
396                                      WasmYAML::FunctionSection &Section) {
397   encodeULEB128(Section.FunctionTypes.size(), OS);
398   for (uint32_t FuncType : Section.FunctionTypes)
399     encodeULEB128(FuncType, OS);
400 }
401 
402 void WasmWriter::writeSectionContent(raw_ostream &OS,
403                                     WasmYAML::ExportSection &Section) {
404   encodeULEB128(Section.Exports.size(), OS);
405   for (const WasmYAML::Export &Export : Section.Exports) {
406     writeStringRef(Export.Name, OS);
407     writeUint8(OS, Export.Kind);
408     encodeULEB128(Export.Index, OS);
409   }
410 }
411 
412 void WasmWriter::writeSectionContent(raw_ostream &OS,
413                                      WasmYAML::StartSection &Section) {
414   encodeULEB128(Section.StartFunction, OS);
415 }
416 
417 void WasmWriter::writeSectionContent(raw_ostream &OS,
418                                      WasmYAML::TableSection &Section) {
419   encodeULEB128(Section.Tables.size(), OS);
420   uint32_t ExpectedIndex = NumImportedTables;
421   for (auto &Table : Section.Tables) {
422     if (Table.Index != ExpectedIndex) {
423       reportError("unexpected table index: " + Twine(Table.Index));
424       return;
425     }
426     ++ExpectedIndex;
427     writeUint8(OS, Table.ElemType);
428     writeLimits(Table.TableLimits, OS);
429   }
430 }
431 
432 void WasmWriter::writeSectionContent(raw_ostream &OS,
433                                      WasmYAML::MemorySection &Section) {
434   encodeULEB128(Section.Memories.size(), OS);
435   for (const WasmYAML::Limits &Mem : Section.Memories)
436     writeLimits(Mem, OS);
437 }
438 
439 void WasmWriter::writeSectionContent(raw_ostream &OS,
440                                      WasmYAML::EventSection &Section) {
441   encodeULEB128(Section.Events.size(), OS);
442   uint32_t ExpectedIndex = NumImportedEvents;
443   for (auto &Event : Section.Events) {
444     if (Event.Index != ExpectedIndex) {
445       reportError("unexpected event index: " + Twine(Event.Index));
446       return;
447     }
448     ++ExpectedIndex;
449     encodeULEB128(Event.Attribute, OS);
450     encodeULEB128(Event.SigIndex, OS);
451   }
452 }
453 
454 void WasmWriter::writeSectionContent(raw_ostream &OS,
455                                      WasmYAML::GlobalSection &Section) {
456   encodeULEB128(Section.Globals.size(), OS);
457   uint32_t ExpectedIndex = NumImportedGlobals;
458   for (auto &Global : Section.Globals) {
459     if (Global.Index != ExpectedIndex) {
460       reportError("unexpected global index: " + Twine(Global.Index));
461       return;
462     }
463     ++ExpectedIndex;
464     writeUint8(OS, Global.Type);
465     writeUint8(OS, Global.Mutable);
466     writeInitExpr(OS, Global.InitExpr);
467   }
468 }
469 
470 void WasmWriter::writeSectionContent(raw_ostream &OS,
471                                      WasmYAML::ElemSection &Section) {
472   encodeULEB128(Section.Segments.size(), OS);
473   for (auto &Segment : Section.Segments) {
474     encodeULEB128(Segment.TableIndex, OS);
475     writeInitExpr(OS, Segment.Offset);
476 
477     encodeULEB128(Segment.Functions.size(), OS);
478     for (auto &Function : Segment.Functions)
479       encodeULEB128(Function, OS);
480   }
481 }
482 
483 void WasmWriter::writeSectionContent(raw_ostream &OS,
484                                     WasmYAML::CodeSection &Section) {
485   encodeULEB128(Section.Functions.size(), OS);
486   uint32_t ExpectedIndex = NumImportedFunctions;
487   for (auto &Func : Section.Functions) {
488     std::string OutString;
489     raw_string_ostream StringStream(OutString);
490     if (Func.Index != ExpectedIndex) {
491       reportError("unexpected function index: " + Twine(Func.Index));
492       return;
493     }
494     ++ExpectedIndex;
495 
496     encodeULEB128(Func.Locals.size(), StringStream);
497     for (auto &LocalDecl : Func.Locals) {
498       encodeULEB128(LocalDecl.Count, StringStream);
499       writeUint8(StringStream, LocalDecl.Type);
500     }
501 
502     Func.Body.writeAsBinary(StringStream);
503 
504     // Write the section size followed by the content
505     StringStream.flush();
506     encodeULEB128(OutString.size(), OS);
507     OS << OutString;
508   }
509 }
510 
511 void WasmWriter::writeSectionContent(raw_ostream &OS,
512                                      WasmYAML::DataSection &Section) {
513   encodeULEB128(Section.Segments.size(), OS);
514   for (auto &Segment : Section.Segments) {
515     encodeULEB128(Segment.InitFlags, OS);
516     if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
517       encodeULEB128(Segment.MemoryIndex, OS);
518     if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0)
519       writeInitExpr(OS, Segment.Offset);
520     encodeULEB128(Segment.Content.binary_size(), OS);
521     Segment.Content.writeAsBinary(OS);
522   }
523 }
524 
525 void WasmWriter::writeSectionContent(raw_ostream &OS,
526                                      WasmYAML::DataCountSection &Section) {
527   encodeULEB128(Section.Count, OS);
528 }
529 
530 void WasmWriter::writeRelocSection(raw_ostream &OS, WasmYAML::Section &Sec,
531                                   uint32_t SectionIndex) {
532   switch (Sec.Type) {
533   case wasm::WASM_SEC_CODE:
534     writeStringRef("reloc.CODE", OS);
535     break;
536   case wasm::WASM_SEC_DATA:
537     writeStringRef("reloc.DATA", OS);
538     break;
539   case wasm::WASM_SEC_CUSTOM: {
540     auto *CustomSection = cast<WasmYAML::CustomSection>(&Sec);
541     writeStringRef(("reloc." + CustomSection->Name).str(), OS);
542     break;
543   }
544   default:
545     llvm_unreachable("not yet implemented");
546   }
547 
548   encodeULEB128(SectionIndex, OS);
549   encodeULEB128(Sec.Relocations.size(), OS);
550 
551   for (auto Reloc : Sec.Relocations) {
552     writeUint8(OS, Reloc.Type);
553     encodeULEB128(Reloc.Offset, OS);
554     encodeULEB128(Reloc.Index, OS);
555     switch (Reloc.Type) {
556     case wasm::R_WASM_MEMORY_ADDR_LEB:
557     case wasm::R_WASM_MEMORY_ADDR_LEB64:
558     case wasm::R_WASM_MEMORY_ADDR_SLEB:
559     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
560     case wasm::R_WASM_MEMORY_ADDR_I32:
561     case wasm::R_WASM_MEMORY_ADDR_I64:
562     case wasm::R_WASM_FUNCTION_OFFSET_I32:
563     case wasm::R_WASM_FUNCTION_OFFSET_I64:
564     case wasm::R_WASM_SECTION_OFFSET_I32:
565       encodeULEB128(Reloc.Addend, OS);
566     }
567   }
568 }
569 
570 bool WasmWriter::writeWasm(raw_ostream &OS) {
571   // Write headers
572   OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
573   writeUint32(OS, Obj.Header.Version);
574 
575   // Write each section
576   llvm::object::WasmSectionOrderChecker Checker;
577   for (const std::unique_ptr<WasmYAML::Section> &Sec : Obj.Sections) {
578     StringRef SecName = "";
579     if (auto S = dyn_cast<WasmYAML::CustomSection>(Sec.get()))
580       SecName = S->Name;
581     if (!Checker.isValidSectionOrder(Sec->Type, SecName)) {
582       reportError("out of order section type: " + Twine(Sec->Type));
583       return false;
584     }
585     encodeULEB128(Sec->Type, OS);
586     std::string OutString;
587     raw_string_ostream StringStream(OutString);
588     if (auto S = dyn_cast<WasmYAML::CustomSection>(Sec.get()))
589       writeSectionContent(StringStream, *S);
590     else if (auto S = dyn_cast<WasmYAML::TypeSection>(Sec.get()))
591       writeSectionContent(StringStream, *S);
592     else if (auto S = dyn_cast<WasmYAML::ImportSection>(Sec.get()))
593       writeSectionContent(StringStream, *S);
594     else if (auto S = dyn_cast<WasmYAML::FunctionSection>(Sec.get()))
595       writeSectionContent(StringStream, *S);
596     else if (auto S = dyn_cast<WasmYAML::TableSection>(Sec.get()))
597       writeSectionContent(StringStream, *S);
598     else if (auto S = dyn_cast<WasmYAML::MemorySection>(Sec.get()))
599       writeSectionContent(StringStream, *S);
600     else if (auto S = dyn_cast<WasmYAML::EventSection>(Sec.get()))
601       writeSectionContent(StringStream, *S);
602     else if (auto S = dyn_cast<WasmYAML::GlobalSection>(Sec.get()))
603       writeSectionContent(StringStream, *S);
604     else if (auto S = dyn_cast<WasmYAML::ExportSection>(Sec.get()))
605       writeSectionContent(StringStream, *S);
606     else if (auto S = dyn_cast<WasmYAML::StartSection>(Sec.get()))
607       writeSectionContent(StringStream, *S);
608     else if (auto S = dyn_cast<WasmYAML::ElemSection>(Sec.get()))
609       writeSectionContent(StringStream, *S);
610     else if (auto S = dyn_cast<WasmYAML::CodeSection>(Sec.get()))
611       writeSectionContent(StringStream, *S);
612     else if (auto S = dyn_cast<WasmYAML::DataSection>(Sec.get()))
613       writeSectionContent(StringStream, *S);
614     else if (auto S = dyn_cast<WasmYAML::DataCountSection>(Sec.get()))
615       writeSectionContent(StringStream, *S);
616     else
617       reportError("unknown section type: " + Twine(Sec->Type));
618 
619     if (HasError)
620       return false;
621 
622     StringStream.flush();
623 
624     // Write the section size followed by the content
625     encodeULEB128(OutString.size(), OS);
626     OS << OutString;
627   }
628 
629   // write reloc sections for any section that have relocations
630   uint32_t SectionIndex = 0;
631   for (const std::unique_ptr<WasmYAML::Section> &Sec : Obj.Sections) {
632     if (Sec->Relocations.empty()) {
633       SectionIndex++;
634       continue;
635     }
636 
637     writeUint8(OS, wasm::WASM_SEC_CUSTOM);
638     std::string OutString;
639     raw_string_ostream StringStream(OutString);
640     writeRelocSection(StringStream, *Sec, SectionIndex++);
641     StringStream.flush();
642 
643     encodeULEB128(OutString.size(), OS);
644     OS << OutString;
645   }
646 
647   return true;
648 }
649 
650 namespace llvm {
651 namespace yaml {
652 
653 bool yaml2wasm(WasmYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH) {
654   WasmWriter Writer(Doc, EH);
655   return Writer.writeWasm(Out);
656 }
657 
658 } // namespace yaml
659 } // namespace llvm
660