1 //===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//
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 "llvm/ADT/ArrayRef.h"
10 #include "llvm/ADT/DenseSet.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallSet.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/StringSet.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/BinaryFormat/Wasm.h"
18 #include "llvm/MC/SubtargetFeature.h"
19 #include "llvm/Object/Binary.h"
20 #include "llvm/Object/Error.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Object/SymbolicFile.h"
23 #include "llvm/Object/Wasm.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LEB128.h"
28 #include "llvm/Support/ScopedPrinter.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstdint>
32 #include <cstring>
33 #include <system_error>
34 
35 #define DEBUG_TYPE "wasm-object"
36 
37 using namespace llvm;
38 using namespace object;
39 
40 void WasmSymbol::print(raw_ostream &Out) const {
41   Out << "Name=" << Info.Name
42       << ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind))
43       << ", Flags=" << Info.Flags;
44   if (!isTypeData()) {
45     Out << ", ElemIndex=" << Info.ElementIndex;
46   } else if (isDefined()) {
47     Out << ", Segment=" << Info.DataRef.Segment;
48     Out << ", Offset=" << Info.DataRef.Offset;
49     Out << ", Size=" << Info.DataRef.Size;
50   }
51 }
52 
53 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
54 LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); }
55 #endif
56 
57 Expected<std::unique_ptr<WasmObjectFile>>
58 ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {
59   Error Err = Error::success();
60   auto ObjectFile = std::make_unique<WasmObjectFile>(Buffer, Err);
61   if (Err)
62     return std::move(Err);
63 
64   return std::move(ObjectFile);
65 }
66 
67 #define VARINT7_MAX ((1 << 7) - 1)
68 #define VARINT7_MIN (-(1 << 7))
69 #define VARUINT7_MAX (1 << 7)
70 #define VARUINT1_MAX (1)
71 
72 static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) {
73   if (Ctx.Ptr == Ctx.End)
74     report_fatal_error("EOF while reading uint8");
75   return *Ctx.Ptr++;
76 }
77 
78 static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) {
79   if (Ctx.Ptr + 4 > Ctx.End)
80     report_fatal_error("EOF while reading uint32");
81   uint32_t Result = support::endian::read32le(Ctx.Ptr);
82   Ctx.Ptr += 4;
83   return Result;
84 }
85 
86 static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) {
87   if (Ctx.Ptr + 4 > Ctx.End)
88     report_fatal_error("EOF while reading float64");
89   int32_t Result = 0;
90   memcpy(&Result, Ctx.Ptr, sizeof(Result));
91   Ctx.Ptr += sizeof(Result);
92   return Result;
93 }
94 
95 static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) {
96   if (Ctx.Ptr + 8 > Ctx.End)
97     report_fatal_error("EOF while reading float64");
98   int64_t Result = 0;
99   memcpy(&Result, Ctx.Ptr, sizeof(Result));
100   Ctx.Ptr += sizeof(Result);
101   return Result;
102 }
103 
104 static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) {
105   unsigned Count;
106   const char *Error = nullptr;
107   uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
108   if (Error)
109     report_fatal_error(Error);
110   Ctx.Ptr += Count;
111   return Result;
112 }
113 
114 static StringRef readString(WasmObjectFile::ReadContext &Ctx) {
115   uint32_t StringLen = readULEB128(Ctx);
116   if (Ctx.Ptr + StringLen > Ctx.End)
117     report_fatal_error("EOF while reading string");
118   StringRef Return =
119       StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen);
120   Ctx.Ptr += StringLen;
121   return Return;
122 }
123 
124 static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) {
125   unsigned Count;
126   const char *Error = nullptr;
127   uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
128   if (Error)
129     report_fatal_error(Error);
130   Ctx.Ptr += Count;
131   return Result;
132 }
133 
134 static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) {
135   int64_t Result = readLEB128(Ctx);
136   if (Result > VARUINT1_MAX || Result < 0)
137     report_fatal_error("LEB is outside Varuint1 range");
138   return Result;
139 }
140 
141 static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) {
142   int64_t Result = readLEB128(Ctx);
143   if (Result > INT32_MAX || Result < INT32_MIN)
144     report_fatal_error("LEB is outside Varint32 range");
145   return Result;
146 }
147 
148 static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) {
149   uint64_t Result = readULEB128(Ctx);
150   if (Result > UINT32_MAX)
151     report_fatal_error("LEB is outside Varuint32 range");
152   return Result;
153 }
154 
155 static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) {
156   return readLEB128(Ctx);
157 }
158 
159 static uint64_t readVaruint64(WasmObjectFile::ReadContext &Ctx) {
160   return readULEB128(Ctx);
161 }
162 
163 static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) {
164   return readUint8(Ctx);
165 }
166 
167 static Error readInitExpr(wasm::WasmInitExpr &Expr,
168                           WasmObjectFile::ReadContext &Ctx) {
169   Expr.Opcode = readOpcode(Ctx);
170 
171   switch (Expr.Opcode) {
172   case wasm::WASM_OPCODE_I32_CONST:
173     Expr.Value.Int32 = readVarint32(Ctx);
174     break;
175   case wasm::WASM_OPCODE_I64_CONST:
176     Expr.Value.Int64 = readVarint64(Ctx);
177     break;
178   case wasm::WASM_OPCODE_F32_CONST:
179     Expr.Value.Float32 = readFloat32(Ctx);
180     break;
181   case wasm::WASM_OPCODE_F64_CONST:
182     Expr.Value.Float64 = readFloat64(Ctx);
183     break;
184   case wasm::WASM_OPCODE_GLOBAL_GET:
185     Expr.Value.Global = readULEB128(Ctx);
186     break;
187   case wasm::WASM_OPCODE_REF_NULL: {
188     wasm::ValType Ty = static_cast<wasm::ValType>(readULEB128(Ctx));
189     if (Ty != wasm::ValType::EXTERNREF) {
190       return make_error<GenericBinaryError>("Invalid type for ref.null",
191                                             object_error::parse_failed);
192     }
193     break;
194   }
195   default:
196     return make_error<GenericBinaryError>("Invalid opcode in init_expr",
197                                           object_error::parse_failed);
198   }
199 
200   uint8_t EndOpcode = readOpcode(Ctx);
201   if (EndOpcode != wasm::WASM_OPCODE_END) {
202     return make_error<GenericBinaryError>("Invalid init_expr",
203                                           object_error::parse_failed);
204   }
205   return Error::success();
206 }
207 
208 static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) {
209   wasm::WasmLimits Result;
210   Result.Flags = readVaruint32(Ctx);
211   Result.Initial = readVaruint64(Ctx);
212   if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
213     Result.Maximum = readVaruint64(Ctx);
214   return Result;
215 }
216 
217 static wasm::WasmTable readTable(WasmObjectFile::ReadContext &Ctx) {
218   wasm::WasmTable Table;
219   Table.ElemType = readUint8(Ctx);
220   Table.Limits = readLimits(Ctx);
221   // The caller needs to set Table.Index field for Table
222   return Table;
223 }
224 
225 static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx,
226                          WasmSectionOrderChecker &Checker) {
227   Section.Offset = Ctx.Ptr - Ctx.Start;
228   Section.Type = readUint8(Ctx);
229   LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");
230   uint32_t Size = readVaruint32(Ctx);
231   if (Size == 0)
232     return make_error<StringError>("Zero length section",
233                                    object_error::parse_failed);
234   if (Ctx.Ptr + Size > Ctx.End)
235     return make_error<StringError>("Section too large",
236                                    object_error::parse_failed);
237   if (Section.Type == wasm::WASM_SEC_CUSTOM) {
238     WasmObjectFile::ReadContext SectionCtx;
239     SectionCtx.Start = Ctx.Ptr;
240     SectionCtx.Ptr = Ctx.Ptr;
241     SectionCtx.End = Ctx.Ptr + Size;
242 
243     Section.Name = readString(SectionCtx);
244 
245     uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start;
246     Ctx.Ptr += SectionNameSize;
247     Size -= SectionNameSize;
248   }
249 
250   if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) {
251     return make_error<StringError>("Out of order section type: " +
252                                        llvm::to_string(Section.Type),
253                                    object_error::parse_failed);
254   }
255 
256   Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
257   Ctx.Ptr += Size;
258   return Error::success();
259 }
260 
261 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
262     : ObjectFile(Binary::ID_Wasm, Buffer) {
263   ErrorAsOutParameter ErrAsOutParam(&Err);
264   Header.Magic = getData().substr(0, 4);
265   if (Header.Magic != StringRef("\0asm", 4)) {
266     Err =
267         make_error<StringError>("Bad magic number", object_error::parse_failed);
268     return;
269   }
270 
271   ReadContext Ctx;
272   Ctx.Start = getData().bytes_begin();
273   Ctx.Ptr = Ctx.Start + 4;
274   Ctx.End = Ctx.Start + getData().size();
275 
276   if (Ctx.Ptr + 4 > Ctx.End) {
277     Err = make_error<StringError>("Missing version number",
278                                   object_error::parse_failed);
279     return;
280   }
281 
282   Header.Version = readUint32(Ctx);
283   if (Header.Version != wasm::WasmVersion) {
284     Err = make_error<StringError>("Bad version number",
285                                   object_error::parse_failed);
286     return;
287   }
288 
289   WasmSection Sec;
290   WasmSectionOrderChecker Checker;
291   while (Ctx.Ptr < Ctx.End) {
292     if ((Err = readSection(Sec, Ctx, Checker)))
293       return;
294     if ((Err = parseSection(Sec)))
295       return;
296 
297     Sections.push_back(Sec);
298   }
299 }
300 
301 Error WasmObjectFile::parseSection(WasmSection &Sec) {
302   ReadContext Ctx;
303   Ctx.Start = Sec.Content.data();
304   Ctx.End = Ctx.Start + Sec.Content.size();
305   Ctx.Ptr = Ctx.Start;
306   switch (Sec.Type) {
307   case wasm::WASM_SEC_CUSTOM:
308     return parseCustomSection(Sec, Ctx);
309   case wasm::WASM_SEC_TYPE:
310     return parseTypeSection(Ctx);
311   case wasm::WASM_SEC_IMPORT:
312     return parseImportSection(Ctx);
313   case wasm::WASM_SEC_FUNCTION:
314     return parseFunctionSection(Ctx);
315   case wasm::WASM_SEC_TABLE:
316     return parseTableSection(Ctx);
317   case wasm::WASM_SEC_MEMORY:
318     return parseMemorySection(Ctx);
319   case wasm::WASM_SEC_EVENT:
320     return parseEventSection(Ctx);
321   case wasm::WASM_SEC_GLOBAL:
322     return parseGlobalSection(Ctx);
323   case wasm::WASM_SEC_EXPORT:
324     return parseExportSection(Ctx);
325   case wasm::WASM_SEC_START:
326     return parseStartSection(Ctx);
327   case wasm::WASM_SEC_ELEM:
328     return parseElemSection(Ctx);
329   case wasm::WASM_SEC_CODE:
330     return parseCodeSection(Ctx);
331   case wasm::WASM_SEC_DATA:
332     return parseDataSection(Ctx);
333   case wasm::WASM_SEC_DATACOUNT:
334     return parseDataCountSection(Ctx);
335   default:
336     return make_error<GenericBinaryError>(
337         "Invalid section type: " + Twine(Sec.Type), object_error::parse_failed);
338   }
339 }
340 
341 Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) {
342   // See https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
343   HasDylinkSection = true;
344   DylinkInfo.MemorySize = readVaruint32(Ctx);
345   DylinkInfo.MemoryAlignment = readVaruint32(Ctx);
346   DylinkInfo.TableSize = readVaruint32(Ctx);
347   DylinkInfo.TableAlignment = readVaruint32(Ctx);
348   uint32_t Count = readVaruint32(Ctx);
349   while (Count--) {
350     DylinkInfo.Needed.push_back(readString(Ctx));
351   }
352   if (Ctx.Ptr != Ctx.End)
353     return make_error<GenericBinaryError>("dylink section ended prematurely",
354                                           object_error::parse_failed);
355   return Error::success();
356 }
357 
358 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {
359   llvm::DenseSet<uint64_t> Seen;
360   if (FunctionTypes.size() && !SeenCodeSection) {
361     return make_error<GenericBinaryError>("Names must come after code section",
362                                           object_error::parse_failed);
363   }
364 
365   while (Ctx.Ptr < Ctx.End) {
366     uint8_t Type = readUint8(Ctx);
367     uint32_t Size = readVaruint32(Ctx);
368     const uint8_t *SubSectionEnd = Ctx.Ptr + Size;
369     switch (Type) {
370     case wasm::WASM_NAMES_FUNCTION: {
371       uint32_t Count = readVaruint32(Ctx);
372       while (Count--) {
373         uint32_t Index = readVaruint32(Ctx);
374         if (!Seen.insert(Index).second)
375           return make_error<GenericBinaryError>("Function named more than once",
376                                                 object_error::parse_failed);
377         StringRef Name = readString(Ctx);
378         if (!isValidFunctionIndex(Index) || Name.empty())
379           return make_error<GenericBinaryError>("Invalid name entry",
380                                                 object_error::parse_failed);
381         DebugNames.push_back(wasm::WasmFunctionName{Index, Name});
382         if (isDefinedFunctionIndex(Index))
383           getDefinedFunction(Index).DebugName = Name;
384       }
385       break;
386     }
387     // Ignore local names for now
388     case wasm::WASM_NAMES_LOCAL:
389     default:
390       Ctx.Ptr += Size;
391       break;
392     }
393     if (Ctx.Ptr != SubSectionEnd)
394       return make_error<GenericBinaryError>(
395           "Name sub-section ended prematurely", object_error::parse_failed);
396   }
397 
398   if (Ctx.Ptr != Ctx.End)
399     return make_error<GenericBinaryError>("Name section ended prematurely",
400                                           object_error::parse_failed);
401   return Error::success();
402 }
403 
404 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {
405   HasLinkingSection = true;
406   if (FunctionTypes.size() && !SeenCodeSection) {
407     return make_error<GenericBinaryError>(
408         "Linking data must come after code section",
409         object_error::parse_failed);
410   }
411 
412   LinkingData.Version = readVaruint32(Ctx);
413   if (LinkingData.Version != wasm::WasmMetadataVersion) {
414     return make_error<GenericBinaryError>(
415         "Unexpected metadata version: " + Twine(LinkingData.Version) +
416             " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",
417         object_error::parse_failed);
418   }
419 
420   const uint8_t *OrigEnd = Ctx.End;
421   while (Ctx.Ptr < OrigEnd) {
422     Ctx.End = OrigEnd;
423     uint8_t Type = readUint8(Ctx);
424     uint32_t Size = readVaruint32(Ctx);
425     LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size
426                       << "\n");
427     Ctx.End = Ctx.Ptr + Size;
428     switch (Type) {
429     case wasm::WASM_SYMBOL_TABLE:
430       if (Error Err = parseLinkingSectionSymtab(Ctx))
431         return Err;
432       break;
433     case wasm::WASM_SEGMENT_INFO: {
434       uint32_t Count = readVaruint32(Ctx);
435       if (Count > DataSegments.size())
436         return make_error<GenericBinaryError>("Too many segment names",
437                                               object_error::parse_failed);
438       for (uint32_t I = 0; I < Count; I++) {
439         DataSegments[I].Data.Name = readString(Ctx);
440         DataSegments[I].Data.Alignment = readVaruint32(Ctx);
441         DataSegments[I].Data.LinkerFlags = readVaruint32(Ctx);
442       }
443       break;
444     }
445     case wasm::WASM_INIT_FUNCS: {
446       uint32_t Count = readVaruint32(Ctx);
447       LinkingData.InitFunctions.reserve(Count);
448       for (uint32_t I = 0; I < Count; I++) {
449         wasm::WasmInitFunc Init;
450         Init.Priority = readVaruint32(Ctx);
451         Init.Symbol = readVaruint32(Ctx);
452         if (!isValidFunctionSymbol(Init.Symbol))
453           return make_error<GenericBinaryError>("Invalid function symbol: " +
454                                                     Twine(Init.Symbol),
455                                                 object_error::parse_failed);
456         LinkingData.InitFunctions.emplace_back(Init);
457       }
458       break;
459     }
460     case wasm::WASM_COMDAT_INFO:
461       if (Error Err = parseLinkingSectionComdat(Ctx))
462         return Err;
463       break;
464     default:
465       Ctx.Ptr += Size;
466       break;
467     }
468     if (Ctx.Ptr != Ctx.End)
469       return make_error<GenericBinaryError>(
470           "Linking sub-section ended prematurely", object_error::parse_failed);
471   }
472   if (Ctx.Ptr != OrigEnd)
473     return make_error<GenericBinaryError>("Linking section ended prematurely",
474                                           object_error::parse_failed);
475   return Error::success();
476 }
477 
478 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {
479   uint32_t Count = readVaruint32(Ctx);
480   LinkingData.SymbolTable.reserve(Count);
481   Symbols.reserve(Count);
482   StringSet<> SymbolNames;
483 
484   std::vector<wasm::WasmImport *> ImportedGlobals;
485   std::vector<wasm::WasmImport *> ImportedFunctions;
486   std::vector<wasm::WasmImport *> ImportedEvents;
487   ImportedGlobals.reserve(Imports.size());
488   ImportedFunctions.reserve(Imports.size());
489   ImportedEvents.reserve(Imports.size());
490   for (auto &I : Imports) {
491     if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)
492       ImportedFunctions.emplace_back(&I);
493     else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)
494       ImportedGlobals.emplace_back(&I);
495     else if (I.Kind == wasm::WASM_EXTERNAL_EVENT)
496       ImportedEvents.emplace_back(&I);
497   }
498 
499   while (Count--) {
500     wasm::WasmSymbolInfo Info;
501     const wasm::WasmSignature *Signature = nullptr;
502     const wasm::WasmGlobalType *GlobalType = nullptr;
503     uint8_t TableType = 0;
504     const wasm::WasmEventType *EventType = nullptr;
505 
506     Info.Kind = readUint8(Ctx);
507     Info.Flags = readVaruint32(Ctx);
508     bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;
509 
510     switch (Info.Kind) {
511     case wasm::WASM_SYMBOL_TYPE_FUNCTION:
512       Info.ElementIndex = readVaruint32(Ctx);
513       if (!isValidFunctionIndex(Info.ElementIndex) ||
514           IsDefined != isDefinedFunctionIndex(Info.ElementIndex))
515         return make_error<GenericBinaryError>("invalid function symbol index",
516                                               object_error::parse_failed);
517       if (IsDefined) {
518         Info.Name = readString(Ctx);
519         unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
520         Signature = &Signatures[FunctionTypes[FuncIndex]];
521         wasm::WasmFunction &Function = Functions[FuncIndex];
522         if (Function.SymbolName.empty())
523           Function.SymbolName = Info.Name;
524       } else {
525         wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];
526         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
527           Info.Name = readString(Ctx);
528           Info.ImportName = Import.Field;
529         } else {
530           Info.Name = Import.Field;
531         }
532         Signature = &Signatures[Import.SigIndex];
533         if (!Import.Module.empty()) {
534           Info.ImportModule = Import.Module;
535         }
536       }
537       break;
538 
539     case wasm::WASM_SYMBOL_TYPE_GLOBAL:
540       Info.ElementIndex = readVaruint32(Ctx);
541       if (!isValidGlobalIndex(Info.ElementIndex) ||
542           IsDefined != isDefinedGlobalIndex(Info.ElementIndex))
543         return make_error<GenericBinaryError>("invalid global symbol index",
544                                               object_error::parse_failed);
545       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
546                             wasm::WASM_SYMBOL_BINDING_WEAK)
547         return make_error<GenericBinaryError>("undefined weak global symbol",
548                                               object_error::parse_failed);
549       if (IsDefined) {
550         Info.Name = readString(Ctx);
551         unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;
552         wasm::WasmGlobal &Global = Globals[GlobalIndex];
553         GlobalType = &Global.Type;
554         if (Global.SymbolName.empty())
555           Global.SymbolName = Info.Name;
556       } else {
557         wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];
558         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
559           Info.Name = readString(Ctx);
560           Info.ImportName = Import.Field;
561         } else {
562           Info.Name = Import.Field;
563         }
564         GlobalType = &Import.Global;
565         if (!Import.Module.empty()) {
566           Info.ImportModule = Import.Module;
567         }
568       }
569       break;
570 
571     case wasm::WASM_SYMBOL_TYPE_TABLE:
572       Info.ElementIndex = readVaruint32(Ctx);
573       if (!isValidTableIndex(Info.ElementIndex) ||
574           IsDefined != isDefinedTableIndex(Info.ElementIndex))
575         return make_error<GenericBinaryError>("invalid table symbol index",
576                                               object_error::parse_failed);
577       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
578                             wasm::WASM_SYMBOL_BINDING_WEAK)
579         return make_error<GenericBinaryError>("undefined weak table symbol",
580                                               object_error::parse_failed);
581       if (IsDefined) {
582         Info.Name = readString(Ctx);
583         unsigned TableIndex = Info.ElementIndex - NumImportedTables;
584         wasm::WasmTable &Table = Tables[TableIndex];
585         TableType = Table.ElemType;
586       } else {
587         return make_error<GenericBinaryError>("undefined table symbol",
588                                               object_error::parse_failed);
589       }
590       break;
591 
592     case wasm::WASM_SYMBOL_TYPE_DATA:
593       Info.Name = readString(Ctx);
594       if (IsDefined) {
595         auto Index = readVaruint32(Ctx);
596         if (Index >= DataSegments.size())
597           return make_error<GenericBinaryError>("invalid data symbol index",
598                                                 object_error::parse_failed);
599         auto Offset = readVaruint64(Ctx);
600         auto Size = readVaruint64(Ctx);
601         if (Offset + Size > DataSegments[Index].Data.Content.size())
602           return make_error<GenericBinaryError>("invalid data symbol offset",
603                                                 object_error::parse_failed);
604         Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
605       }
606       break;
607 
608     case wasm::WASM_SYMBOL_TYPE_SECTION: {
609       if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
610           wasm::WASM_SYMBOL_BINDING_LOCAL)
611         return make_error<GenericBinaryError>(
612             "Section symbols must have local binding",
613             object_error::parse_failed);
614       Info.ElementIndex = readVaruint32(Ctx);
615       // Use somewhat unique section name as symbol name.
616       StringRef SectionName = Sections[Info.ElementIndex].Name;
617       Info.Name = SectionName;
618       break;
619     }
620 
621     case wasm::WASM_SYMBOL_TYPE_EVENT: {
622       Info.ElementIndex = readVaruint32(Ctx);
623       if (!isValidEventIndex(Info.ElementIndex) ||
624           IsDefined != isDefinedEventIndex(Info.ElementIndex))
625         return make_error<GenericBinaryError>("invalid event symbol index",
626                                               object_error::parse_failed);
627       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
628                             wasm::WASM_SYMBOL_BINDING_WEAK)
629         return make_error<GenericBinaryError>("undefined weak global symbol",
630                                               object_error::parse_failed);
631       if (IsDefined) {
632         Info.Name = readString(Ctx);
633         unsigned EventIndex = Info.ElementIndex - NumImportedEvents;
634         wasm::WasmEvent &Event = Events[EventIndex];
635         Signature = &Signatures[Event.Type.SigIndex];
636         EventType = &Event.Type;
637         if (Event.SymbolName.empty())
638           Event.SymbolName = Info.Name;
639 
640       } else {
641         wasm::WasmImport &Import = *ImportedEvents[Info.ElementIndex];
642         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
643           Info.Name = readString(Ctx);
644           Info.ImportName = Import.Field;
645         } else {
646           Info.Name = Import.Field;
647         }
648         EventType = &Import.Event;
649         Signature = &Signatures[EventType->SigIndex];
650         if (!Import.Module.empty()) {
651           Info.ImportModule = Import.Module;
652         }
653       }
654       break;
655     }
656 
657     default:
658       return make_error<GenericBinaryError>("Invalid symbol type",
659                                             object_error::parse_failed);
660     }
661 
662     if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
663             wasm::WASM_SYMBOL_BINDING_LOCAL &&
664         !SymbolNames.insert(Info.Name).second)
665       return make_error<GenericBinaryError>("Duplicate symbol name " +
666                                                 Twine(Info.Name),
667                                             object_error::parse_failed);
668     LinkingData.SymbolTable.emplace_back(Info);
669     Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType, TableType,
670                          EventType, Signature);
671     LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
672   }
673 
674   return Error::success();
675 }
676 
677 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {
678   uint32_t ComdatCount = readVaruint32(Ctx);
679   StringSet<> ComdatSet;
680   for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {
681     StringRef Name = readString(Ctx);
682     if (Name.empty() || !ComdatSet.insert(Name).second)
683       return make_error<GenericBinaryError>("Bad/duplicate COMDAT name " +
684                                                 Twine(Name),
685                                             object_error::parse_failed);
686     LinkingData.Comdats.emplace_back(Name);
687     uint32_t Flags = readVaruint32(Ctx);
688     if (Flags != 0)
689       return make_error<GenericBinaryError>("Unsupported COMDAT flags",
690                                             object_error::parse_failed);
691 
692     uint32_t EntryCount = readVaruint32(Ctx);
693     while (EntryCount--) {
694       unsigned Kind = readVaruint32(Ctx);
695       unsigned Index = readVaruint32(Ctx);
696       switch (Kind) {
697       default:
698         return make_error<GenericBinaryError>("Invalid COMDAT entry type",
699                                               object_error::parse_failed);
700       case wasm::WASM_COMDAT_DATA:
701         if (Index >= DataSegments.size())
702           return make_error<GenericBinaryError>(
703               "COMDAT data index out of range", object_error::parse_failed);
704         if (DataSegments[Index].Data.Comdat != UINT32_MAX)
705           return make_error<GenericBinaryError>("Data segment in two COMDATs",
706                                                 object_error::parse_failed);
707         DataSegments[Index].Data.Comdat = ComdatIndex;
708         break;
709       case wasm::WASM_COMDAT_FUNCTION:
710         if (!isDefinedFunctionIndex(Index))
711           return make_error<GenericBinaryError>(
712               "COMDAT function index out of range", object_error::parse_failed);
713         if (getDefinedFunction(Index).Comdat != UINT32_MAX)
714           return make_error<GenericBinaryError>("Function in two COMDATs",
715                                                 object_error::parse_failed);
716         getDefinedFunction(Index).Comdat = ComdatIndex;
717         break;
718       }
719     }
720   }
721   return Error::success();
722 }
723 
724 Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) {
725   llvm::SmallSet<StringRef, 3> FieldsSeen;
726   uint32_t Fields = readVaruint32(Ctx);
727   for (size_t I = 0; I < Fields; ++I) {
728     StringRef FieldName = readString(Ctx);
729     if (!FieldsSeen.insert(FieldName).second)
730       return make_error<GenericBinaryError>(
731           "Producers section does not have unique fields",
732           object_error::parse_failed);
733     std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr;
734     if (FieldName == "language") {
735       ProducerVec = &ProducerInfo.Languages;
736     } else if (FieldName == "processed-by") {
737       ProducerVec = &ProducerInfo.Tools;
738     } else if (FieldName == "sdk") {
739       ProducerVec = &ProducerInfo.SDKs;
740     } else {
741       return make_error<GenericBinaryError>(
742           "Producers section field is not named one of language, processed-by, "
743           "or sdk",
744           object_error::parse_failed);
745     }
746     uint32_t ValueCount = readVaruint32(Ctx);
747     llvm::SmallSet<StringRef, 8> ProducersSeen;
748     for (size_t J = 0; J < ValueCount; ++J) {
749       StringRef Name = readString(Ctx);
750       StringRef Version = readString(Ctx);
751       if (!ProducersSeen.insert(Name).second) {
752         return make_error<GenericBinaryError>(
753             "Producers section contains repeated producer",
754             object_error::parse_failed);
755       }
756       ProducerVec->emplace_back(std::string(Name), std::string(Version));
757     }
758   }
759   if (Ctx.Ptr != Ctx.End)
760     return make_error<GenericBinaryError>("Producers section ended prematurely",
761                                           object_error::parse_failed);
762   return Error::success();
763 }
764 
765 Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) {
766   llvm::SmallSet<std::string, 8> FeaturesSeen;
767   uint32_t FeatureCount = readVaruint32(Ctx);
768   for (size_t I = 0; I < FeatureCount; ++I) {
769     wasm::WasmFeatureEntry Feature;
770     Feature.Prefix = readUint8(Ctx);
771     switch (Feature.Prefix) {
772     case wasm::WASM_FEATURE_PREFIX_USED:
773     case wasm::WASM_FEATURE_PREFIX_REQUIRED:
774     case wasm::WASM_FEATURE_PREFIX_DISALLOWED:
775       break;
776     default:
777       return make_error<GenericBinaryError>("Unknown feature policy prefix",
778                                             object_error::parse_failed);
779     }
780     Feature.Name = std::string(readString(Ctx));
781     if (!FeaturesSeen.insert(Feature.Name).second)
782       return make_error<GenericBinaryError>(
783           "Target features section contains repeated feature \"" +
784               Feature.Name + "\"",
785           object_error::parse_failed);
786     TargetFeatures.push_back(Feature);
787   }
788   if (Ctx.Ptr != Ctx.End)
789     return make_error<GenericBinaryError>(
790         "Target features section ended prematurely",
791         object_error::parse_failed);
792   return Error::success();
793 }
794 
795 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {
796   uint32_t SectionIndex = readVaruint32(Ctx);
797   if (SectionIndex >= Sections.size())
798     return make_error<GenericBinaryError>("Invalid section index",
799                                           object_error::parse_failed);
800   WasmSection &Section = Sections[SectionIndex];
801   uint32_t RelocCount = readVaruint32(Ctx);
802   uint32_t EndOffset = Section.Content.size();
803   uint32_t PreviousOffset = 0;
804   while (RelocCount--) {
805     wasm::WasmRelocation Reloc = {};
806     Reloc.Type = readVaruint32(Ctx);
807     Reloc.Offset = readVaruint32(Ctx);
808     if (Reloc.Offset < PreviousOffset)
809       return make_error<GenericBinaryError>("Relocations not in offset order",
810                                             object_error::parse_failed);
811     PreviousOffset = Reloc.Offset;
812     Reloc.Index = readVaruint32(Ctx);
813     switch (Reloc.Type) {
814     case wasm::R_WASM_FUNCTION_INDEX_LEB:
815     case wasm::R_WASM_TABLE_INDEX_SLEB:
816     case wasm::R_WASM_TABLE_INDEX_SLEB64:
817     case wasm::R_WASM_TABLE_INDEX_I32:
818     case wasm::R_WASM_TABLE_INDEX_I64:
819     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
820       if (!isValidFunctionSymbol(Reloc.Index))
821         return make_error<GenericBinaryError>("Bad relocation function index",
822                                               object_error::parse_failed);
823       break;
824     case wasm::R_WASM_TABLE_NUMBER_LEB:
825       if (!isValidTableSymbol(Reloc.Index))
826         return make_error<GenericBinaryError>("Bad relocation table index",
827                                               object_error::parse_failed);
828       break;
829     case wasm::R_WASM_TYPE_INDEX_LEB:
830       if (Reloc.Index >= Signatures.size())
831         return make_error<GenericBinaryError>("Bad relocation type index",
832                                               object_error::parse_failed);
833       break;
834     case wasm::R_WASM_GLOBAL_INDEX_LEB:
835       // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data
836       // symbols to refer to their GOT entries.
837       if (!isValidGlobalSymbol(Reloc.Index) &&
838           !isValidDataSymbol(Reloc.Index) &&
839           !isValidFunctionSymbol(Reloc.Index))
840         return make_error<GenericBinaryError>("Bad relocation global index",
841                                               object_error::parse_failed);
842       break;
843     case wasm::R_WASM_GLOBAL_INDEX_I32:
844       if (!isValidGlobalSymbol(Reloc.Index))
845         return make_error<GenericBinaryError>("Bad relocation global index",
846                                               object_error::parse_failed);
847       break;
848     case wasm::R_WASM_EVENT_INDEX_LEB:
849       if (!isValidEventSymbol(Reloc.Index))
850         return make_error<GenericBinaryError>("Bad relocation event index",
851                                               object_error::parse_failed);
852       break;
853     case wasm::R_WASM_MEMORY_ADDR_LEB:
854     case wasm::R_WASM_MEMORY_ADDR_SLEB:
855     case wasm::R_WASM_MEMORY_ADDR_I32:
856     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
857     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
858       if (!isValidDataSymbol(Reloc.Index))
859         return make_error<GenericBinaryError>("Bad relocation data index",
860                                               object_error::parse_failed);
861       Reloc.Addend = readVarint32(Ctx);
862       break;
863     case wasm::R_WASM_MEMORY_ADDR_LEB64:
864     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
865     case wasm::R_WASM_MEMORY_ADDR_I64:
866     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
867       if (!isValidDataSymbol(Reloc.Index))
868         return make_error<GenericBinaryError>("Bad relocation data index",
869                                               object_error::parse_failed);
870       Reloc.Addend = readVarint64(Ctx);
871       break;
872     case wasm::R_WASM_FUNCTION_OFFSET_I32:
873       if (!isValidFunctionSymbol(Reloc.Index))
874         return make_error<GenericBinaryError>("Bad relocation function index",
875                                               object_error::parse_failed);
876       Reloc.Addend = readVarint32(Ctx);
877       break;
878     case wasm::R_WASM_FUNCTION_OFFSET_I64:
879       if (!isValidFunctionSymbol(Reloc.Index))
880         return make_error<GenericBinaryError>("Bad relocation function index",
881                                               object_error::parse_failed);
882       Reloc.Addend = readVarint64(Ctx);
883       break;
884     case wasm::R_WASM_SECTION_OFFSET_I32:
885       if (!isValidSectionSymbol(Reloc.Index))
886         return make_error<GenericBinaryError>("Bad relocation section index",
887                                               object_error::parse_failed);
888       Reloc.Addend = readVarint32(Ctx);
889       break;
890     default:
891       return make_error<GenericBinaryError>("Bad relocation type: " +
892                                                 Twine(Reloc.Type),
893                                             object_error::parse_failed);
894     }
895 
896     // Relocations must fit inside the section, and must appear in order.  They
897     // also shouldn't overlap a function/element boundary, but we don't bother
898     // to check that.
899     uint64_t Size = 5;
900     if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 ||
901         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 ||
902         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64)
903       Size = 10;
904     if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 ||
905         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 ||
906         Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 ||
907         Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
908         Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32)
909       Size = 4;
910     if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 ||
911         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 ||
912         Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64)
913       Size = 8;
914     if (Reloc.Offset + Size > EndOffset)
915       return make_error<GenericBinaryError>("Bad relocation offset",
916                                             object_error::parse_failed);
917 
918     Section.Relocations.push_back(Reloc);
919   }
920   if (Ctx.Ptr != Ctx.End)
921     return make_error<GenericBinaryError>("Reloc section ended prematurely",
922                                           object_error::parse_failed);
923   return Error::success();
924 }
925 
926 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {
927   if (Sec.Name == "dylink") {
928     if (Error Err = parseDylinkSection(Ctx))
929       return Err;
930   } else if (Sec.Name == "name") {
931     if (Error Err = parseNameSection(Ctx))
932       return Err;
933   } else if (Sec.Name == "linking") {
934     if (Error Err = parseLinkingSection(Ctx))
935       return Err;
936   } else if (Sec.Name == "producers") {
937     if (Error Err = parseProducersSection(Ctx))
938       return Err;
939   } else if (Sec.Name == "target_features") {
940     if (Error Err = parseTargetFeaturesSection(Ctx))
941       return Err;
942   } else if (Sec.Name.startswith("reloc.")) {
943     if (Error Err = parseRelocSection(Sec.Name, Ctx))
944       return Err;
945   }
946   return Error::success();
947 }
948 
949 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {
950   uint32_t Count = readVaruint32(Ctx);
951   Signatures.reserve(Count);
952   while (Count--) {
953     wasm::WasmSignature Sig;
954     uint8_t Form = readUint8(Ctx);
955     if (Form != wasm::WASM_TYPE_FUNC) {
956       return make_error<GenericBinaryError>("Invalid signature type",
957                                             object_error::parse_failed);
958     }
959     uint32_t ParamCount = readVaruint32(Ctx);
960     Sig.Params.reserve(ParamCount);
961     while (ParamCount--) {
962       uint32_t ParamType = readUint8(Ctx);
963       Sig.Params.push_back(wasm::ValType(ParamType));
964     }
965     uint32_t ReturnCount = readVaruint32(Ctx);
966     while (ReturnCount--) {
967       uint32_t ReturnType = readUint8(Ctx);
968       Sig.Returns.push_back(wasm::ValType(ReturnType));
969     }
970     Signatures.push_back(std::move(Sig));
971   }
972   if (Ctx.Ptr != Ctx.End)
973     return make_error<GenericBinaryError>("Type section ended prematurely",
974                                           object_error::parse_failed);
975   return Error::success();
976 }
977 
978 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {
979   uint32_t Count = readVaruint32(Ctx);
980   Imports.reserve(Count);
981   for (uint32_t I = 0; I < Count; I++) {
982     wasm::WasmImport Im;
983     Im.Module = readString(Ctx);
984     Im.Field = readString(Ctx);
985     Im.Kind = readUint8(Ctx);
986     switch (Im.Kind) {
987     case wasm::WASM_EXTERNAL_FUNCTION:
988       NumImportedFunctions++;
989       Im.SigIndex = readVaruint32(Ctx);
990       break;
991     case wasm::WASM_EXTERNAL_GLOBAL:
992       NumImportedGlobals++;
993       Im.Global.Type = readUint8(Ctx);
994       Im.Global.Mutable = readVaruint1(Ctx);
995       break;
996     case wasm::WASM_EXTERNAL_MEMORY:
997       Im.Memory = readLimits(Ctx);
998       if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
999         HasMemory64 = true;
1000       break;
1001     case wasm::WASM_EXTERNAL_TABLE: {
1002       Im.Table = readTable(Ctx);
1003       Im.Table.Index = NumImportedTables + Tables.size();
1004       NumImportedTables++;
1005       auto ElemType = Im.Table.ElemType;
1006       if (ElemType != wasm::WASM_TYPE_FUNCREF &&
1007           ElemType != wasm::WASM_TYPE_EXTERNREF)
1008         return make_error<GenericBinaryError>("Invalid table element type",
1009                                               object_error::parse_failed);
1010       break;
1011     }
1012     case wasm::WASM_EXTERNAL_EVENT:
1013       NumImportedEvents++;
1014       Im.Event.Attribute = readVarint32(Ctx);
1015       Im.Event.SigIndex = readVarint32(Ctx);
1016       break;
1017     default:
1018       return make_error<GenericBinaryError>("Unexpected import kind",
1019                                             object_error::parse_failed);
1020     }
1021     Imports.push_back(Im);
1022   }
1023   if (Ctx.Ptr != Ctx.End)
1024     return make_error<GenericBinaryError>("Import section ended prematurely",
1025                                           object_error::parse_failed);
1026   return Error::success();
1027 }
1028 
1029 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {
1030   uint32_t Count = readVaruint32(Ctx);
1031   FunctionTypes.reserve(Count);
1032   Functions.resize(Count);
1033   uint32_t NumTypes = Signatures.size();
1034   while (Count--) {
1035     uint32_t Type = readVaruint32(Ctx);
1036     if (Type >= NumTypes)
1037       return make_error<GenericBinaryError>("Invalid function type",
1038                                             object_error::parse_failed);
1039     FunctionTypes.push_back(Type);
1040   }
1041   if (Ctx.Ptr != Ctx.End)
1042     return make_error<GenericBinaryError>("Function section ended prematurely",
1043                                           object_error::parse_failed);
1044   return Error::success();
1045 }
1046 
1047 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {
1048   uint32_t Count = readVaruint32(Ctx);
1049   Tables.reserve(Count);
1050   while (Count--) {
1051     wasm::WasmTable T = readTable(Ctx);
1052     T.Index = NumImportedTables + Tables.size();
1053     Tables.push_back(T);
1054     auto ElemType = Tables.back().ElemType;
1055     if (ElemType != wasm::WASM_TYPE_FUNCREF &&
1056         ElemType != wasm::WASM_TYPE_EXTERNREF) {
1057       return make_error<GenericBinaryError>("Invalid table element type",
1058                                             object_error::parse_failed);
1059     }
1060   }
1061   if (Ctx.Ptr != Ctx.End)
1062     return make_error<GenericBinaryError>("Table section ended prematurely",
1063                                           object_error::parse_failed);
1064   return Error::success();
1065 }
1066 
1067 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {
1068   uint32_t Count = readVaruint32(Ctx);
1069   Memories.reserve(Count);
1070   while (Count--) {
1071     auto Limits = readLimits(Ctx);
1072     if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
1073       HasMemory64 = true;
1074     Memories.push_back(Limits);
1075   }
1076   if (Ctx.Ptr != Ctx.End)
1077     return make_error<GenericBinaryError>("Memory section ended prematurely",
1078                                           object_error::parse_failed);
1079   return Error::success();
1080 }
1081 
1082 Error WasmObjectFile::parseEventSection(ReadContext &Ctx) {
1083   EventSection = Sections.size();
1084   uint32_t Count = readVarint32(Ctx);
1085   Events.reserve(Count);
1086   while (Count--) {
1087     wasm::WasmEvent Event;
1088     Event.Index = NumImportedEvents + Events.size();
1089     Event.Type.Attribute = readVaruint32(Ctx);
1090     Event.Type.SigIndex = readVarint32(Ctx);
1091     Events.push_back(Event);
1092   }
1093 
1094   if (Ctx.Ptr != Ctx.End)
1095     return make_error<GenericBinaryError>("Event section ended prematurely",
1096                                           object_error::parse_failed);
1097   return Error::success();
1098 }
1099 
1100 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {
1101   GlobalSection = Sections.size();
1102   uint32_t Count = readVaruint32(Ctx);
1103   Globals.reserve(Count);
1104   while (Count--) {
1105     wasm::WasmGlobal Global;
1106     Global.Index = NumImportedGlobals + Globals.size();
1107     Global.Type.Type = readUint8(Ctx);
1108     Global.Type.Mutable = readVaruint1(Ctx);
1109     if (Error Err = readInitExpr(Global.InitExpr, Ctx))
1110       return Err;
1111     Globals.push_back(Global);
1112   }
1113   if (Ctx.Ptr != Ctx.End)
1114     return make_error<GenericBinaryError>("Global section ended prematurely",
1115                                           object_error::parse_failed);
1116   return Error::success();
1117 }
1118 
1119 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {
1120   uint32_t Count = readVaruint32(Ctx);
1121   Exports.reserve(Count);
1122   for (uint32_t I = 0; I < Count; I++) {
1123     wasm::WasmExport Ex;
1124     Ex.Name = readString(Ctx);
1125     Ex.Kind = readUint8(Ctx);
1126     Ex.Index = readVaruint32(Ctx);
1127     switch (Ex.Kind) {
1128     case wasm::WASM_EXTERNAL_FUNCTION:
1129 
1130       if (!isDefinedFunctionIndex(Ex.Index))
1131         return make_error<GenericBinaryError>("Invalid function export",
1132                                               object_error::parse_failed);
1133       getDefinedFunction(Ex.Index).ExportName = Ex.Name;
1134       break;
1135     case wasm::WASM_EXTERNAL_GLOBAL:
1136       if (!isValidGlobalIndex(Ex.Index))
1137         return make_error<GenericBinaryError>("Invalid global export",
1138                                               object_error::parse_failed);
1139       break;
1140     case wasm::WASM_EXTERNAL_EVENT:
1141       if (!isValidEventIndex(Ex.Index))
1142         return make_error<GenericBinaryError>("Invalid event export",
1143                                               object_error::parse_failed);
1144       break;
1145     case wasm::WASM_EXTERNAL_MEMORY:
1146     case wasm::WASM_EXTERNAL_TABLE:
1147       break;
1148     default:
1149       return make_error<GenericBinaryError>("Unexpected export kind",
1150                                             object_error::parse_failed);
1151     }
1152     Exports.push_back(Ex);
1153   }
1154   if (Ctx.Ptr != Ctx.End)
1155     return make_error<GenericBinaryError>("Export section ended prematurely",
1156                                           object_error::parse_failed);
1157   return Error::success();
1158 }
1159 
1160 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
1161   return Index < NumImportedFunctions + FunctionTypes.size();
1162 }
1163 
1164 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {
1165   return Index >= NumImportedFunctions && isValidFunctionIndex(Index);
1166 }
1167 
1168 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {
1169   return Index < NumImportedGlobals + Globals.size();
1170 }
1171 
1172 bool WasmObjectFile::isValidTableIndex(uint32_t Index) const {
1173   return Index < NumImportedTables + Tables.size();
1174 }
1175 
1176 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {
1177   return Index >= NumImportedGlobals && isValidGlobalIndex(Index);
1178 }
1179 
1180 bool WasmObjectFile::isDefinedTableIndex(uint32_t Index) const {
1181   return Index >= NumImportedTables && isValidTableIndex(Index);
1182 }
1183 
1184 bool WasmObjectFile::isValidEventIndex(uint32_t Index) const {
1185   return Index < NumImportedEvents + Events.size();
1186 }
1187 
1188 bool WasmObjectFile::isDefinedEventIndex(uint32_t Index) const {
1189   return Index >= NumImportedEvents && isValidEventIndex(Index);
1190 }
1191 
1192 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {
1193   return Index < Symbols.size() && Symbols[Index].isTypeFunction();
1194 }
1195 
1196 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const {
1197   return Index < Symbols.size() && Symbols[Index].isTypeTable();
1198 }
1199 
1200 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {
1201   return Index < Symbols.size() && Symbols[Index].isTypeGlobal();
1202 }
1203 
1204 bool WasmObjectFile::isValidEventSymbol(uint32_t Index) const {
1205   return Index < Symbols.size() && Symbols[Index].isTypeEvent();
1206 }
1207 
1208 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {
1209   return Index < Symbols.size() && Symbols[Index].isTypeData();
1210 }
1211 
1212 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {
1213   return Index < Symbols.size() && Symbols[Index].isTypeSection();
1214 }
1215 
1216 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {
1217   assert(isDefinedFunctionIndex(Index));
1218   return Functions[Index - NumImportedFunctions];
1219 }
1220 
1221 const wasm::WasmFunction &
1222 WasmObjectFile::getDefinedFunction(uint32_t Index) const {
1223   assert(isDefinedFunctionIndex(Index));
1224   return Functions[Index - NumImportedFunctions];
1225 }
1226 
1227 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) {
1228   assert(isDefinedGlobalIndex(Index));
1229   return Globals[Index - NumImportedGlobals];
1230 }
1231 
1232 wasm::WasmEvent &WasmObjectFile::getDefinedEvent(uint32_t Index) {
1233   assert(isDefinedEventIndex(Index));
1234   return Events[Index - NumImportedEvents];
1235 }
1236 
1237 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {
1238   StartFunction = readVaruint32(Ctx);
1239   if (!isValidFunctionIndex(StartFunction))
1240     return make_error<GenericBinaryError>("Invalid start function",
1241                                           object_error::parse_failed);
1242   return Error::success();
1243 }
1244 
1245 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {
1246   SeenCodeSection = true;
1247   CodeSection = Sections.size();
1248   uint32_t FunctionCount = readVaruint32(Ctx);
1249   if (FunctionCount != FunctionTypes.size()) {
1250     return make_error<GenericBinaryError>("Invalid function count",
1251                                           object_error::parse_failed);
1252   }
1253 
1254   for (uint32_t i = 0; i < FunctionCount; i++) {
1255     wasm::WasmFunction& Function = Functions[i];
1256     const uint8_t *FunctionStart = Ctx.Ptr;
1257     uint32_t Size = readVaruint32(Ctx);
1258     const uint8_t *FunctionEnd = Ctx.Ptr + Size;
1259 
1260     Function.CodeOffset = Ctx.Ptr - FunctionStart;
1261     Function.Index = NumImportedFunctions + i;
1262     Function.CodeSectionOffset = FunctionStart - Ctx.Start;
1263     Function.Size = FunctionEnd - FunctionStart;
1264 
1265     uint32_t NumLocalDecls = readVaruint32(Ctx);
1266     Function.Locals.reserve(NumLocalDecls);
1267     while (NumLocalDecls--) {
1268       wasm::WasmLocalDecl Decl;
1269       Decl.Count = readVaruint32(Ctx);
1270       Decl.Type = readUint8(Ctx);
1271       Function.Locals.push_back(Decl);
1272     }
1273 
1274     uint32_t BodySize = FunctionEnd - Ctx.Ptr;
1275     Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);
1276     // This will be set later when reading in the linking metadata section.
1277     Function.Comdat = UINT32_MAX;
1278     Ctx.Ptr += BodySize;
1279     assert(Ctx.Ptr == FunctionEnd);
1280   }
1281   if (Ctx.Ptr != Ctx.End)
1282     return make_error<GenericBinaryError>("Code section ended prematurely",
1283                                           object_error::parse_failed);
1284   return Error::success();
1285 }
1286 
1287 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {
1288   uint32_t Count = readVaruint32(Ctx);
1289   ElemSegments.reserve(Count);
1290   while (Count--) {
1291     wasm::WasmElemSegment Segment;
1292     Segment.TableIndex = readVaruint32(Ctx);
1293     if (Segment.TableIndex != 0) {
1294       return make_error<GenericBinaryError>("Invalid TableIndex",
1295                                             object_error::parse_failed);
1296     }
1297     if (Error Err = readInitExpr(Segment.Offset, Ctx))
1298       return Err;
1299     uint32_t NumElems = readVaruint32(Ctx);
1300     while (NumElems--) {
1301       Segment.Functions.push_back(readVaruint32(Ctx));
1302     }
1303     ElemSegments.push_back(Segment);
1304   }
1305   if (Ctx.Ptr != Ctx.End)
1306     return make_error<GenericBinaryError>("Elem section ended prematurely",
1307                                           object_error::parse_failed);
1308   return Error::success();
1309 }
1310 
1311 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {
1312   DataSection = Sections.size();
1313   uint32_t Count = readVaruint32(Ctx);
1314   if (DataCount && Count != DataCount.getValue())
1315     return make_error<GenericBinaryError>(
1316         "Number of data segments does not match DataCount section");
1317   DataSegments.reserve(Count);
1318   while (Count--) {
1319     WasmSegment Segment;
1320     Segment.Data.InitFlags = readVaruint32(Ctx);
1321     Segment.Data.MemoryIndex = (Segment.Data.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
1322                                ? readVaruint32(Ctx) : 0;
1323     if ((Segment.Data.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
1324       if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
1325         return Err;
1326     } else {
1327       Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST;
1328       Segment.Data.Offset.Value.Int32 = 0;
1329     }
1330     uint32_t Size = readVaruint32(Ctx);
1331     if (Size > (size_t)(Ctx.End - Ctx.Ptr))
1332       return make_error<GenericBinaryError>("Invalid segment size",
1333                                             object_error::parse_failed);
1334     Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
1335     // The rest of these Data fields are set later, when reading in the linking
1336     // metadata section.
1337     Segment.Data.Alignment = 0;
1338     Segment.Data.LinkerFlags = 0;
1339     Segment.Data.Comdat = UINT32_MAX;
1340     Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
1341     Ctx.Ptr += Size;
1342     DataSegments.push_back(Segment);
1343   }
1344   if (Ctx.Ptr != Ctx.End)
1345     return make_error<GenericBinaryError>("Data section ended prematurely",
1346                                           object_error::parse_failed);
1347   return Error::success();
1348 }
1349 
1350 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {
1351   DataCount = readVaruint32(Ctx);
1352   return Error::success();
1353 }
1354 
1355 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
1356   return Header;
1357 }
1358 
1359 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }
1360 
1361 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
1362   uint32_t Result = SymbolRef::SF_None;
1363   const WasmSymbol &Sym = getWasmSymbol(Symb);
1364 
1365   LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
1366   if (Sym.isBindingWeak())
1367     Result |= SymbolRef::SF_Weak;
1368   if (!Sym.isBindingLocal())
1369     Result |= SymbolRef::SF_Global;
1370   if (Sym.isHidden())
1371     Result |= SymbolRef::SF_Hidden;
1372   if (!Sym.isDefined())
1373     Result |= SymbolRef::SF_Undefined;
1374   if (Sym.isTypeFunction())
1375     Result |= SymbolRef::SF_Executable;
1376   return Result;
1377 }
1378 
1379 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
1380   DataRefImpl Ref;
1381   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1382   Ref.d.b = 0; // Symbol index
1383   return BasicSymbolRef(Ref, this);
1384 }
1385 
1386 basic_symbol_iterator WasmObjectFile::symbol_end() const {
1387   DataRefImpl Ref;
1388   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1389   Ref.d.b = Symbols.size(); // Symbol index
1390   return BasicSymbolRef(Ref, this);
1391 }
1392 
1393 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
1394   return Symbols[Symb.d.b];
1395 }
1396 
1397 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
1398   return getWasmSymbol(Symb.getRawDataRefImpl());
1399 }
1400 
1401 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
1402   return getWasmSymbol(Symb).Info.Name;
1403 }
1404 
1405 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
1406   auto &Sym = getWasmSymbol(Symb);
1407   if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&
1408       isDefinedFunctionIndex(Sym.Info.ElementIndex))
1409     return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset;
1410   else
1411     return getSymbolValue(Symb);
1412 }
1413 
1414 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {
1415   switch (Sym.Info.Kind) {
1416   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1417   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1418   case wasm::WASM_SYMBOL_TYPE_EVENT:
1419     return Sym.Info.ElementIndex;
1420   case wasm::WASM_SYMBOL_TYPE_DATA: {
1421     // The value of a data symbol is the segment offset, plus the symbol
1422     // offset within the segment.
1423     uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
1424     const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
1425     if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) {
1426       return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset;
1427     } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) {
1428       return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset;
1429     } else {
1430       llvm_unreachable("unknown init expr opcode");
1431     }
1432   }
1433   case wasm::WASM_SYMBOL_TYPE_SECTION:
1434     return 0;
1435   }
1436   llvm_unreachable("invalid symbol type");
1437 }
1438 
1439 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
1440   return getWasmSymbolValue(getWasmSymbol(Symb));
1441 }
1442 
1443 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
1444   llvm_unreachable("not yet implemented");
1445   return 0;
1446 }
1447 
1448 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
1449   llvm_unreachable("not yet implemented");
1450   return 0;
1451 }
1452 
1453 Expected<SymbolRef::Type>
1454 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
1455   const WasmSymbol &Sym = getWasmSymbol(Symb);
1456 
1457   switch (Sym.Info.Kind) {
1458   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1459     return SymbolRef::ST_Function;
1460   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1461     return SymbolRef::ST_Other;
1462   case wasm::WASM_SYMBOL_TYPE_DATA:
1463     return SymbolRef::ST_Data;
1464   case wasm::WASM_SYMBOL_TYPE_SECTION:
1465     return SymbolRef::ST_Debug;
1466   case wasm::WASM_SYMBOL_TYPE_EVENT:
1467     return SymbolRef::ST_Other;
1468   }
1469 
1470   llvm_unreachable("Unknown WasmSymbol::SymbolType");
1471   return SymbolRef::ST_Other;
1472 }
1473 
1474 Expected<section_iterator>
1475 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
1476   const WasmSymbol &Sym = getWasmSymbol(Symb);
1477   if (Sym.isUndefined())
1478     return section_end();
1479 
1480   DataRefImpl Ref;
1481   Ref.d.a = getSymbolSectionIdImpl(Sym);
1482   return section_iterator(SectionRef(Ref, this));
1483 }
1484 
1485 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {
1486   const WasmSymbol &Sym = getWasmSymbol(Symb);
1487   return getSymbolSectionIdImpl(Sym);
1488 }
1489 
1490 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {
1491   switch (Sym.Info.Kind) {
1492   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1493     return CodeSection;
1494   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1495     return GlobalSection;
1496   case wasm::WASM_SYMBOL_TYPE_DATA:
1497     return DataSection;
1498   case wasm::WASM_SYMBOL_TYPE_SECTION:
1499     return Sym.Info.ElementIndex;
1500   case wasm::WASM_SYMBOL_TYPE_EVENT:
1501     return EventSection;
1502   default:
1503     llvm_unreachable("Unknown WasmSymbol::SymbolType");
1504   }
1505 }
1506 
1507 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
1508 
1509 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {
1510   const WasmSection &S = Sections[Sec.d.a];
1511 #define ECase(X)                                                               \
1512   case wasm::WASM_SEC_##X:                                                     \
1513     return #X;
1514   switch (S.Type) {
1515     ECase(TYPE);
1516     ECase(IMPORT);
1517     ECase(FUNCTION);
1518     ECase(TABLE);
1519     ECase(MEMORY);
1520     ECase(GLOBAL);
1521     ECase(EVENT);
1522     ECase(EXPORT);
1523     ECase(START);
1524     ECase(ELEM);
1525     ECase(CODE);
1526     ECase(DATA);
1527     ECase(DATACOUNT);
1528   case wasm::WASM_SEC_CUSTOM:
1529     return S.Name;
1530   default:
1531     return createStringError(object_error::invalid_section_index, "");
1532   }
1533 #undef ECase
1534 }
1535 
1536 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
1537 
1538 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
1539   return Sec.d.a;
1540 }
1541 
1542 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
1543   const WasmSection &S = Sections[Sec.d.a];
1544   return S.Content.size();
1545 }
1546 
1547 Expected<ArrayRef<uint8_t>>
1548 WasmObjectFile::getSectionContents(DataRefImpl Sec) const {
1549   const WasmSection &S = Sections[Sec.d.a];
1550   // This will never fail since wasm sections can never be empty (user-sections
1551   // must have a name and non-user sections each have a defined structure).
1552   return S.Content;
1553 }
1554 
1555 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1556   return 1;
1557 }
1558 
1559 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1560   return false;
1561 }
1562 
1563 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
1564   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
1565 }
1566 
1567 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
1568   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
1569 }
1570 
1571 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
1572 
1573 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
1574 
1575 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
1576   DataRefImpl RelocRef;
1577   RelocRef.d.a = Ref.d.a;
1578   RelocRef.d.b = 0;
1579   return relocation_iterator(RelocationRef(RelocRef, this));
1580 }
1581 
1582 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
1583   const WasmSection &Sec = getWasmSection(Ref);
1584   DataRefImpl RelocRef;
1585   RelocRef.d.a = Ref.d.a;
1586   RelocRef.d.b = Sec.Relocations.size();
1587   return relocation_iterator(RelocationRef(RelocRef, this));
1588 }
1589 
1590 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }
1591 
1592 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1593   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1594   return Rel.Offset;
1595 }
1596 
1597 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
1598   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1599   if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)
1600     return symbol_end();
1601   DataRefImpl Sym;
1602   Sym.d.a = 1;
1603   Sym.d.b = Rel.Index;
1604   return symbol_iterator(SymbolRef(Sym, this));
1605 }
1606 
1607 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1608   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1609   return Rel.Type;
1610 }
1611 
1612 void WasmObjectFile::getRelocationTypeName(
1613     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1614   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1615   StringRef Res = "Unknown";
1616 
1617 #define WASM_RELOC(name, value)                                                \
1618   case wasm::name:                                                             \
1619     Res = #name;                                                               \
1620     break;
1621 
1622   switch (Rel.Type) {
1623 #include "llvm/BinaryFormat/WasmRelocs.def"
1624   }
1625 
1626 #undef WASM_RELOC
1627 
1628   Result.append(Res.begin(), Res.end());
1629 }
1630 
1631 section_iterator WasmObjectFile::section_begin() const {
1632   DataRefImpl Ref;
1633   Ref.d.a = 0;
1634   return section_iterator(SectionRef(Ref, this));
1635 }
1636 
1637 section_iterator WasmObjectFile::section_end() const {
1638   DataRefImpl Ref;
1639   Ref.d.a = Sections.size();
1640   return section_iterator(SectionRef(Ref, this));
1641 }
1642 
1643 uint8_t WasmObjectFile::getBytesInAddress() const {
1644   return HasMemory64 ? 8 : 4;
1645 }
1646 
1647 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1648 
1649 Triple::ArchType WasmObjectFile::getArch() const {
1650   return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
1651 }
1652 
1653 SubtargetFeatures WasmObjectFile::getFeatures() const {
1654   return SubtargetFeatures();
1655 }
1656 
1657 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }
1658 
1659 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }
1660 
1661 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1662   assert(Ref.d.a < Sections.size());
1663   return Sections[Ref.d.a];
1664 }
1665 
1666 const WasmSection &
1667 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1668   return getWasmSection(Section.getRawDataRefImpl());
1669 }
1670 
1671 const wasm::WasmRelocation &
1672 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1673   return getWasmRelocation(Ref.getRawDataRefImpl());
1674 }
1675 
1676 const wasm::WasmRelocation &
1677 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1678   assert(Ref.d.a < Sections.size());
1679   const WasmSection &Sec = Sections[Ref.d.a];
1680   assert(Ref.d.b < Sec.Relocations.size());
1681   return Sec.Relocations[Ref.d.b];
1682 }
1683 
1684 int WasmSectionOrderChecker::getSectionOrder(unsigned ID,
1685                                              StringRef CustomSectionName) {
1686   switch (ID) {
1687   case wasm::WASM_SEC_CUSTOM:
1688     return StringSwitch<unsigned>(CustomSectionName)
1689         .Case("dylink", WASM_SEC_ORDER_DYLINK)
1690         .Case("linking", WASM_SEC_ORDER_LINKING)
1691         .StartsWith("reloc.", WASM_SEC_ORDER_RELOC)
1692         .Case("name", WASM_SEC_ORDER_NAME)
1693         .Case("producers", WASM_SEC_ORDER_PRODUCERS)
1694         .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)
1695         .Default(WASM_SEC_ORDER_NONE);
1696   case wasm::WASM_SEC_TYPE:
1697     return WASM_SEC_ORDER_TYPE;
1698   case wasm::WASM_SEC_IMPORT:
1699     return WASM_SEC_ORDER_IMPORT;
1700   case wasm::WASM_SEC_FUNCTION:
1701     return WASM_SEC_ORDER_FUNCTION;
1702   case wasm::WASM_SEC_TABLE:
1703     return WASM_SEC_ORDER_TABLE;
1704   case wasm::WASM_SEC_MEMORY:
1705     return WASM_SEC_ORDER_MEMORY;
1706   case wasm::WASM_SEC_GLOBAL:
1707     return WASM_SEC_ORDER_GLOBAL;
1708   case wasm::WASM_SEC_EXPORT:
1709     return WASM_SEC_ORDER_EXPORT;
1710   case wasm::WASM_SEC_START:
1711     return WASM_SEC_ORDER_START;
1712   case wasm::WASM_SEC_ELEM:
1713     return WASM_SEC_ORDER_ELEM;
1714   case wasm::WASM_SEC_CODE:
1715     return WASM_SEC_ORDER_CODE;
1716   case wasm::WASM_SEC_DATA:
1717     return WASM_SEC_ORDER_DATA;
1718   case wasm::WASM_SEC_DATACOUNT:
1719     return WASM_SEC_ORDER_DATACOUNT;
1720   case wasm::WASM_SEC_EVENT:
1721     return WASM_SEC_ORDER_EVENT;
1722   default:
1723     return WASM_SEC_ORDER_NONE;
1724   }
1725 }
1726 
1727 // Represents the edges in a directed graph where any node B reachable from node
1728 // A is not allowed to appear before A in the section ordering, but may appear
1729 // afterward.
1730 int WasmSectionOrderChecker::DisallowedPredecessors
1731     [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {
1732         // WASM_SEC_ORDER_NONE
1733         {},
1734         // WASM_SEC_ORDER_TYPE
1735         {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},
1736         // WASM_SEC_ORDER_IMPORT
1737         {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},
1738         // WASM_SEC_ORDER_FUNCTION
1739         {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},
1740         // WASM_SEC_ORDER_TABLE
1741         {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},
1742         // WASM_SEC_ORDER_MEMORY
1743         {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_EVENT},
1744         // WASM_SEC_ORDER_EVENT
1745         {WASM_SEC_ORDER_EVENT, WASM_SEC_ORDER_GLOBAL},
1746         // WASM_SEC_ORDER_GLOBAL
1747         {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},
1748         // WASM_SEC_ORDER_EXPORT
1749         {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},
1750         // WASM_SEC_ORDER_START
1751         {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},
1752         // WASM_SEC_ORDER_ELEM
1753         {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},
1754         // WASM_SEC_ORDER_DATACOUNT
1755         {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},
1756         // WASM_SEC_ORDER_CODE
1757         {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},
1758         // WASM_SEC_ORDER_DATA
1759         {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},
1760 
1761         // Custom Sections
1762         // WASM_SEC_ORDER_DYLINK
1763         {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},
1764         // WASM_SEC_ORDER_LINKING
1765         {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},
1766         // WASM_SEC_ORDER_RELOC (can be repeated)
1767         {},
1768         // WASM_SEC_ORDER_NAME
1769         {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},
1770         // WASM_SEC_ORDER_PRODUCERS
1771         {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},
1772         // WASM_SEC_ORDER_TARGET_FEATURES
1773         {WASM_SEC_ORDER_TARGET_FEATURES}};
1774 
1775 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,
1776                                                   StringRef CustomSectionName) {
1777   int Order = getSectionOrder(ID, CustomSectionName);
1778   if (Order == WASM_SEC_ORDER_NONE)
1779     return true;
1780 
1781   // Disallowed predecessors we need to check for
1782   SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;
1783 
1784   // Keep track of completed checks to avoid repeating work
1785   bool Checked[WASM_NUM_SEC_ORDERS] = {};
1786 
1787   int Curr = Order;
1788   while (true) {
1789     // Add new disallowed predecessors to work list
1790     for (size_t I = 0;; ++I) {
1791       int Next = DisallowedPredecessors[Curr][I];
1792       if (Next == WASM_SEC_ORDER_NONE)
1793         break;
1794       if (Checked[Next])
1795         continue;
1796       WorkList.push_back(Next);
1797       Checked[Next] = true;
1798     }
1799 
1800     if (WorkList.empty())
1801       break;
1802 
1803     // Consider next disallowed predecessor
1804     Curr = WorkList.pop_back_val();
1805     if (Seen[Curr])
1806       return false;
1807   }
1808 
1809   // Have not seen any disallowed predecessors
1810   Seen[Order] = true;
1811   return true;
1812 }
1813