xref: /llvm-project/llvm/lib/Object/WasmObjectFile.cpp (revision b78c85a44af300f8e3da582411814385cf70239d)
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)) << ", Flags=0x"
43       << Twine::utohexstr(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.Minimum = 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::WasmTableType readTableType(WasmObjectFile::ReadContext &Ctx) {
218   wasm::WasmTableType TableType;
219   TableType.ElemType = readUint8(Ctx);
220   TableType.Limits = readLimits(Ctx);
221   return TableType;
222 }
223 
224 static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx,
225                          WasmSectionOrderChecker &Checker) {
226   Section.Offset = Ctx.Ptr - Ctx.Start;
227   Section.Type = readUint8(Ctx);
228   LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");
229   uint32_t Size = readVaruint32(Ctx);
230   if (Size == 0)
231     return make_error<StringError>("zero length section",
232                                    object_error::parse_failed);
233   if (Ctx.Ptr + Size > Ctx.End)
234     return make_error<StringError>("section too large",
235                                    object_error::parse_failed);
236   if (Section.Type == wasm::WASM_SEC_CUSTOM) {
237     WasmObjectFile::ReadContext SectionCtx;
238     SectionCtx.Start = Ctx.Ptr;
239     SectionCtx.Ptr = Ctx.Ptr;
240     SectionCtx.End = Ctx.Ptr + Size;
241 
242     Section.Name = readString(SectionCtx);
243 
244     uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start;
245     Ctx.Ptr += SectionNameSize;
246     Size -= SectionNameSize;
247   }
248 
249   if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) {
250     return make_error<StringError>("out of order section type: " +
251                                        llvm::to_string(Section.Type),
252                                    object_error::parse_failed);
253   }
254 
255   Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
256   Ctx.Ptr += Size;
257   return Error::success();
258 }
259 
260 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
261     : ObjectFile(Binary::ID_Wasm, Buffer) {
262   ErrorAsOutParameter ErrAsOutParam(&Err);
263   Header.Magic = getData().substr(0, 4);
264   if (Header.Magic != StringRef("\0asm", 4)) {
265     Err = make_error<StringError>("invalid magic number",
266                                   object_error::parse_failed);
267     return;
268   }
269 
270   ReadContext Ctx;
271   Ctx.Start = getData().bytes_begin();
272   Ctx.Ptr = Ctx.Start + 4;
273   Ctx.End = Ctx.Start + getData().size();
274 
275   if (Ctx.Ptr + 4 > Ctx.End) {
276     Err = make_error<StringError>("missing version number",
277                                   object_error::parse_failed);
278     return;
279   }
280 
281   Header.Version = readUint32(Ctx);
282   if (Header.Version != wasm::WasmVersion) {
283     Err = make_error<StringError>("invalid version number: " +
284                                       Twine(Header.Version),
285                                   object_error::parse_failed);
286     return;
287   }
288 
289   WasmSectionOrderChecker Checker;
290   while (Ctx.Ptr < Ctx.End) {
291     WasmSection Sec;
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_TAG:
320     return parseTagSection(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   // Legacy "dylink" section support.
343   // See parseDylink0Section for the current "dylink.0" section parsing.
344   HasDylinkSection = true;
345   DylinkInfo.MemorySize = readVaruint32(Ctx);
346   DylinkInfo.MemoryAlignment = readVaruint32(Ctx);
347   DylinkInfo.TableSize = readVaruint32(Ctx);
348   DylinkInfo.TableAlignment = readVaruint32(Ctx);
349   uint32_t Count = readVaruint32(Ctx);
350   while (Count--) {
351     DylinkInfo.Needed.push_back(readString(Ctx));
352   }
353 
354   if (Ctx.Ptr != Ctx.End)
355     return make_error<GenericBinaryError>("dylink section ended prematurely",
356                                           object_error::parse_failed);
357   return Error::success();
358 }
359 
360 Error WasmObjectFile::parseDylink0Section(ReadContext &Ctx) {
361   // See
362   // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
363   HasDylinkSection = true;
364 
365   const uint8_t *OrigEnd = Ctx.End;
366   while (Ctx.Ptr < OrigEnd) {
367     Ctx.End = OrigEnd;
368     uint8_t Type = readUint8(Ctx);
369     uint32_t Size = readVaruint32(Ctx);
370     LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size
371                       << "\n");
372     Ctx.End = Ctx.Ptr + Size;
373     uint32_t Count;
374     switch (Type) {
375     case wasm::WASM_DYLINK_MEM_INFO:
376       DylinkInfo.MemorySize = readVaruint32(Ctx);
377       DylinkInfo.MemoryAlignment = readVaruint32(Ctx);
378       DylinkInfo.TableSize = readVaruint32(Ctx);
379       DylinkInfo.TableAlignment = readVaruint32(Ctx);
380       break;
381     case wasm::WASM_DYLINK_NEEDED:
382       Count = readVaruint32(Ctx);
383       while (Count--) {
384         DylinkInfo.Needed.push_back(readString(Ctx));
385       }
386       break;
387     default:
388       return make_error<GenericBinaryError>("unknown dylink.0 sub-section",
389                                             object_error::parse_failed);
390       Ctx.Ptr += Size;
391       break;
392     }
393     if (Ctx.Ptr != Ctx.End) {
394       return make_error<GenericBinaryError>(
395           "dylink.0 sub-section ended prematurely", object_error::parse_failed);
396     }
397   }
398 
399   if (Ctx.Ptr != Ctx.End)
400     return make_error<GenericBinaryError>("dylink.0 section ended prematurely",
401                                           object_error::parse_failed);
402   return Error::success();
403 }
404 
405 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {
406   llvm::DenseSet<uint64_t> SeenFunctions;
407   llvm::DenseSet<uint64_t> SeenGlobals;
408   llvm::DenseSet<uint64_t> SeenSegments;
409   if (FunctionTypes.size() && !SeenCodeSection) {
410     return make_error<GenericBinaryError>("names must come after code section",
411                                           object_error::parse_failed);
412   }
413 
414   while (Ctx.Ptr < Ctx.End) {
415     uint8_t Type = readUint8(Ctx);
416     uint32_t Size = readVaruint32(Ctx);
417     const uint8_t *SubSectionEnd = Ctx.Ptr + Size;
418     switch (Type) {
419     case wasm::WASM_NAMES_FUNCTION:
420     case wasm::WASM_NAMES_GLOBAL:
421     case wasm::WASM_NAMES_DATA_SEGMENT: {
422       uint32_t Count = readVaruint32(Ctx);
423       while (Count--) {
424         uint32_t Index = readVaruint32(Ctx);
425         StringRef Name = readString(Ctx);
426         wasm::NameType nameType = wasm::NameType::FUNCTION;
427         if (Type == wasm::WASM_NAMES_FUNCTION) {
428           if (!SeenFunctions.insert(Index).second)
429             return make_error<GenericBinaryError>(
430                 "function named more than once", object_error::parse_failed);
431           if (!isValidFunctionIndex(Index) || Name.empty())
432             return make_error<GenericBinaryError>("invalid name entry",
433                                                   object_error::parse_failed);
434 
435           if (isDefinedFunctionIndex(Index))
436             getDefinedFunction(Index).DebugName = Name;
437         } else if (Type == wasm::WASM_NAMES_GLOBAL) {
438           nameType = wasm::NameType::GLOBAL;
439           if (!SeenGlobals.insert(Index).second)
440             return make_error<GenericBinaryError>("global named more than once",
441                                                   object_error::parse_failed);
442           if (!isValidGlobalIndex(Index) || Name.empty())
443             return make_error<GenericBinaryError>("invalid name entry",
444                                                   object_error::parse_failed);
445         } else {
446           nameType = wasm::NameType::DATA_SEGMENT;
447           if (!SeenSegments.insert(Index).second)
448             return make_error<GenericBinaryError>(
449                 "segment named more than once", object_error::parse_failed);
450           if (Index > DataSegments.size())
451             return make_error<GenericBinaryError>("invalid named data segment",
452                                                   object_error::parse_failed);
453         }
454         DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name});
455       }
456       break;
457     }
458     // Ignore local names for now
459     case wasm::WASM_NAMES_LOCAL:
460     default:
461       Ctx.Ptr += Size;
462       break;
463     }
464     if (Ctx.Ptr != SubSectionEnd)
465       return make_error<GenericBinaryError>(
466           "name sub-section ended prematurely", object_error::parse_failed);
467   }
468 
469   if (Ctx.Ptr != Ctx.End)
470     return make_error<GenericBinaryError>("name section ended prematurely",
471                                           object_error::parse_failed);
472   return Error::success();
473 }
474 
475 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {
476   HasLinkingSection = true;
477   if (FunctionTypes.size() && !SeenCodeSection) {
478     return make_error<GenericBinaryError>(
479         "linking data must come after code section",
480         object_error::parse_failed);
481   }
482 
483   LinkingData.Version = readVaruint32(Ctx);
484   if (LinkingData.Version != wasm::WasmMetadataVersion) {
485     return make_error<GenericBinaryError>(
486         "unexpected metadata version: " + Twine(LinkingData.Version) +
487             " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",
488         object_error::parse_failed);
489   }
490 
491   const uint8_t *OrigEnd = Ctx.End;
492   while (Ctx.Ptr < OrigEnd) {
493     Ctx.End = OrigEnd;
494     uint8_t Type = readUint8(Ctx);
495     uint32_t Size = readVaruint32(Ctx);
496     LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size
497                       << "\n");
498     Ctx.End = Ctx.Ptr + Size;
499     switch (Type) {
500     case wasm::WASM_SYMBOL_TABLE:
501       if (Error Err = parseLinkingSectionSymtab(Ctx))
502         return Err;
503       break;
504     case wasm::WASM_SEGMENT_INFO: {
505       uint32_t Count = readVaruint32(Ctx);
506       if (Count > DataSegments.size())
507         return make_error<GenericBinaryError>("too many segment names",
508                                               object_error::parse_failed);
509       for (uint32_t I = 0; I < Count; I++) {
510         DataSegments[I].Data.Name = readString(Ctx);
511         DataSegments[I].Data.Alignment = readVaruint32(Ctx);
512         DataSegments[I].Data.LinkingFlags = readVaruint32(Ctx);
513       }
514       break;
515     }
516     case wasm::WASM_INIT_FUNCS: {
517       uint32_t Count = readVaruint32(Ctx);
518       LinkingData.InitFunctions.reserve(Count);
519       for (uint32_t I = 0; I < Count; I++) {
520         wasm::WasmInitFunc Init;
521         Init.Priority = readVaruint32(Ctx);
522         Init.Symbol = readVaruint32(Ctx);
523         if (!isValidFunctionSymbol(Init.Symbol))
524           return make_error<GenericBinaryError>("invalid function symbol: " +
525                                                     Twine(Init.Symbol),
526                                                 object_error::parse_failed);
527         LinkingData.InitFunctions.emplace_back(Init);
528       }
529       break;
530     }
531     case wasm::WASM_COMDAT_INFO:
532       if (Error Err = parseLinkingSectionComdat(Ctx))
533         return Err;
534       break;
535     default:
536       Ctx.Ptr += Size;
537       break;
538     }
539     if (Ctx.Ptr != Ctx.End)
540       return make_error<GenericBinaryError>(
541           "linking sub-section ended prematurely", object_error::parse_failed);
542   }
543   if (Ctx.Ptr != OrigEnd)
544     return make_error<GenericBinaryError>("linking section ended prematurely",
545                                           object_error::parse_failed);
546   return Error::success();
547 }
548 
549 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {
550   uint32_t Count = readVaruint32(Ctx);
551   LinkingData.SymbolTable.reserve(Count);
552   Symbols.reserve(Count);
553   StringSet<> SymbolNames;
554 
555   std::vector<wasm::WasmImport *> ImportedGlobals;
556   std::vector<wasm::WasmImport *> ImportedFunctions;
557   std::vector<wasm::WasmImport *> ImportedTags;
558   std::vector<wasm::WasmImport *> ImportedTables;
559   ImportedGlobals.reserve(Imports.size());
560   ImportedFunctions.reserve(Imports.size());
561   ImportedTags.reserve(Imports.size());
562   ImportedTables.reserve(Imports.size());
563   for (auto &I : Imports) {
564     if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)
565       ImportedFunctions.emplace_back(&I);
566     else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)
567       ImportedGlobals.emplace_back(&I);
568     else if (I.Kind == wasm::WASM_EXTERNAL_TAG)
569       ImportedTags.emplace_back(&I);
570     else if (I.Kind == wasm::WASM_EXTERNAL_TABLE)
571       ImportedTables.emplace_back(&I);
572   }
573 
574   while (Count--) {
575     wasm::WasmSymbolInfo Info;
576     const wasm::WasmSignature *Signature = nullptr;
577     const wasm::WasmGlobalType *GlobalType = nullptr;
578     const wasm::WasmTableType *TableType = nullptr;
579     const wasm::WasmTagType *TagType = nullptr;
580 
581     Info.Kind = readUint8(Ctx);
582     Info.Flags = readVaruint32(Ctx);
583     bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;
584 
585     switch (Info.Kind) {
586     case wasm::WASM_SYMBOL_TYPE_FUNCTION:
587       Info.ElementIndex = readVaruint32(Ctx);
588       if (!isValidFunctionIndex(Info.ElementIndex) ||
589           IsDefined != isDefinedFunctionIndex(Info.ElementIndex))
590         return make_error<GenericBinaryError>("invalid function symbol index",
591                                               object_error::parse_failed);
592       if (IsDefined) {
593         Info.Name = readString(Ctx);
594         unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
595         Signature = &Signatures[FunctionTypes[FuncIndex]];
596         wasm::WasmFunction &Function = Functions[FuncIndex];
597         if (Function.SymbolName.empty())
598           Function.SymbolName = Info.Name;
599       } else {
600         wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];
601         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
602           Info.Name = readString(Ctx);
603           Info.ImportName = Import.Field;
604         } else {
605           Info.Name = Import.Field;
606         }
607         Signature = &Signatures[Import.SigIndex];
608         if (!Import.Module.empty()) {
609           Info.ImportModule = Import.Module;
610         }
611       }
612       break;
613 
614     case wasm::WASM_SYMBOL_TYPE_GLOBAL:
615       Info.ElementIndex = readVaruint32(Ctx);
616       if (!isValidGlobalIndex(Info.ElementIndex) ||
617           IsDefined != isDefinedGlobalIndex(Info.ElementIndex))
618         return make_error<GenericBinaryError>("invalid global symbol index",
619                                               object_error::parse_failed);
620       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
621                             wasm::WASM_SYMBOL_BINDING_WEAK)
622         return make_error<GenericBinaryError>("undefined weak global symbol",
623                                               object_error::parse_failed);
624       if (IsDefined) {
625         Info.Name = readString(Ctx);
626         unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;
627         wasm::WasmGlobal &Global = Globals[GlobalIndex];
628         GlobalType = &Global.Type;
629         if (Global.SymbolName.empty())
630           Global.SymbolName = Info.Name;
631       } else {
632         wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];
633         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
634           Info.Name = readString(Ctx);
635           Info.ImportName = Import.Field;
636         } else {
637           Info.Name = Import.Field;
638         }
639         GlobalType = &Import.Global;
640         if (!Import.Module.empty()) {
641           Info.ImportModule = Import.Module;
642         }
643       }
644       break;
645 
646     case wasm::WASM_SYMBOL_TYPE_TABLE:
647       Info.ElementIndex = readVaruint32(Ctx);
648       if (!isValidTableNumber(Info.ElementIndex) ||
649           IsDefined != isDefinedTableNumber(Info.ElementIndex))
650         return make_error<GenericBinaryError>("invalid table symbol index",
651                                               object_error::parse_failed);
652       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
653                             wasm::WASM_SYMBOL_BINDING_WEAK)
654         return make_error<GenericBinaryError>("undefined weak table symbol",
655                                               object_error::parse_failed);
656       if (IsDefined) {
657         Info.Name = readString(Ctx);
658         unsigned TableNumber = Info.ElementIndex - NumImportedTables;
659         wasm::WasmTable &Table = Tables[TableNumber];
660         TableType = &Table.Type;
661         if (Table.SymbolName.empty())
662           Table.SymbolName = Info.Name;
663       } else {
664         wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex];
665         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
666           Info.Name = readString(Ctx);
667           Info.ImportName = Import.Field;
668         } else {
669           Info.Name = Import.Field;
670         }
671         TableType = &Import.Table;
672         if (!Import.Module.empty()) {
673           Info.ImportModule = Import.Module;
674         }
675       }
676       break;
677 
678     case wasm::WASM_SYMBOL_TYPE_DATA:
679       Info.Name = readString(Ctx);
680       if (IsDefined) {
681         auto Index = readVaruint32(Ctx);
682         if (Index >= DataSegments.size())
683           return make_error<GenericBinaryError>("invalid data symbol index",
684                                                 object_error::parse_failed);
685         auto Offset = readVaruint64(Ctx);
686         auto Size = readVaruint64(Ctx);
687         size_t SegmentSize = DataSegments[Index].Data.Content.size();
688         if (Offset > SegmentSize)
689           return make_error<GenericBinaryError>(
690               "invalid data symbol offset: `" + Info.Name + "` (offset: " +
691                   Twine(Offset) + " segment size: " + Twine(SegmentSize) + ")",
692               object_error::parse_failed);
693         Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
694       }
695       break;
696 
697     case wasm::WASM_SYMBOL_TYPE_SECTION: {
698       if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
699           wasm::WASM_SYMBOL_BINDING_LOCAL)
700         return make_error<GenericBinaryError>(
701             "section symbols must have local binding",
702             object_error::parse_failed);
703       Info.ElementIndex = readVaruint32(Ctx);
704       // Use somewhat unique section name as symbol name.
705       StringRef SectionName = Sections[Info.ElementIndex].Name;
706       Info.Name = SectionName;
707       break;
708     }
709 
710     case wasm::WASM_SYMBOL_TYPE_TAG: {
711       Info.ElementIndex = readVaruint32(Ctx);
712       if (!isValidTagIndex(Info.ElementIndex) ||
713           IsDefined != isDefinedTagIndex(Info.ElementIndex))
714         return make_error<GenericBinaryError>("invalid tag symbol index",
715                                               object_error::parse_failed);
716       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
717                             wasm::WASM_SYMBOL_BINDING_WEAK)
718         return make_error<GenericBinaryError>("undefined weak global symbol",
719                                               object_error::parse_failed);
720       if (IsDefined) {
721         Info.Name = readString(Ctx);
722         unsigned TagIndex = Info.ElementIndex - NumImportedTags;
723         wasm::WasmTag &Tag = Tags[TagIndex];
724         Signature = &Signatures[Tag.Type.SigIndex];
725         TagType = &Tag.Type;
726         if (Tag.SymbolName.empty())
727           Tag.SymbolName = Info.Name;
728 
729       } else {
730         wasm::WasmImport &Import = *ImportedTags[Info.ElementIndex];
731         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
732           Info.Name = readString(Ctx);
733           Info.ImportName = Import.Field;
734         } else {
735           Info.Name = Import.Field;
736         }
737         TagType = &Import.Tag;
738         Signature = &Signatures[TagType->SigIndex];
739         if (!Import.Module.empty()) {
740           Info.ImportModule = Import.Module;
741         }
742       }
743       break;
744     }
745 
746     default:
747       return make_error<GenericBinaryError>("invalid symbol type: " +
748                                                 Twine(unsigned(Info.Kind)),
749                                             object_error::parse_failed);
750     }
751 
752     if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
753             wasm::WASM_SYMBOL_BINDING_LOCAL &&
754         !SymbolNames.insert(Info.Name).second)
755       return make_error<GenericBinaryError>("duplicate symbol name " +
756                                                 Twine(Info.Name),
757                                             object_error::parse_failed);
758     LinkingData.SymbolTable.emplace_back(Info);
759     Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType, TableType,
760                          TagType, Signature);
761     LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
762   }
763 
764   return Error::success();
765 }
766 
767 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {
768   uint32_t ComdatCount = readVaruint32(Ctx);
769   StringSet<> ComdatSet;
770   for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {
771     StringRef Name = readString(Ctx);
772     if (Name.empty() || !ComdatSet.insert(Name).second)
773       return make_error<GenericBinaryError>("bad/duplicate COMDAT name " +
774                                                 Twine(Name),
775                                             object_error::parse_failed);
776     LinkingData.Comdats.emplace_back(Name);
777     uint32_t Flags = readVaruint32(Ctx);
778     if (Flags != 0)
779       return make_error<GenericBinaryError>("unsupported COMDAT flags",
780                                             object_error::parse_failed);
781 
782     uint32_t EntryCount = readVaruint32(Ctx);
783     while (EntryCount--) {
784       unsigned Kind = readVaruint32(Ctx);
785       unsigned Index = readVaruint32(Ctx);
786       switch (Kind) {
787       default:
788         return make_error<GenericBinaryError>("invalid COMDAT entry type",
789                                               object_error::parse_failed);
790       case wasm::WASM_COMDAT_DATA:
791         if (Index >= DataSegments.size())
792           return make_error<GenericBinaryError>(
793               "COMDAT data index out of range", object_error::parse_failed);
794         if (DataSegments[Index].Data.Comdat != UINT32_MAX)
795           return make_error<GenericBinaryError>("data segment in two COMDATs",
796                                                 object_error::parse_failed);
797         DataSegments[Index].Data.Comdat = ComdatIndex;
798         break;
799       case wasm::WASM_COMDAT_FUNCTION:
800         if (!isDefinedFunctionIndex(Index))
801           return make_error<GenericBinaryError>(
802               "COMDAT function index out of range", object_error::parse_failed);
803         if (getDefinedFunction(Index).Comdat != UINT32_MAX)
804           return make_error<GenericBinaryError>("function in two COMDATs",
805                                                 object_error::parse_failed);
806         getDefinedFunction(Index).Comdat = ComdatIndex;
807         break;
808       case wasm::WASM_COMDAT_SECTION:
809         if (Index >= Sections.size())
810           return make_error<GenericBinaryError>(
811               "COMDAT section index out of range", object_error::parse_failed);
812         if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM)
813           return make_error<GenericBinaryError>(
814               "non-custom section in a COMDAT", object_error::parse_failed);
815         Sections[Index].Comdat = ComdatIndex;
816         break;
817       }
818     }
819   }
820   return Error::success();
821 }
822 
823 Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) {
824   llvm::SmallSet<StringRef, 3> FieldsSeen;
825   uint32_t Fields = readVaruint32(Ctx);
826   for (size_t I = 0; I < Fields; ++I) {
827     StringRef FieldName = readString(Ctx);
828     if (!FieldsSeen.insert(FieldName).second)
829       return make_error<GenericBinaryError>(
830           "producers section does not have unique fields",
831           object_error::parse_failed);
832     std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr;
833     if (FieldName == "language") {
834       ProducerVec = &ProducerInfo.Languages;
835     } else if (FieldName == "processed-by") {
836       ProducerVec = &ProducerInfo.Tools;
837     } else if (FieldName == "sdk") {
838       ProducerVec = &ProducerInfo.SDKs;
839     } else {
840       return make_error<GenericBinaryError>(
841           "producers section field is not named one of language, processed-by, "
842           "or sdk",
843           object_error::parse_failed);
844     }
845     uint32_t ValueCount = readVaruint32(Ctx);
846     llvm::SmallSet<StringRef, 8> ProducersSeen;
847     for (size_t J = 0; J < ValueCount; ++J) {
848       StringRef Name = readString(Ctx);
849       StringRef Version = readString(Ctx);
850       if (!ProducersSeen.insert(Name).second) {
851         return make_error<GenericBinaryError>(
852             "producers section contains repeated producer",
853             object_error::parse_failed);
854       }
855       ProducerVec->emplace_back(std::string(Name), std::string(Version));
856     }
857   }
858   if (Ctx.Ptr != Ctx.End)
859     return make_error<GenericBinaryError>("producers section ended prematurely",
860                                           object_error::parse_failed);
861   return Error::success();
862 }
863 
864 Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) {
865   llvm::SmallSet<std::string, 8> FeaturesSeen;
866   uint32_t FeatureCount = readVaruint32(Ctx);
867   for (size_t I = 0; I < FeatureCount; ++I) {
868     wasm::WasmFeatureEntry Feature;
869     Feature.Prefix = readUint8(Ctx);
870     switch (Feature.Prefix) {
871     case wasm::WASM_FEATURE_PREFIX_USED:
872     case wasm::WASM_FEATURE_PREFIX_REQUIRED:
873     case wasm::WASM_FEATURE_PREFIX_DISALLOWED:
874       break;
875     default:
876       return make_error<GenericBinaryError>("unknown feature policy prefix",
877                                             object_error::parse_failed);
878     }
879     Feature.Name = std::string(readString(Ctx));
880     if (!FeaturesSeen.insert(Feature.Name).second)
881       return make_error<GenericBinaryError>(
882           "target features section contains repeated feature \"" +
883               Feature.Name + "\"",
884           object_error::parse_failed);
885     TargetFeatures.push_back(Feature);
886   }
887   if (Ctx.Ptr != Ctx.End)
888     return make_error<GenericBinaryError>(
889         "target features section ended prematurely",
890         object_error::parse_failed);
891   return Error::success();
892 }
893 
894 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {
895   uint32_t SectionIndex = readVaruint32(Ctx);
896   if (SectionIndex >= Sections.size())
897     return make_error<GenericBinaryError>("invalid section index",
898                                           object_error::parse_failed);
899   WasmSection &Section = Sections[SectionIndex];
900   uint32_t RelocCount = readVaruint32(Ctx);
901   uint32_t EndOffset = Section.Content.size();
902   uint32_t PreviousOffset = 0;
903   while (RelocCount--) {
904     wasm::WasmRelocation Reloc = {};
905     uint32_t type = readVaruint32(Ctx);
906     Reloc.Type = type;
907     Reloc.Offset = readVaruint32(Ctx);
908     if (Reloc.Offset < PreviousOffset)
909       return make_error<GenericBinaryError>("relocations not in offset order",
910                                             object_error::parse_failed);
911     PreviousOffset = Reloc.Offset;
912     Reloc.Index = readVaruint32(Ctx);
913     switch (type) {
914     case wasm::R_WASM_FUNCTION_INDEX_LEB:
915     case wasm::R_WASM_TABLE_INDEX_SLEB:
916     case wasm::R_WASM_TABLE_INDEX_SLEB64:
917     case wasm::R_WASM_TABLE_INDEX_I32:
918     case wasm::R_WASM_TABLE_INDEX_I64:
919     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
920     case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
921       if (!isValidFunctionSymbol(Reloc.Index))
922         return make_error<GenericBinaryError>(
923             "invalid relocation function index", object_error::parse_failed);
924       break;
925     case wasm::R_WASM_TABLE_NUMBER_LEB:
926       if (!isValidTableSymbol(Reloc.Index))
927         return make_error<GenericBinaryError>("invalid relocation table index",
928                                               object_error::parse_failed);
929       break;
930     case wasm::R_WASM_TYPE_INDEX_LEB:
931       if (Reloc.Index >= Signatures.size())
932         return make_error<GenericBinaryError>("invalid relocation type index",
933                                               object_error::parse_failed);
934       break;
935     case wasm::R_WASM_GLOBAL_INDEX_LEB:
936       // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data
937       // symbols to refer to their GOT entries.
938       if (!isValidGlobalSymbol(Reloc.Index) &&
939           !isValidDataSymbol(Reloc.Index) &&
940           !isValidFunctionSymbol(Reloc.Index))
941         return make_error<GenericBinaryError>("invalid relocation global index",
942                                               object_error::parse_failed);
943       break;
944     case wasm::R_WASM_GLOBAL_INDEX_I32:
945       if (!isValidGlobalSymbol(Reloc.Index))
946         return make_error<GenericBinaryError>("invalid relocation global index",
947                                               object_error::parse_failed);
948       break;
949     case wasm::R_WASM_TAG_INDEX_LEB:
950       if (!isValidTagSymbol(Reloc.Index))
951         return make_error<GenericBinaryError>("invalid relocation tag index",
952                                               object_error::parse_failed);
953       break;
954     case wasm::R_WASM_MEMORY_ADDR_LEB:
955     case wasm::R_WASM_MEMORY_ADDR_SLEB:
956     case wasm::R_WASM_MEMORY_ADDR_I32:
957     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
958     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
959     case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
960       if (!isValidDataSymbol(Reloc.Index))
961         return make_error<GenericBinaryError>("invalid relocation data index",
962                                               object_error::parse_failed);
963       Reloc.Addend = readVarint32(Ctx);
964       break;
965     case wasm::R_WASM_MEMORY_ADDR_LEB64:
966     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
967     case wasm::R_WASM_MEMORY_ADDR_I64:
968     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
969     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
970       if (!isValidDataSymbol(Reloc.Index))
971         return make_error<GenericBinaryError>("invalid relocation data index",
972                                               object_error::parse_failed);
973       Reloc.Addend = readVarint64(Ctx);
974       break;
975     case wasm::R_WASM_FUNCTION_OFFSET_I32:
976       if (!isValidFunctionSymbol(Reloc.Index))
977         return make_error<GenericBinaryError>(
978             "invalid relocation function index", object_error::parse_failed);
979       Reloc.Addend = readVarint32(Ctx);
980       break;
981     case wasm::R_WASM_FUNCTION_OFFSET_I64:
982       if (!isValidFunctionSymbol(Reloc.Index))
983         return make_error<GenericBinaryError>(
984             "invalid relocation function index", object_error::parse_failed);
985       Reloc.Addend = readVarint64(Ctx);
986       break;
987     case wasm::R_WASM_SECTION_OFFSET_I32:
988       if (!isValidSectionSymbol(Reloc.Index))
989         return make_error<GenericBinaryError>(
990             "invalid relocation section index", object_error::parse_failed);
991       Reloc.Addend = readVarint32(Ctx);
992       break;
993     default:
994       return make_error<GenericBinaryError>("invalid relocation type: " +
995                                                 Twine(type),
996                                             object_error::parse_failed);
997     }
998 
999     // Relocations must fit inside the section, and must appear in order.  They
1000     // also shouldn't overlap a function/element boundary, but we don't bother
1001     // to check that.
1002     uint64_t Size = 5;
1003     if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 ||
1004         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 ||
1005         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64)
1006       Size = 10;
1007     if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 ||
1008         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 ||
1009         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LOCREL_I32 ||
1010         Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 ||
1011         Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
1012         Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32)
1013       Size = 4;
1014     if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 ||
1015         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 ||
1016         Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64)
1017       Size = 8;
1018     if (Reloc.Offset + Size > EndOffset)
1019       return make_error<GenericBinaryError>("invalid relocation offset",
1020                                             object_error::parse_failed);
1021 
1022     Section.Relocations.push_back(Reloc);
1023   }
1024   if (Ctx.Ptr != Ctx.End)
1025     return make_error<GenericBinaryError>("reloc section ended prematurely",
1026                                           object_error::parse_failed);
1027   return Error::success();
1028 }
1029 
1030 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {
1031   if (Sec.Name == "dylink") {
1032     if (Error Err = parseDylinkSection(Ctx))
1033       return Err;
1034   } else if (Sec.Name == "dylink.0") {
1035     if (Error Err = parseDylink0Section(Ctx))
1036       return Err;
1037   } else if (Sec.Name == "name") {
1038     if (Error Err = parseNameSection(Ctx))
1039       return Err;
1040   } else if (Sec.Name == "linking") {
1041     if (Error Err = parseLinkingSection(Ctx))
1042       return Err;
1043   } else if (Sec.Name == "producers") {
1044     if (Error Err = parseProducersSection(Ctx))
1045       return Err;
1046   } else if (Sec.Name == "target_features") {
1047     if (Error Err = parseTargetFeaturesSection(Ctx))
1048       return Err;
1049   } else if (Sec.Name.startswith("reloc.")) {
1050     if (Error Err = parseRelocSection(Sec.Name, Ctx))
1051       return Err;
1052   }
1053   return Error::success();
1054 }
1055 
1056 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {
1057   uint32_t Count = readVaruint32(Ctx);
1058   Signatures.reserve(Count);
1059   while (Count--) {
1060     wasm::WasmSignature Sig;
1061     uint8_t Form = readUint8(Ctx);
1062     if (Form != wasm::WASM_TYPE_FUNC) {
1063       return make_error<GenericBinaryError>("invalid signature type",
1064                                             object_error::parse_failed);
1065     }
1066     uint32_t ParamCount = readVaruint32(Ctx);
1067     Sig.Params.reserve(ParamCount);
1068     while (ParamCount--) {
1069       uint32_t ParamType = readUint8(Ctx);
1070       Sig.Params.push_back(wasm::ValType(ParamType));
1071     }
1072     uint32_t ReturnCount = readVaruint32(Ctx);
1073     while (ReturnCount--) {
1074       uint32_t ReturnType = readUint8(Ctx);
1075       Sig.Returns.push_back(wasm::ValType(ReturnType));
1076     }
1077     Signatures.push_back(std::move(Sig));
1078   }
1079   if (Ctx.Ptr != Ctx.End)
1080     return make_error<GenericBinaryError>("type section ended prematurely",
1081                                           object_error::parse_failed);
1082   return Error::success();
1083 }
1084 
1085 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {
1086   uint32_t Count = readVaruint32(Ctx);
1087   Imports.reserve(Count);
1088   for (uint32_t I = 0; I < Count; I++) {
1089     wasm::WasmImport Im;
1090     Im.Module = readString(Ctx);
1091     Im.Field = readString(Ctx);
1092     Im.Kind = readUint8(Ctx);
1093     switch (Im.Kind) {
1094     case wasm::WASM_EXTERNAL_FUNCTION:
1095       NumImportedFunctions++;
1096       Im.SigIndex = readVaruint32(Ctx);
1097       break;
1098     case wasm::WASM_EXTERNAL_GLOBAL:
1099       NumImportedGlobals++;
1100       Im.Global.Type = readUint8(Ctx);
1101       Im.Global.Mutable = readVaruint1(Ctx);
1102       break;
1103     case wasm::WASM_EXTERNAL_MEMORY:
1104       Im.Memory = readLimits(Ctx);
1105       if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
1106         HasMemory64 = true;
1107       break;
1108     case wasm::WASM_EXTERNAL_TABLE: {
1109       Im.Table = readTableType(Ctx);
1110       NumImportedTables++;
1111       auto ElemType = Im.Table.ElemType;
1112       if (ElemType != wasm::WASM_TYPE_FUNCREF &&
1113           ElemType != wasm::WASM_TYPE_EXTERNREF)
1114         return make_error<GenericBinaryError>("invalid table element type",
1115                                               object_error::parse_failed);
1116       break;
1117     }
1118     case wasm::WASM_EXTERNAL_TAG:
1119       NumImportedTags++;
1120       Im.Tag.Attribute = readUint8(Ctx);
1121       Im.Tag.SigIndex = readVarint32(Ctx);
1122       break;
1123     default:
1124       return make_error<GenericBinaryError>("unexpected import kind",
1125                                             object_error::parse_failed);
1126     }
1127     Imports.push_back(Im);
1128   }
1129   if (Ctx.Ptr != Ctx.End)
1130     return make_error<GenericBinaryError>("import section ended prematurely",
1131                                           object_error::parse_failed);
1132   return Error::success();
1133 }
1134 
1135 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {
1136   uint32_t Count = readVaruint32(Ctx);
1137   FunctionTypes.reserve(Count);
1138   Functions.resize(Count);
1139   uint32_t NumTypes = Signatures.size();
1140   while (Count--) {
1141     uint32_t Type = readVaruint32(Ctx);
1142     if (Type >= NumTypes)
1143       return make_error<GenericBinaryError>("invalid function type",
1144                                             object_error::parse_failed);
1145     FunctionTypes.push_back(Type);
1146   }
1147   if (Ctx.Ptr != Ctx.End)
1148     return make_error<GenericBinaryError>("function section ended prematurely",
1149                                           object_error::parse_failed);
1150   return Error::success();
1151 }
1152 
1153 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {
1154   TableSection = Sections.size();
1155   uint32_t Count = readVaruint32(Ctx);
1156   Tables.reserve(Count);
1157   while (Count--) {
1158     wasm::WasmTable T;
1159     T.Type = readTableType(Ctx);
1160     T.Index = NumImportedTables + Tables.size();
1161     Tables.push_back(T);
1162     auto ElemType = Tables.back().Type.ElemType;
1163     if (ElemType != wasm::WASM_TYPE_FUNCREF &&
1164         ElemType != wasm::WASM_TYPE_EXTERNREF) {
1165       return make_error<GenericBinaryError>("invalid table element type",
1166                                             object_error::parse_failed);
1167     }
1168   }
1169   if (Ctx.Ptr != Ctx.End)
1170     return make_error<GenericBinaryError>("table section ended prematurely",
1171                                           object_error::parse_failed);
1172   return Error::success();
1173 }
1174 
1175 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {
1176   uint32_t Count = readVaruint32(Ctx);
1177   Memories.reserve(Count);
1178   while (Count--) {
1179     auto Limits = readLimits(Ctx);
1180     if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
1181       HasMemory64 = true;
1182     Memories.push_back(Limits);
1183   }
1184   if (Ctx.Ptr != Ctx.End)
1185     return make_error<GenericBinaryError>("memory section ended prematurely",
1186                                           object_error::parse_failed);
1187   return Error::success();
1188 }
1189 
1190 Error WasmObjectFile::parseTagSection(ReadContext &Ctx) {
1191   TagSection = Sections.size();
1192   uint32_t Count = readVaruint32(Ctx);
1193   Tags.reserve(Count);
1194   while (Count--) {
1195     wasm::WasmTag Tag;
1196     Tag.Index = NumImportedTags + Tags.size();
1197     Tag.Type.Attribute = readUint8(Ctx);
1198     Tag.Type.SigIndex = readVaruint32(Ctx);
1199     Tags.push_back(Tag);
1200   }
1201 
1202   if (Ctx.Ptr != Ctx.End)
1203     return make_error<GenericBinaryError>("tag section ended prematurely",
1204                                           object_error::parse_failed);
1205   return Error::success();
1206 }
1207 
1208 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {
1209   GlobalSection = Sections.size();
1210   uint32_t Count = readVaruint32(Ctx);
1211   Globals.reserve(Count);
1212   while (Count--) {
1213     wasm::WasmGlobal Global;
1214     Global.Index = NumImportedGlobals + Globals.size();
1215     Global.Type.Type = readUint8(Ctx);
1216     Global.Type.Mutable = readVaruint1(Ctx);
1217     if (Error Err = readInitExpr(Global.InitExpr, Ctx))
1218       return Err;
1219     Globals.push_back(Global);
1220   }
1221   if (Ctx.Ptr != Ctx.End)
1222     return make_error<GenericBinaryError>("global section ended prematurely",
1223                                           object_error::parse_failed);
1224   return Error::success();
1225 }
1226 
1227 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {
1228   uint32_t Count = readVaruint32(Ctx);
1229   Exports.reserve(Count);
1230   for (uint32_t I = 0; I < Count; I++) {
1231     wasm::WasmExport Ex;
1232     Ex.Name = readString(Ctx);
1233     Ex.Kind = readUint8(Ctx);
1234     Ex.Index = readVaruint32(Ctx);
1235     switch (Ex.Kind) {
1236     case wasm::WASM_EXTERNAL_FUNCTION:
1237 
1238       if (!isDefinedFunctionIndex(Ex.Index))
1239         return make_error<GenericBinaryError>("invalid function export",
1240                                               object_error::parse_failed);
1241       getDefinedFunction(Ex.Index).ExportName = Ex.Name;
1242       break;
1243     case wasm::WASM_EXTERNAL_GLOBAL:
1244       if (!isValidGlobalIndex(Ex.Index))
1245         return make_error<GenericBinaryError>("invalid global export",
1246                                               object_error::parse_failed);
1247       break;
1248     case wasm::WASM_EXTERNAL_TAG:
1249       if (!isValidTagIndex(Ex.Index))
1250         return make_error<GenericBinaryError>("invalid tag export",
1251                                               object_error::parse_failed);
1252       break;
1253     case wasm::WASM_EXTERNAL_MEMORY:
1254     case wasm::WASM_EXTERNAL_TABLE:
1255       break;
1256     default:
1257       return make_error<GenericBinaryError>("unexpected export kind",
1258                                             object_error::parse_failed);
1259     }
1260     Exports.push_back(Ex);
1261   }
1262   if (Ctx.Ptr != Ctx.End)
1263     return make_error<GenericBinaryError>("export section ended prematurely",
1264                                           object_error::parse_failed);
1265   return Error::success();
1266 }
1267 
1268 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
1269   return Index < NumImportedFunctions + FunctionTypes.size();
1270 }
1271 
1272 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {
1273   return Index >= NumImportedFunctions && isValidFunctionIndex(Index);
1274 }
1275 
1276 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {
1277   return Index < NumImportedGlobals + Globals.size();
1278 }
1279 
1280 bool WasmObjectFile::isValidTableNumber(uint32_t Index) const {
1281   return Index < NumImportedTables + Tables.size();
1282 }
1283 
1284 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {
1285   return Index >= NumImportedGlobals && isValidGlobalIndex(Index);
1286 }
1287 
1288 bool WasmObjectFile::isDefinedTableNumber(uint32_t Index) const {
1289   return Index >= NumImportedTables && isValidTableNumber(Index);
1290 }
1291 
1292 bool WasmObjectFile::isValidTagIndex(uint32_t Index) const {
1293   return Index < NumImportedTags + Tags.size();
1294 }
1295 
1296 bool WasmObjectFile::isDefinedTagIndex(uint32_t Index) const {
1297   return Index >= NumImportedTags && isValidTagIndex(Index);
1298 }
1299 
1300 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {
1301   return Index < Symbols.size() && Symbols[Index].isTypeFunction();
1302 }
1303 
1304 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const {
1305   return Index < Symbols.size() && Symbols[Index].isTypeTable();
1306 }
1307 
1308 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {
1309   return Index < Symbols.size() && Symbols[Index].isTypeGlobal();
1310 }
1311 
1312 bool WasmObjectFile::isValidTagSymbol(uint32_t Index) const {
1313   return Index < Symbols.size() && Symbols[Index].isTypeTag();
1314 }
1315 
1316 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {
1317   return Index < Symbols.size() && Symbols[Index].isTypeData();
1318 }
1319 
1320 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {
1321   return Index < Symbols.size() && Symbols[Index].isTypeSection();
1322 }
1323 
1324 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {
1325   assert(isDefinedFunctionIndex(Index));
1326   return Functions[Index - NumImportedFunctions];
1327 }
1328 
1329 const wasm::WasmFunction &
1330 WasmObjectFile::getDefinedFunction(uint32_t Index) const {
1331   assert(isDefinedFunctionIndex(Index));
1332   return Functions[Index - NumImportedFunctions];
1333 }
1334 
1335 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) {
1336   assert(isDefinedGlobalIndex(Index));
1337   return Globals[Index - NumImportedGlobals];
1338 }
1339 
1340 wasm::WasmTag &WasmObjectFile::getDefinedTag(uint32_t Index) {
1341   assert(isDefinedTagIndex(Index));
1342   return Tags[Index - NumImportedTags];
1343 }
1344 
1345 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {
1346   StartFunction = readVaruint32(Ctx);
1347   if (!isValidFunctionIndex(StartFunction))
1348     return make_error<GenericBinaryError>("invalid start function",
1349                                           object_error::parse_failed);
1350   return Error::success();
1351 }
1352 
1353 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {
1354   SeenCodeSection = true;
1355   CodeSection = Sections.size();
1356   uint32_t FunctionCount = readVaruint32(Ctx);
1357   if (FunctionCount != FunctionTypes.size()) {
1358     return make_error<GenericBinaryError>("invalid function count",
1359                                           object_error::parse_failed);
1360   }
1361 
1362   for (uint32_t i = 0; i < FunctionCount; i++) {
1363     wasm::WasmFunction& Function = Functions[i];
1364     const uint8_t *FunctionStart = Ctx.Ptr;
1365     uint32_t Size = readVaruint32(Ctx);
1366     const uint8_t *FunctionEnd = Ctx.Ptr + Size;
1367 
1368     Function.CodeOffset = Ctx.Ptr - FunctionStart;
1369     Function.Index = NumImportedFunctions + i;
1370     Function.CodeSectionOffset = FunctionStart - Ctx.Start;
1371     Function.Size = FunctionEnd - FunctionStart;
1372 
1373     uint32_t NumLocalDecls = readVaruint32(Ctx);
1374     Function.Locals.reserve(NumLocalDecls);
1375     while (NumLocalDecls--) {
1376       wasm::WasmLocalDecl Decl;
1377       Decl.Count = readVaruint32(Ctx);
1378       Decl.Type = readUint8(Ctx);
1379       Function.Locals.push_back(Decl);
1380     }
1381 
1382     uint32_t BodySize = FunctionEnd - Ctx.Ptr;
1383     Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);
1384     // This will be set later when reading in the linking metadata section.
1385     Function.Comdat = UINT32_MAX;
1386     Ctx.Ptr += BodySize;
1387     assert(Ctx.Ptr == FunctionEnd);
1388   }
1389   if (Ctx.Ptr != Ctx.End)
1390     return make_error<GenericBinaryError>("code section ended prematurely",
1391                                           object_error::parse_failed);
1392   return Error::success();
1393 }
1394 
1395 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {
1396   uint32_t Count = readVaruint32(Ctx);
1397   ElemSegments.reserve(Count);
1398   while (Count--) {
1399     wasm::WasmElemSegment Segment;
1400     Segment.Flags = readVaruint32(Ctx);
1401 
1402     uint32_t SupportedFlags = wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER |
1403                               wasm::WASM_ELEM_SEGMENT_IS_PASSIVE |
1404                               wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS;
1405     if (Segment.Flags & ~SupportedFlags)
1406       return make_error<GenericBinaryError>(
1407           "Unsupported flags for element segment", object_error::parse_failed);
1408 
1409     if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
1410       Segment.TableNumber = readVaruint32(Ctx);
1411     else
1412       Segment.TableNumber = 0;
1413     if (!isValidTableNumber(Segment.TableNumber))
1414       return make_error<GenericBinaryError>("invalid TableNumber",
1415                                             object_error::parse_failed);
1416 
1417     if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_PASSIVE) {
1418       Segment.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST;
1419       Segment.Offset.Value.Int32 = 0;
1420     } else {
1421       if (Error Err = readInitExpr(Segment.Offset, Ctx))
1422         return Err;
1423     }
1424 
1425     if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) {
1426       Segment.ElemKind = readUint8(Ctx);
1427       if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) {
1428         if (Segment.ElemKind != uint8_t(wasm::ValType::FUNCREF) &&
1429             Segment.ElemKind != uint8_t(wasm::ValType::EXTERNREF)) {
1430           return make_error<GenericBinaryError>("invalid reference type",
1431                                                 object_error::parse_failed);
1432         }
1433       } else {
1434         if (Segment.ElemKind != 0)
1435           return make_error<GenericBinaryError>("invalid elemtype",
1436                                                 object_error::parse_failed);
1437         Segment.ElemKind = uint8_t(wasm::ValType::FUNCREF);
1438       }
1439     } else {
1440       Segment.ElemKind = uint8_t(wasm::ValType::FUNCREF);
1441     }
1442 
1443     if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS)
1444       return make_error<GenericBinaryError>(
1445           "elem segment init expressions not yet implemented",
1446           object_error::parse_failed);
1447 
1448     uint32_t NumElems = readVaruint32(Ctx);
1449     while (NumElems--) {
1450       Segment.Functions.push_back(readVaruint32(Ctx));
1451     }
1452     ElemSegments.push_back(Segment);
1453   }
1454   if (Ctx.Ptr != Ctx.End)
1455     return make_error<GenericBinaryError>("elem section ended prematurely",
1456                                           object_error::parse_failed);
1457   return Error::success();
1458 }
1459 
1460 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {
1461   DataSection = Sections.size();
1462   uint32_t Count = readVaruint32(Ctx);
1463   if (DataCount && Count != DataCount.getValue())
1464     return make_error<GenericBinaryError>(
1465         "number of data segments does not match DataCount section");
1466   DataSegments.reserve(Count);
1467   while (Count--) {
1468     WasmSegment Segment;
1469     Segment.Data.InitFlags = readVaruint32(Ctx);
1470     Segment.Data.MemoryIndex =
1471         (Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
1472             ? readVaruint32(Ctx)
1473             : 0;
1474     if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
1475       if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
1476         return Err;
1477     } else {
1478       Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST;
1479       Segment.Data.Offset.Value.Int32 = 0;
1480     }
1481     uint32_t Size = readVaruint32(Ctx);
1482     if (Size > (size_t)(Ctx.End - Ctx.Ptr))
1483       return make_error<GenericBinaryError>("invalid segment size",
1484                                             object_error::parse_failed);
1485     Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
1486     // The rest of these Data fields are set later, when reading in the linking
1487     // metadata section.
1488     Segment.Data.Alignment = 0;
1489     Segment.Data.LinkingFlags = 0;
1490     Segment.Data.Comdat = UINT32_MAX;
1491     Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
1492     Ctx.Ptr += Size;
1493     DataSegments.push_back(Segment);
1494   }
1495   if (Ctx.Ptr != Ctx.End)
1496     return make_error<GenericBinaryError>("data section ended prematurely",
1497                                           object_error::parse_failed);
1498   return Error::success();
1499 }
1500 
1501 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {
1502   DataCount = readVaruint32(Ctx);
1503   return Error::success();
1504 }
1505 
1506 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
1507   return Header;
1508 }
1509 
1510 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }
1511 
1512 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
1513   uint32_t Result = SymbolRef::SF_None;
1514   const WasmSymbol &Sym = getWasmSymbol(Symb);
1515 
1516   LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
1517   if (Sym.isBindingWeak())
1518     Result |= SymbolRef::SF_Weak;
1519   if (!Sym.isBindingLocal())
1520     Result |= SymbolRef::SF_Global;
1521   if (Sym.isHidden())
1522     Result |= SymbolRef::SF_Hidden;
1523   if (!Sym.isDefined())
1524     Result |= SymbolRef::SF_Undefined;
1525   if (Sym.isTypeFunction())
1526     Result |= SymbolRef::SF_Executable;
1527   return Result;
1528 }
1529 
1530 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
1531   DataRefImpl Ref;
1532   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1533   Ref.d.b = 0; // Symbol index
1534   return BasicSymbolRef(Ref, this);
1535 }
1536 
1537 basic_symbol_iterator WasmObjectFile::symbol_end() const {
1538   DataRefImpl Ref;
1539   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1540   Ref.d.b = Symbols.size(); // Symbol index
1541   return BasicSymbolRef(Ref, this);
1542 }
1543 
1544 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
1545   return Symbols[Symb.d.b];
1546 }
1547 
1548 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
1549   return getWasmSymbol(Symb.getRawDataRefImpl());
1550 }
1551 
1552 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
1553   return getWasmSymbol(Symb).Info.Name;
1554 }
1555 
1556 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
1557   auto &Sym = getWasmSymbol(Symb);
1558   if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&
1559       isDefinedFunctionIndex(Sym.Info.ElementIndex))
1560     return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset;
1561   else
1562     return getSymbolValue(Symb);
1563 }
1564 
1565 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {
1566   switch (Sym.Info.Kind) {
1567   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1568   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1569   case wasm::WASM_SYMBOL_TYPE_TAG:
1570   case wasm::WASM_SYMBOL_TYPE_TABLE:
1571     return Sym.Info.ElementIndex;
1572   case wasm::WASM_SYMBOL_TYPE_DATA: {
1573     // The value of a data symbol is the segment offset, plus the symbol
1574     // offset within the segment.
1575     uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
1576     const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
1577     if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) {
1578       return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset;
1579     } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) {
1580       return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset;
1581     } else {
1582       llvm_unreachable("unknown init expr opcode");
1583     }
1584   }
1585   case wasm::WASM_SYMBOL_TYPE_SECTION:
1586     return 0;
1587   }
1588   llvm_unreachable("invalid symbol type");
1589 }
1590 
1591 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
1592   return getWasmSymbolValue(getWasmSymbol(Symb));
1593 }
1594 
1595 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
1596   llvm_unreachable("not yet implemented");
1597   return 0;
1598 }
1599 
1600 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
1601   llvm_unreachable("not yet implemented");
1602   return 0;
1603 }
1604 
1605 Expected<SymbolRef::Type>
1606 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
1607   const WasmSymbol &Sym = getWasmSymbol(Symb);
1608 
1609   switch (Sym.Info.Kind) {
1610   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1611     return SymbolRef::ST_Function;
1612   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1613     return SymbolRef::ST_Other;
1614   case wasm::WASM_SYMBOL_TYPE_DATA:
1615     return SymbolRef::ST_Data;
1616   case wasm::WASM_SYMBOL_TYPE_SECTION:
1617     return SymbolRef::ST_Debug;
1618   case wasm::WASM_SYMBOL_TYPE_TAG:
1619     return SymbolRef::ST_Other;
1620   case wasm::WASM_SYMBOL_TYPE_TABLE:
1621     return SymbolRef::ST_Other;
1622   }
1623 
1624   llvm_unreachable("unknown WasmSymbol::SymbolType");
1625   return SymbolRef::ST_Other;
1626 }
1627 
1628 Expected<section_iterator>
1629 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
1630   const WasmSymbol &Sym = getWasmSymbol(Symb);
1631   if (Sym.isUndefined())
1632     return section_end();
1633 
1634   DataRefImpl Ref;
1635   Ref.d.a = getSymbolSectionIdImpl(Sym);
1636   return section_iterator(SectionRef(Ref, this));
1637 }
1638 
1639 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {
1640   const WasmSymbol &Sym = getWasmSymbol(Symb);
1641   return getSymbolSectionIdImpl(Sym);
1642 }
1643 
1644 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {
1645   switch (Sym.Info.Kind) {
1646   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1647     return CodeSection;
1648   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1649     return GlobalSection;
1650   case wasm::WASM_SYMBOL_TYPE_DATA:
1651     return DataSection;
1652   case wasm::WASM_SYMBOL_TYPE_SECTION:
1653     return Sym.Info.ElementIndex;
1654   case wasm::WASM_SYMBOL_TYPE_TAG:
1655     return TagSection;
1656   case wasm::WASM_SYMBOL_TYPE_TABLE:
1657     return TableSection;
1658   default:
1659     llvm_unreachable("unknown WasmSymbol::SymbolType");
1660   }
1661 }
1662 
1663 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
1664 
1665 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {
1666   const WasmSection &S = Sections[Sec.d.a];
1667 #define ECase(X)                                                               \
1668   case wasm::WASM_SEC_##X:                                                     \
1669     return #X;
1670   switch (S.Type) {
1671     ECase(TYPE);
1672     ECase(IMPORT);
1673     ECase(FUNCTION);
1674     ECase(TABLE);
1675     ECase(MEMORY);
1676     ECase(GLOBAL);
1677     ECase(TAG);
1678     ECase(EXPORT);
1679     ECase(START);
1680     ECase(ELEM);
1681     ECase(CODE);
1682     ECase(DATA);
1683     ECase(DATACOUNT);
1684   case wasm::WASM_SEC_CUSTOM:
1685     return S.Name;
1686   default:
1687     return createStringError(object_error::invalid_section_index, "");
1688   }
1689 #undef ECase
1690 }
1691 
1692 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
1693 
1694 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
1695   return Sec.d.a;
1696 }
1697 
1698 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
1699   const WasmSection &S = Sections[Sec.d.a];
1700   return S.Content.size();
1701 }
1702 
1703 Expected<ArrayRef<uint8_t>>
1704 WasmObjectFile::getSectionContents(DataRefImpl Sec) const {
1705   const WasmSection &S = Sections[Sec.d.a];
1706   // This will never fail since wasm sections can never be empty (user-sections
1707   // must have a name and non-user sections each have a defined structure).
1708   return S.Content;
1709 }
1710 
1711 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1712   return 1;
1713 }
1714 
1715 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1716   return false;
1717 }
1718 
1719 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
1720   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
1721 }
1722 
1723 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
1724   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
1725 }
1726 
1727 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
1728 
1729 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
1730 
1731 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
1732   DataRefImpl RelocRef;
1733   RelocRef.d.a = Ref.d.a;
1734   RelocRef.d.b = 0;
1735   return relocation_iterator(RelocationRef(RelocRef, this));
1736 }
1737 
1738 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
1739   const WasmSection &Sec = getWasmSection(Ref);
1740   DataRefImpl RelocRef;
1741   RelocRef.d.a = Ref.d.a;
1742   RelocRef.d.b = Sec.Relocations.size();
1743   return relocation_iterator(RelocationRef(RelocRef, this));
1744 }
1745 
1746 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }
1747 
1748 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1749   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1750   return Rel.Offset;
1751 }
1752 
1753 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
1754   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1755   if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)
1756     return symbol_end();
1757   DataRefImpl Sym;
1758   Sym.d.a = 1;
1759   Sym.d.b = Rel.Index;
1760   return symbol_iterator(SymbolRef(Sym, this));
1761 }
1762 
1763 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1764   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1765   return Rel.Type;
1766 }
1767 
1768 void WasmObjectFile::getRelocationTypeName(
1769     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1770   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1771   StringRef Res = "Unknown";
1772 
1773 #define WASM_RELOC(name, value)                                                \
1774   case wasm::name:                                                             \
1775     Res = #name;                                                               \
1776     break;
1777 
1778   switch (Rel.Type) {
1779 #include "llvm/BinaryFormat/WasmRelocs.def"
1780   }
1781 
1782 #undef WASM_RELOC
1783 
1784   Result.append(Res.begin(), Res.end());
1785 }
1786 
1787 section_iterator WasmObjectFile::section_begin() const {
1788   DataRefImpl Ref;
1789   Ref.d.a = 0;
1790   return section_iterator(SectionRef(Ref, this));
1791 }
1792 
1793 section_iterator WasmObjectFile::section_end() const {
1794   DataRefImpl Ref;
1795   Ref.d.a = Sections.size();
1796   return section_iterator(SectionRef(Ref, this));
1797 }
1798 
1799 uint8_t WasmObjectFile::getBytesInAddress() const {
1800   return HasMemory64 ? 8 : 4;
1801 }
1802 
1803 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1804 
1805 Triple::ArchType WasmObjectFile::getArch() const {
1806   return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
1807 }
1808 
1809 SubtargetFeatures WasmObjectFile::getFeatures() const {
1810   return SubtargetFeatures();
1811 }
1812 
1813 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }
1814 
1815 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }
1816 
1817 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1818   assert(Ref.d.a < Sections.size());
1819   return Sections[Ref.d.a];
1820 }
1821 
1822 const WasmSection &
1823 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1824   return getWasmSection(Section.getRawDataRefImpl());
1825 }
1826 
1827 const wasm::WasmRelocation &
1828 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1829   return getWasmRelocation(Ref.getRawDataRefImpl());
1830 }
1831 
1832 const wasm::WasmRelocation &
1833 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1834   assert(Ref.d.a < Sections.size());
1835   const WasmSection &Sec = Sections[Ref.d.a];
1836   assert(Ref.d.b < Sec.Relocations.size());
1837   return Sec.Relocations[Ref.d.b];
1838 }
1839 
1840 int WasmSectionOrderChecker::getSectionOrder(unsigned ID,
1841                                              StringRef CustomSectionName) {
1842   switch (ID) {
1843   case wasm::WASM_SEC_CUSTOM:
1844     return StringSwitch<unsigned>(CustomSectionName)
1845         .Case("dylink", WASM_SEC_ORDER_DYLINK)
1846         .Case("dylink.0", WASM_SEC_ORDER_DYLINK)
1847         .Case("linking", WASM_SEC_ORDER_LINKING)
1848         .StartsWith("reloc.", WASM_SEC_ORDER_RELOC)
1849         .Case("name", WASM_SEC_ORDER_NAME)
1850         .Case("producers", WASM_SEC_ORDER_PRODUCERS)
1851         .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)
1852         .Default(WASM_SEC_ORDER_NONE);
1853   case wasm::WASM_SEC_TYPE:
1854     return WASM_SEC_ORDER_TYPE;
1855   case wasm::WASM_SEC_IMPORT:
1856     return WASM_SEC_ORDER_IMPORT;
1857   case wasm::WASM_SEC_FUNCTION:
1858     return WASM_SEC_ORDER_FUNCTION;
1859   case wasm::WASM_SEC_TABLE:
1860     return WASM_SEC_ORDER_TABLE;
1861   case wasm::WASM_SEC_MEMORY:
1862     return WASM_SEC_ORDER_MEMORY;
1863   case wasm::WASM_SEC_GLOBAL:
1864     return WASM_SEC_ORDER_GLOBAL;
1865   case wasm::WASM_SEC_EXPORT:
1866     return WASM_SEC_ORDER_EXPORT;
1867   case wasm::WASM_SEC_START:
1868     return WASM_SEC_ORDER_START;
1869   case wasm::WASM_SEC_ELEM:
1870     return WASM_SEC_ORDER_ELEM;
1871   case wasm::WASM_SEC_CODE:
1872     return WASM_SEC_ORDER_CODE;
1873   case wasm::WASM_SEC_DATA:
1874     return WASM_SEC_ORDER_DATA;
1875   case wasm::WASM_SEC_DATACOUNT:
1876     return WASM_SEC_ORDER_DATACOUNT;
1877   case wasm::WASM_SEC_TAG:
1878     return WASM_SEC_ORDER_TAG;
1879   default:
1880     return WASM_SEC_ORDER_NONE;
1881   }
1882 }
1883 
1884 // Represents the edges in a directed graph where any node B reachable from node
1885 // A is not allowed to appear before A in the section ordering, but may appear
1886 // afterward.
1887 int WasmSectionOrderChecker::DisallowedPredecessors
1888     [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {
1889         // WASM_SEC_ORDER_NONE
1890         {},
1891         // WASM_SEC_ORDER_TYPE
1892         {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},
1893         // WASM_SEC_ORDER_IMPORT
1894         {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},
1895         // WASM_SEC_ORDER_FUNCTION
1896         {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},
1897         // WASM_SEC_ORDER_TABLE
1898         {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},
1899         // WASM_SEC_ORDER_MEMORY
1900         {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_TAG},
1901         // WASM_SEC_ORDER_TAG
1902         {WASM_SEC_ORDER_TAG, WASM_SEC_ORDER_GLOBAL},
1903         // WASM_SEC_ORDER_GLOBAL
1904         {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},
1905         // WASM_SEC_ORDER_EXPORT
1906         {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},
1907         // WASM_SEC_ORDER_START
1908         {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},
1909         // WASM_SEC_ORDER_ELEM
1910         {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},
1911         // WASM_SEC_ORDER_DATACOUNT
1912         {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},
1913         // WASM_SEC_ORDER_CODE
1914         {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},
1915         // WASM_SEC_ORDER_DATA
1916         {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},
1917 
1918         // Custom Sections
1919         // WASM_SEC_ORDER_DYLINK
1920         {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},
1921         // WASM_SEC_ORDER_LINKING
1922         {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},
1923         // WASM_SEC_ORDER_RELOC (can be repeated)
1924         {},
1925         // WASM_SEC_ORDER_NAME
1926         {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},
1927         // WASM_SEC_ORDER_PRODUCERS
1928         {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},
1929         // WASM_SEC_ORDER_TARGET_FEATURES
1930         {WASM_SEC_ORDER_TARGET_FEATURES}};
1931 
1932 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,
1933                                                   StringRef CustomSectionName) {
1934   int Order = getSectionOrder(ID, CustomSectionName);
1935   if (Order == WASM_SEC_ORDER_NONE)
1936     return true;
1937 
1938   // Disallowed predecessors we need to check for
1939   SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;
1940 
1941   // Keep track of completed checks to avoid repeating work
1942   bool Checked[WASM_NUM_SEC_ORDERS] = {};
1943 
1944   int Curr = Order;
1945   while (true) {
1946     // Add new disallowed predecessors to work list
1947     for (size_t I = 0;; ++I) {
1948       int Next = DisallowedPredecessors[Curr][I];
1949       if (Next == WASM_SEC_ORDER_NONE)
1950         break;
1951       if (Checked[Next])
1952         continue;
1953       WorkList.push_back(Next);
1954       Checked[Next] = true;
1955     }
1956 
1957     if (WorkList.empty())
1958       break;
1959 
1960     // Consider next disallowed predecessor
1961     Curr = WorkList.pop_back_val();
1962     if (Seen[Curr])
1963       return false;
1964   }
1965 
1966   // Have not seen any disallowed predecessors
1967   Seen[Order] = true;
1968   return true;
1969 }
1970