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