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     uint8_t TableType = 0;
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.ElemType;
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.ElemType;
624         // FIXME: Parse limits here too.
625         if (!Import.Module.empty()) {
626           Info.ImportModule = Import.Module;
627         }
628       }
629       break;
630 
631     case wasm::WASM_SYMBOL_TYPE_DATA:
632       Info.Name = readString(Ctx);
633       if (IsDefined) {
634         auto Index = readVaruint32(Ctx);
635         if (Index >= DataSegments.size())
636           return make_error<GenericBinaryError>("invalid data symbol index",
637                                                 object_error::parse_failed);
638         auto Offset = readVaruint64(Ctx);
639         auto Size = readVaruint64(Ctx);
640         if (Offset + Size > DataSegments[Index].Data.Content.size())
641           return make_error<GenericBinaryError>("invalid data symbol offset",
642                                                 object_error::parse_failed);
643         Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
644       }
645       break;
646 
647     case wasm::WASM_SYMBOL_TYPE_SECTION: {
648       if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
649           wasm::WASM_SYMBOL_BINDING_LOCAL)
650         return make_error<GenericBinaryError>(
651             "Section symbols must have local binding",
652             object_error::parse_failed);
653       Info.ElementIndex = readVaruint32(Ctx);
654       // Use somewhat unique section name as symbol name.
655       StringRef SectionName = Sections[Info.ElementIndex].Name;
656       Info.Name = SectionName;
657       break;
658     }
659 
660     case wasm::WASM_SYMBOL_TYPE_EVENT: {
661       Info.ElementIndex = readVaruint32(Ctx);
662       if (!isValidEventIndex(Info.ElementIndex) ||
663           IsDefined != isDefinedEventIndex(Info.ElementIndex))
664         return make_error<GenericBinaryError>("invalid event symbol index",
665                                               object_error::parse_failed);
666       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
667                             wasm::WASM_SYMBOL_BINDING_WEAK)
668         return make_error<GenericBinaryError>("undefined weak global symbol",
669                                               object_error::parse_failed);
670       if (IsDefined) {
671         Info.Name = readString(Ctx);
672         unsigned EventIndex = Info.ElementIndex - NumImportedEvents;
673         wasm::WasmEvent &Event = Events[EventIndex];
674         Signature = &Signatures[Event.Type.SigIndex];
675         EventType = &Event.Type;
676         if (Event.SymbolName.empty())
677           Event.SymbolName = Info.Name;
678 
679       } else {
680         wasm::WasmImport &Import = *ImportedEvents[Info.ElementIndex];
681         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
682           Info.Name = readString(Ctx);
683           Info.ImportName = Import.Field;
684         } else {
685           Info.Name = Import.Field;
686         }
687         EventType = &Import.Event;
688         Signature = &Signatures[EventType->SigIndex];
689         if (!Import.Module.empty()) {
690           Info.ImportModule = Import.Module;
691         }
692       }
693       break;
694     }
695 
696     default:
697       return make_error<GenericBinaryError>("Invalid symbol type",
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     Reloc.Type = readVaruint32(Ctx);
855     Reloc.Offset = readVaruint32(Ctx);
856     if (Reloc.Offset < PreviousOffset)
857       return make_error<GenericBinaryError>("Relocations not in offset order",
858                                             object_error::parse_failed);
859     PreviousOffset = Reloc.Offset;
860     Reloc.Index = readVaruint32(Ctx);
861     switch (Reloc.Type) {
862     case wasm::R_WASM_FUNCTION_INDEX_LEB:
863     case wasm::R_WASM_TABLE_INDEX_SLEB:
864     case wasm::R_WASM_TABLE_INDEX_SLEB64:
865     case wasm::R_WASM_TABLE_INDEX_I32:
866     case wasm::R_WASM_TABLE_INDEX_I64:
867     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
868       if (!isValidFunctionSymbol(Reloc.Index))
869         return make_error<GenericBinaryError>("Bad relocation function index",
870                                               object_error::parse_failed);
871       break;
872     case wasm::R_WASM_TABLE_NUMBER_LEB:
873       if (!isValidTableSymbol(Reloc.Index))
874         return make_error<GenericBinaryError>("Bad relocation table index",
875                                               object_error::parse_failed);
876       break;
877     case wasm::R_WASM_TYPE_INDEX_LEB:
878       if (Reloc.Index >= Signatures.size())
879         return make_error<GenericBinaryError>("Bad relocation type index",
880                                               object_error::parse_failed);
881       break;
882     case wasm::R_WASM_GLOBAL_INDEX_LEB:
883       // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data
884       // symbols to refer to their GOT entries.
885       if (!isValidGlobalSymbol(Reloc.Index) &&
886           !isValidDataSymbol(Reloc.Index) &&
887           !isValidFunctionSymbol(Reloc.Index))
888         return make_error<GenericBinaryError>("Bad relocation global index",
889                                               object_error::parse_failed);
890       break;
891     case wasm::R_WASM_GLOBAL_INDEX_I32:
892       if (!isValidGlobalSymbol(Reloc.Index))
893         return make_error<GenericBinaryError>("Bad relocation global index",
894                                               object_error::parse_failed);
895       break;
896     case wasm::R_WASM_EVENT_INDEX_LEB:
897       if (!isValidEventSymbol(Reloc.Index))
898         return make_error<GenericBinaryError>("Bad relocation event index",
899                                               object_error::parse_failed);
900       break;
901     case wasm::R_WASM_MEMORY_ADDR_LEB:
902     case wasm::R_WASM_MEMORY_ADDR_SLEB:
903     case wasm::R_WASM_MEMORY_ADDR_I32:
904     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
905     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
906       if (!isValidDataSymbol(Reloc.Index))
907         return make_error<GenericBinaryError>("Bad relocation data index",
908                                               object_error::parse_failed);
909       Reloc.Addend = readVarint32(Ctx);
910       break;
911     case wasm::R_WASM_MEMORY_ADDR_LEB64:
912     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
913     case wasm::R_WASM_MEMORY_ADDR_I64:
914     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
915       if (!isValidDataSymbol(Reloc.Index))
916         return make_error<GenericBinaryError>("Bad relocation data index",
917                                               object_error::parse_failed);
918       Reloc.Addend = readVarint64(Ctx);
919       break;
920     case wasm::R_WASM_FUNCTION_OFFSET_I32:
921       if (!isValidFunctionSymbol(Reloc.Index))
922         return make_error<GenericBinaryError>("Bad relocation function index",
923                                               object_error::parse_failed);
924       Reloc.Addend = readVarint32(Ctx);
925       break;
926     case wasm::R_WASM_FUNCTION_OFFSET_I64:
927       if (!isValidFunctionSymbol(Reloc.Index))
928         return make_error<GenericBinaryError>("Bad relocation function index",
929                                               object_error::parse_failed);
930       Reloc.Addend = readVarint64(Ctx);
931       break;
932     case wasm::R_WASM_SECTION_OFFSET_I32:
933       if (!isValidSectionSymbol(Reloc.Index))
934         return make_error<GenericBinaryError>("Bad relocation section index",
935                                               object_error::parse_failed);
936       Reloc.Addend = readVarint32(Ctx);
937       break;
938     default:
939       return make_error<GenericBinaryError>("Bad relocation type: " +
940                                                 Twine(Reloc.Type),
941                                             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 = (Segment.Data.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
1371                                ? readVaruint32(Ctx) : 0;
1372     if ((Segment.Data.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
1373       if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
1374         return Err;
1375     } else {
1376       Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST;
1377       Segment.Data.Offset.Value.Int32 = 0;
1378     }
1379     uint32_t Size = readVaruint32(Ctx);
1380     if (Size > (size_t)(Ctx.End - Ctx.Ptr))
1381       return make_error<GenericBinaryError>("Invalid segment size",
1382                                             object_error::parse_failed);
1383     Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
1384     // The rest of these Data fields are set later, when reading in the linking
1385     // metadata section.
1386     Segment.Data.Alignment = 0;
1387     Segment.Data.LinkerFlags = 0;
1388     Segment.Data.Comdat = UINT32_MAX;
1389     Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
1390     Ctx.Ptr += Size;
1391     DataSegments.push_back(Segment);
1392   }
1393   if (Ctx.Ptr != Ctx.End)
1394     return make_error<GenericBinaryError>("Data section ended prematurely",
1395                                           object_error::parse_failed);
1396   return Error::success();
1397 }
1398 
1399 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {
1400   DataCount = readVaruint32(Ctx);
1401   return Error::success();
1402 }
1403 
1404 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
1405   return Header;
1406 }
1407 
1408 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }
1409 
1410 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
1411   uint32_t Result = SymbolRef::SF_None;
1412   const WasmSymbol &Sym = getWasmSymbol(Symb);
1413 
1414   LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
1415   if (Sym.isBindingWeak())
1416     Result |= SymbolRef::SF_Weak;
1417   if (!Sym.isBindingLocal())
1418     Result |= SymbolRef::SF_Global;
1419   if (Sym.isHidden())
1420     Result |= SymbolRef::SF_Hidden;
1421   if (!Sym.isDefined())
1422     Result |= SymbolRef::SF_Undefined;
1423   if (Sym.isTypeFunction())
1424     Result |= SymbolRef::SF_Executable;
1425   return Result;
1426 }
1427 
1428 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
1429   DataRefImpl Ref;
1430   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1431   Ref.d.b = 0; // Symbol index
1432   return BasicSymbolRef(Ref, this);
1433 }
1434 
1435 basic_symbol_iterator WasmObjectFile::symbol_end() const {
1436   DataRefImpl Ref;
1437   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1438   Ref.d.b = Symbols.size(); // Symbol index
1439   return BasicSymbolRef(Ref, this);
1440 }
1441 
1442 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
1443   return Symbols[Symb.d.b];
1444 }
1445 
1446 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
1447   return getWasmSymbol(Symb.getRawDataRefImpl());
1448 }
1449 
1450 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
1451   return getWasmSymbol(Symb).Info.Name;
1452 }
1453 
1454 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
1455   auto &Sym = getWasmSymbol(Symb);
1456   if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&
1457       isDefinedFunctionIndex(Sym.Info.ElementIndex))
1458     return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset;
1459   else
1460     return getSymbolValue(Symb);
1461 }
1462 
1463 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {
1464   switch (Sym.Info.Kind) {
1465   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1466   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1467   case wasm::WASM_SYMBOL_TYPE_EVENT:
1468   case wasm::WASM_SYMBOL_TYPE_TABLE:
1469     return Sym.Info.ElementIndex;
1470   case wasm::WASM_SYMBOL_TYPE_DATA: {
1471     // The value of a data symbol is the segment offset, plus the symbol
1472     // offset within the segment.
1473     uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
1474     const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
1475     if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) {
1476       return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset;
1477     } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) {
1478       return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset;
1479     } else {
1480       llvm_unreachable("unknown init expr opcode");
1481     }
1482   }
1483   case wasm::WASM_SYMBOL_TYPE_SECTION:
1484     return 0;
1485   }
1486   llvm_unreachable("invalid symbol type");
1487 }
1488 
1489 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
1490   return getWasmSymbolValue(getWasmSymbol(Symb));
1491 }
1492 
1493 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
1494   llvm_unreachable("not yet implemented");
1495   return 0;
1496 }
1497 
1498 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
1499   llvm_unreachable("not yet implemented");
1500   return 0;
1501 }
1502 
1503 Expected<SymbolRef::Type>
1504 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
1505   const WasmSymbol &Sym = getWasmSymbol(Symb);
1506 
1507   switch (Sym.Info.Kind) {
1508   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1509     return SymbolRef::ST_Function;
1510   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1511     return SymbolRef::ST_Other;
1512   case wasm::WASM_SYMBOL_TYPE_DATA:
1513     return SymbolRef::ST_Data;
1514   case wasm::WASM_SYMBOL_TYPE_SECTION:
1515     return SymbolRef::ST_Debug;
1516   case wasm::WASM_SYMBOL_TYPE_EVENT:
1517     return SymbolRef::ST_Other;
1518   case wasm::WASM_SYMBOL_TYPE_TABLE:
1519     return SymbolRef::ST_Other;
1520   }
1521 
1522   llvm_unreachable("Unknown WasmSymbol::SymbolType");
1523   return SymbolRef::ST_Other;
1524 }
1525 
1526 Expected<section_iterator>
1527 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
1528   const WasmSymbol &Sym = getWasmSymbol(Symb);
1529   if (Sym.isUndefined())
1530     return section_end();
1531 
1532   DataRefImpl Ref;
1533   Ref.d.a = getSymbolSectionIdImpl(Sym);
1534   return section_iterator(SectionRef(Ref, this));
1535 }
1536 
1537 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {
1538   const WasmSymbol &Sym = getWasmSymbol(Symb);
1539   return getSymbolSectionIdImpl(Sym);
1540 }
1541 
1542 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {
1543   switch (Sym.Info.Kind) {
1544   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1545     return CodeSection;
1546   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1547     return GlobalSection;
1548   case wasm::WASM_SYMBOL_TYPE_DATA:
1549     return DataSection;
1550   case wasm::WASM_SYMBOL_TYPE_SECTION:
1551     return Sym.Info.ElementIndex;
1552   case wasm::WASM_SYMBOL_TYPE_EVENT:
1553     return EventSection;
1554   case wasm::WASM_SYMBOL_TYPE_TABLE:
1555     return TableSection;
1556   default:
1557     llvm_unreachable("Unknown WasmSymbol::SymbolType");
1558   }
1559 }
1560 
1561 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
1562 
1563 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {
1564   const WasmSection &S = Sections[Sec.d.a];
1565 #define ECase(X)                                                               \
1566   case wasm::WASM_SEC_##X:                                                     \
1567     return #X;
1568   switch (S.Type) {
1569     ECase(TYPE);
1570     ECase(IMPORT);
1571     ECase(FUNCTION);
1572     ECase(TABLE);
1573     ECase(MEMORY);
1574     ECase(GLOBAL);
1575     ECase(EVENT);
1576     ECase(EXPORT);
1577     ECase(START);
1578     ECase(ELEM);
1579     ECase(CODE);
1580     ECase(DATA);
1581     ECase(DATACOUNT);
1582   case wasm::WASM_SEC_CUSTOM:
1583     return S.Name;
1584   default:
1585     return createStringError(object_error::invalid_section_index, "");
1586   }
1587 #undef ECase
1588 }
1589 
1590 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
1591 
1592 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
1593   return Sec.d.a;
1594 }
1595 
1596 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
1597   const WasmSection &S = Sections[Sec.d.a];
1598   return S.Content.size();
1599 }
1600 
1601 Expected<ArrayRef<uint8_t>>
1602 WasmObjectFile::getSectionContents(DataRefImpl Sec) const {
1603   const WasmSection &S = Sections[Sec.d.a];
1604   // This will never fail since wasm sections can never be empty (user-sections
1605   // must have a name and non-user sections each have a defined structure).
1606   return S.Content;
1607 }
1608 
1609 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1610   return 1;
1611 }
1612 
1613 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1614   return false;
1615 }
1616 
1617 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
1618   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
1619 }
1620 
1621 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
1622   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
1623 }
1624 
1625 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
1626 
1627 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
1628 
1629 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
1630   DataRefImpl RelocRef;
1631   RelocRef.d.a = Ref.d.a;
1632   RelocRef.d.b = 0;
1633   return relocation_iterator(RelocationRef(RelocRef, this));
1634 }
1635 
1636 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
1637   const WasmSection &Sec = getWasmSection(Ref);
1638   DataRefImpl RelocRef;
1639   RelocRef.d.a = Ref.d.a;
1640   RelocRef.d.b = Sec.Relocations.size();
1641   return relocation_iterator(RelocationRef(RelocRef, this));
1642 }
1643 
1644 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }
1645 
1646 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1647   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1648   return Rel.Offset;
1649 }
1650 
1651 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
1652   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1653   if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)
1654     return symbol_end();
1655   DataRefImpl Sym;
1656   Sym.d.a = 1;
1657   Sym.d.b = Rel.Index;
1658   return symbol_iterator(SymbolRef(Sym, this));
1659 }
1660 
1661 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1662   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1663   return Rel.Type;
1664 }
1665 
1666 void WasmObjectFile::getRelocationTypeName(
1667     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1668   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1669   StringRef Res = "Unknown";
1670 
1671 #define WASM_RELOC(name, value)                                                \
1672   case wasm::name:                                                             \
1673     Res = #name;                                                               \
1674     break;
1675 
1676   switch (Rel.Type) {
1677 #include "llvm/BinaryFormat/WasmRelocs.def"
1678   }
1679 
1680 #undef WASM_RELOC
1681 
1682   Result.append(Res.begin(), Res.end());
1683 }
1684 
1685 section_iterator WasmObjectFile::section_begin() const {
1686   DataRefImpl Ref;
1687   Ref.d.a = 0;
1688   return section_iterator(SectionRef(Ref, this));
1689 }
1690 
1691 section_iterator WasmObjectFile::section_end() const {
1692   DataRefImpl Ref;
1693   Ref.d.a = Sections.size();
1694   return section_iterator(SectionRef(Ref, this));
1695 }
1696 
1697 uint8_t WasmObjectFile::getBytesInAddress() const {
1698   return HasMemory64 ? 8 : 4;
1699 }
1700 
1701 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1702 
1703 Triple::ArchType WasmObjectFile::getArch() const {
1704   return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
1705 }
1706 
1707 SubtargetFeatures WasmObjectFile::getFeatures() const {
1708   return SubtargetFeatures();
1709 }
1710 
1711 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }
1712 
1713 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }
1714 
1715 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1716   assert(Ref.d.a < Sections.size());
1717   return Sections[Ref.d.a];
1718 }
1719 
1720 const WasmSection &
1721 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1722   return getWasmSection(Section.getRawDataRefImpl());
1723 }
1724 
1725 const wasm::WasmRelocation &
1726 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1727   return getWasmRelocation(Ref.getRawDataRefImpl());
1728 }
1729 
1730 const wasm::WasmRelocation &
1731 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1732   assert(Ref.d.a < Sections.size());
1733   const WasmSection &Sec = Sections[Ref.d.a];
1734   assert(Ref.d.b < Sec.Relocations.size());
1735   return Sec.Relocations[Ref.d.b];
1736 }
1737 
1738 int WasmSectionOrderChecker::getSectionOrder(unsigned ID,
1739                                              StringRef CustomSectionName) {
1740   switch (ID) {
1741   case wasm::WASM_SEC_CUSTOM:
1742     return StringSwitch<unsigned>(CustomSectionName)
1743         .Case("dylink", WASM_SEC_ORDER_DYLINK)
1744         .Case("linking", WASM_SEC_ORDER_LINKING)
1745         .StartsWith("reloc.", WASM_SEC_ORDER_RELOC)
1746         .Case("name", WASM_SEC_ORDER_NAME)
1747         .Case("producers", WASM_SEC_ORDER_PRODUCERS)
1748         .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)
1749         .Default(WASM_SEC_ORDER_NONE);
1750   case wasm::WASM_SEC_TYPE:
1751     return WASM_SEC_ORDER_TYPE;
1752   case wasm::WASM_SEC_IMPORT:
1753     return WASM_SEC_ORDER_IMPORT;
1754   case wasm::WASM_SEC_FUNCTION:
1755     return WASM_SEC_ORDER_FUNCTION;
1756   case wasm::WASM_SEC_TABLE:
1757     return WASM_SEC_ORDER_TABLE;
1758   case wasm::WASM_SEC_MEMORY:
1759     return WASM_SEC_ORDER_MEMORY;
1760   case wasm::WASM_SEC_GLOBAL:
1761     return WASM_SEC_ORDER_GLOBAL;
1762   case wasm::WASM_SEC_EXPORT:
1763     return WASM_SEC_ORDER_EXPORT;
1764   case wasm::WASM_SEC_START:
1765     return WASM_SEC_ORDER_START;
1766   case wasm::WASM_SEC_ELEM:
1767     return WASM_SEC_ORDER_ELEM;
1768   case wasm::WASM_SEC_CODE:
1769     return WASM_SEC_ORDER_CODE;
1770   case wasm::WASM_SEC_DATA:
1771     return WASM_SEC_ORDER_DATA;
1772   case wasm::WASM_SEC_DATACOUNT:
1773     return WASM_SEC_ORDER_DATACOUNT;
1774   case wasm::WASM_SEC_EVENT:
1775     return WASM_SEC_ORDER_EVENT;
1776   default:
1777     return WASM_SEC_ORDER_NONE;
1778   }
1779 }
1780 
1781 // Represents the edges in a directed graph where any node B reachable from node
1782 // A is not allowed to appear before A in the section ordering, but may appear
1783 // afterward.
1784 int WasmSectionOrderChecker::DisallowedPredecessors
1785     [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {
1786         // WASM_SEC_ORDER_NONE
1787         {},
1788         // WASM_SEC_ORDER_TYPE
1789         {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},
1790         // WASM_SEC_ORDER_IMPORT
1791         {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},
1792         // WASM_SEC_ORDER_FUNCTION
1793         {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},
1794         // WASM_SEC_ORDER_TABLE
1795         {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},
1796         // WASM_SEC_ORDER_MEMORY
1797         {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_EVENT},
1798         // WASM_SEC_ORDER_EVENT
1799         {WASM_SEC_ORDER_EVENT, WASM_SEC_ORDER_GLOBAL},
1800         // WASM_SEC_ORDER_GLOBAL
1801         {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},
1802         // WASM_SEC_ORDER_EXPORT
1803         {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},
1804         // WASM_SEC_ORDER_START
1805         {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},
1806         // WASM_SEC_ORDER_ELEM
1807         {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},
1808         // WASM_SEC_ORDER_DATACOUNT
1809         {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},
1810         // WASM_SEC_ORDER_CODE
1811         {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},
1812         // WASM_SEC_ORDER_DATA
1813         {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},
1814 
1815         // Custom Sections
1816         // WASM_SEC_ORDER_DYLINK
1817         {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},
1818         // WASM_SEC_ORDER_LINKING
1819         {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},
1820         // WASM_SEC_ORDER_RELOC (can be repeated)
1821         {},
1822         // WASM_SEC_ORDER_NAME
1823         {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},
1824         // WASM_SEC_ORDER_PRODUCERS
1825         {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},
1826         // WASM_SEC_ORDER_TARGET_FEATURES
1827         {WASM_SEC_ORDER_TARGET_FEATURES}};
1828 
1829 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,
1830                                                   StringRef CustomSectionName) {
1831   int Order = getSectionOrder(ID, CustomSectionName);
1832   if (Order == WASM_SEC_ORDER_NONE)
1833     return true;
1834 
1835   // Disallowed predecessors we need to check for
1836   SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;
1837 
1838   // Keep track of completed checks to avoid repeating work
1839   bool Checked[WASM_NUM_SEC_ORDERS] = {};
1840 
1841   int Curr = Order;
1842   while (true) {
1843     // Add new disallowed predecessors to work list
1844     for (size_t I = 0;; ++I) {
1845       int Next = DisallowedPredecessors[Curr][I];
1846       if (Next == WASM_SEC_ORDER_NONE)
1847         break;
1848       if (Checked[Next])
1849         continue;
1850       WorkList.push_back(Next);
1851       Checked[Next] = true;
1852     }
1853 
1854     if (WorkList.empty())
1855       break;
1856 
1857     // Consider next disallowed predecessor
1858     Curr = WorkList.pop_back_val();
1859     if (Seen[Curr])
1860       return false;
1861   }
1862 
1863   // Have not seen any disallowed predecessors
1864   Seen[Order] = true;
1865   return true;
1866 }
1867