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