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