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