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