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