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