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