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