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