xref: /llvm-project/llvm/lib/Object/WasmObjectFile.cpp (revision e3d6b9786e61c80a089a5812e7699dd18f0ebcc3)
1 //===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseSet.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/StringSet.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/BinaryFormat/Wasm.h"
17 #include "llvm/MC/SubtargetFeature.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/Object/Error.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Object/SymbolicFile.h"
22 #include "llvm/Object/Wasm.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/LEB128.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <cstdint>
30 #include <cstring>
31 #include <system_error>
32 
33 #define DEBUG_TYPE "wasm-object"
34 
35 using namespace llvm;
36 using namespace object;
37 
38 void WasmSymbol::print(raw_ostream &Out) const {
39   Out << "Name=" << Info.Name
40   << ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind))
41   << ", Flags=" << Info.Flags;
42   if (!isTypeData()) {
43     Out << ", ElemIndex=" << Info.ElementIndex;
44   } else if (isDefined()) {
45     Out << ", Segment=" << Info.DataRef.Segment;
46     Out << ", Offset=" << Info.DataRef.Offset;
47     Out << ", Size=" << Info.DataRef.Size;
48   }
49 }
50 
51 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52 LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); }
53 #endif
54 
55 Expected<std::unique_ptr<WasmObjectFile>>
56 ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {
57   Error Err = Error::success();
58   auto ObjectFile = llvm::make_unique<WasmObjectFile>(Buffer, Err);
59   if (Err)
60     return std::move(Err);
61 
62   return std::move(ObjectFile);
63 }
64 
65 #define VARINT7_MAX ((1<<7)-1)
66 #define VARINT7_MIN (-(1<<7))
67 #define VARUINT7_MAX (1<<7)
68 #define VARUINT1_MAX (1)
69 
70 static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) {
71   if (Ctx.Ptr == Ctx.End)
72     report_fatal_error("EOF while reading uint8");
73   return *Ctx.Ptr++;
74 }
75 
76 static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) {
77   if (Ctx.Ptr + 4 > Ctx.End)
78     report_fatal_error("EOF while reading uint32");
79   uint32_t Result = support::endian::read32le(Ctx.Ptr);
80   Ctx.Ptr += 4;
81   return Result;
82 }
83 
84 static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) {
85   if (Ctx.Ptr + 4 > Ctx.End)
86     report_fatal_error("EOF while reading float64");
87   int32_t Result = 0;
88   memcpy(&Result, Ctx.Ptr, sizeof(Result));
89   Ctx.Ptr += sizeof(Result);
90   return Result;
91 }
92 
93 static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) {
94   if (Ctx.Ptr + 8 > Ctx.End)
95     report_fatal_error("EOF while reading float64");
96   int64_t Result = 0;
97   memcpy(&Result, Ctx.Ptr, sizeof(Result));
98   Ctx.Ptr += sizeof(Result);
99   return Result;
100 }
101 
102 static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) {
103   unsigned Count;
104   const char* Error = nullptr;
105   uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
106   if (Error)
107     report_fatal_error(Error);
108   Ctx.Ptr += Count;
109   return Result;
110 }
111 
112 static StringRef readString(WasmObjectFile::ReadContext &Ctx) {
113   uint32_t StringLen = readULEB128(Ctx);
114   if (Ctx.Ptr + StringLen > Ctx.End)
115     report_fatal_error("EOF while reading string");
116   StringRef Return =
117       StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen);
118   Ctx.Ptr += StringLen;
119   return Return;
120 }
121 
122 static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) {
123   unsigned Count;
124   const char* Error = nullptr;
125   uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
126   if (Error)
127     report_fatal_error(Error);
128   Ctx.Ptr += Count;
129   return Result;
130 }
131 
132 static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) {
133   int64_t result = readLEB128(Ctx);
134   if (result > VARUINT1_MAX || result < 0)
135     report_fatal_error("LEB is outside Varuint1 range");
136   return result;
137 }
138 
139 static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) {
140   int64_t result = readLEB128(Ctx);
141   if (result > INT32_MAX || result < INT32_MIN)
142     report_fatal_error("LEB is outside Varint32 range");
143   return result;
144 }
145 
146 static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) {
147   uint64_t result = readULEB128(Ctx);
148   if (result > UINT32_MAX)
149     report_fatal_error("LEB is outside Varuint32 range");
150   return result;
151 }
152 
153 static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) {
154   return readLEB128(Ctx);
155 }
156 
157 static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) {
158   return readUint8(Ctx);
159 }
160 
161 static Error readInitExpr(wasm::WasmInitExpr &Expr,
162                           WasmObjectFile::ReadContext &Ctx) {
163   Expr.Opcode = readOpcode(Ctx);
164 
165   switch (Expr.Opcode) {
166   case wasm::WASM_OPCODE_I32_CONST:
167     Expr.Value.Int32 = readVarint32(Ctx);
168     break;
169   case wasm::WASM_OPCODE_I64_CONST:
170     Expr.Value.Int64 = readVarint64(Ctx);
171     break;
172   case wasm::WASM_OPCODE_F32_CONST:
173     Expr.Value.Float32 = readFloat32(Ctx);
174     break;
175   case wasm::WASM_OPCODE_F64_CONST:
176     Expr.Value.Float64 = readFloat64(Ctx);
177     break;
178   case wasm::WASM_OPCODE_GET_GLOBAL:
179     Expr.Value.Global = readULEB128(Ctx);
180     break;
181   default:
182     return make_error<GenericBinaryError>("Invalid opcode in init_expr",
183                                           object_error::parse_failed);
184   }
185 
186   uint8_t EndOpcode = readOpcode(Ctx);
187   if (EndOpcode != wasm::WASM_OPCODE_END) {
188     return make_error<GenericBinaryError>("Invalid init_expr",
189                                           object_error::parse_failed);
190   }
191   return Error::success();
192 }
193 
194 static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) {
195   wasm::WasmLimits Result;
196   Result.Flags = readVaruint1(Ctx);
197   Result.Initial = readVaruint32(Ctx);
198   if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
199     Result.Maximum = readVaruint32(Ctx);
200   return Result;
201 }
202 
203 static wasm::WasmTable readTable(WasmObjectFile::ReadContext &Ctx) {
204   wasm::WasmTable Table;
205   Table.ElemType = readUint8(Ctx);
206   Table.Limits = readLimits(Ctx);
207   return Table;
208 }
209 
210 static Error readSection(WasmSection &Section,
211                          WasmObjectFile::ReadContext &Ctx) {
212   Section.Offset = Ctx.Ptr - Ctx.Start;
213   Section.Type = readUint8(Ctx);
214   LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");
215   uint32_t Size = readVaruint32(Ctx);
216   if (Size == 0)
217     return make_error<StringError>("Zero length section",
218                                    object_error::parse_failed);
219   if (Ctx.Ptr + Size > Ctx.End)
220     return make_error<StringError>("Section too large",
221                                    object_error::parse_failed);
222   if (Section.Type == wasm::WASM_SEC_CUSTOM) {
223     WasmObjectFile::ReadContext SectionCtx;
224     SectionCtx.Start = Ctx.Ptr;
225     SectionCtx.Ptr = Ctx.Ptr;
226     SectionCtx.End = Ctx.Ptr + Size;
227 
228     Section.Name = readString(SectionCtx);
229 
230     uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start;
231     Ctx.Ptr += SectionNameSize;
232     Size -= SectionNameSize;
233   }
234   Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
235   Ctx.Ptr += Size;
236   return Error::success();
237 }
238 
239 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
240     : ObjectFile(Binary::ID_Wasm, Buffer) {
241   ErrorAsOutParameter ErrAsOutParam(&Err);
242   Header.Magic = getData().substr(0, 4);
243   if (Header.Magic != StringRef("\0asm", 4)) {
244     Err = make_error<StringError>("Bad magic number",
245                                   object_error::parse_failed);
246     return;
247   }
248 
249   ReadContext Ctx;
250   Ctx.Start = getPtr(0);
251   Ctx.Ptr = Ctx.Start + 4;
252   Ctx.End = Ctx.Start + getData().size();
253 
254   if (Ctx.Ptr + 4 > Ctx.End) {
255     Err = make_error<StringError>("Missing version number",
256                                   object_error::parse_failed);
257     return;
258   }
259 
260   Header.Version = readUint32(Ctx);
261   if (Header.Version != wasm::WasmVersion) {
262     Err = make_error<StringError>("Bad version number",
263                                   object_error::parse_failed);
264     return;
265   }
266 
267   WasmSection Sec;
268   while (Ctx.Ptr < Ctx.End) {
269     if ((Err = readSection(Sec, Ctx)))
270       return;
271     if ((Err = parseSection(Sec)))
272       return;
273 
274     Sections.push_back(Sec);
275   }
276 }
277 
278 Error WasmObjectFile::parseSection(WasmSection &Sec) {
279   ReadContext Ctx;
280   Ctx.Start = Sec.Content.data();
281   Ctx.End = Ctx.Start + Sec.Content.size();
282   Ctx.Ptr = Ctx.Start;
283   switch (Sec.Type) {
284   case wasm::WASM_SEC_CUSTOM:
285     return parseCustomSection(Sec, Ctx);
286   case wasm::WASM_SEC_TYPE:
287     return parseTypeSection(Ctx);
288   case wasm::WASM_SEC_IMPORT:
289     return parseImportSection(Ctx);
290   case wasm::WASM_SEC_FUNCTION:
291     return parseFunctionSection(Ctx);
292   case wasm::WASM_SEC_TABLE:
293     return parseTableSection(Ctx);
294   case wasm::WASM_SEC_MEMORY:
295     return parseMemorySection(Ctx);
296   case wasm::WASM_SEC_GLOBAL:
297     return parseGlobalSection(Ctx);
298   case wasm::WASM_SEC_EXPORT:
299     return parseExportSection(Ctx);
300   case wasm::WASM_SEC_START:
301     return parseStartSection(Ctx);
302   case wasm::WASM_SEC_ELEM:
303     return parseElemSection(Ctx);
304   case wasm::WASM_SEC_CODE:
305     return parseCodeSection(Ctx);
306   case wasm::WASM_SEC_DATA:
307     return parseDataSection(Ctx);
308   default:
309     return make_error<GenericBinaryError>("Bad section type",
310                                           object_error::parse_failed);
311   }
312 }
313 
314 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {
315   llvm::DenseSet<uint64_t> Seen;
316   if (Functions.size() != FunctionTypes.size()) {
317     return make_error<GenericBinaryError>("Names must come after code section",
318                                           object_error::parse_failed);
319   }
320 
321   while (Ctx.Ptr < Ctx.End) {
322     uint8_t Type = readUint8(Ctx);
323     uint32_t Size = readVaruint32(Ctx);
324     const uint8_t *SubSectionEnd = Ctx.Ptr + Size;
325     switch (Type) {
326     case wasm::WASM_NAMES_FUNCTION: {
327       uint32_t Count = readVaruint32(Ctx);
328       while (Count--) {
329         uint32_t Index = readVaruint32(Ctx);
330         if (!Seen.insert(Index).second)
331           return make_error<GenericBinaryError>("Function named more than once",
332                                                 object_error::parse_failed);
333         StringRef Name = readString(Ctx);
334         if (!isValidFunctionIndex(Index) || Name.empty())
335           return make_error<GenericBinaryError>("Invalid name entry",
336                                                 object_error::parse_failed);
337         DebugNames.push_back(wasm::WasmFunctionName{Index, Name});
338         if (isDefinedFunctionIndex(Index))
339           getDefinedFunction(Index).DebugName = Name;
340       }
341       break;
342     }
343     // Ignore local names for now
344     case wasm::WASM_NAMES_LOCAL:
345     default:
346       Ctx.Ptr += Size;
347       break;
348     }
349     if (Ctx.Ptr != SubSectionEnd)
350       return make_error<GenericBinaryError>("Name sub-section ended prematurely",
351                                             object_error::parse_failed);
352   }
353 
354   if (Ctx.Ptr != Ctx.End)
355     return make_error<GenericBinaryError>("Name section ended prematurely",
356                                           object_error::parse_failed);
357   return Error::success();
358 }
359 
360 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {
361   HasLinkingSection = true;
362   if (Functions.size() != FunctionTypes.size()) {
363     return make_error<GenericBinaryError>(
364         "Linking data must come after code section", object_error::parse_failed);
365   }
366 
367   LinkingData.Version = readVaruint32(Ctx);
368   if (LinkingData.Version != wasm::WasmMetadataVersion) {
369     return make_error<GenericBinaryError>(
370         "Unexpected metadata version: " + Twine(LinkingData.Version) +
371             " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",
372         object_error::parse_failed);
373   }
374 
375   const uint8_t *OrigEnd = Ctx.End;
376   while (Ctx.Ptr < OrigEnd) {
377     Ctx.End = OrigEnd;
378     uint8_t Type = readUint8(Ctx);
379     uint32_t Size = readVaruint32(Ctx);
380     LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size
381                       << "\n");
382     Ctx.End = Ctx.Ptr + Size;
383     switch (Type) {
384     case wasm::WASM_SYMBOL_TABLE:
385       if (Error Err = parseLinkingSectionSymtab(Ctx))
386         return Err;
387       break;
388     case wasm::WASM_SEGMENT_INFO: {
389       uint32_t Count = readVaruint32(Ctx);
390       if (Count > DataSegments.size())
391         return make_error<GenericBinaryError>("Too many segment names",
392                                               object_error::parse_failed);
393       for (uint32_t i = 0; i < Count; i++) {
394         DataSegments[i].Data.Name = readString(Ctx);
395         DataSegments[i].Data.Alignment = readVaruint32(Ctx);
396         DataSegments[i].Data.Flags = readVaruint32(Ctx);
397       }
398       break;
399     }
400     case wasm::WASM_INIT_FUNCS: {
401       uint32_t Count = readVaruint32(Ctx);
402       LinkingData.InitFunctions.reserve(Count);
403       for (uint32_t i = 0; i < Count; i++) {
404         wasm::WasmInitFunc Init;
405         Init.Priority = readVaruint32(Ctx);
406         Init.Symbol = readVaruint32(Ctx);
407         if (!isValidFunctionSymbol(Init.Symbol))
408           return make_error<GenericBinaryError>("Invalid function symbol: " +
409                                                     Twine(Init.Symbol),
410                                                 object_error::parse_failed);
411         LinkingData.InitFunctions.emplace_back(Init);
412       }
413       break;
414     }
415     case wasm::WASM_COMDAT_INFO:
416       if (Error Err = parseLinkingSectionComdat(Ctx))
417         return Err;
418       break;
419     default:
420       Ctx.Ptr += Size;
421       break;
422     }
423     if (Ctx.Ptr != Ctx.End)
424       return make_error<GenericBinaryError>(
425           "Linking sub-section ended prematurely", object_error::parse_failed);
426   }
427   if (Ctx.Ptr != OrigEnd)
428     return make_error<GenericBinaryError>("Linking section ended prematurely",
429                                           object_error::parse_failed);
430   return Error::success();
431 }
432 
433 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {
434   uint32_t Count = readVaruint32(Ctx);
435   LinkingData.SymbolTable.reserve(Count);
436   Symbols.reserve(Count);
437   StringSet<> SymbolNames;
438 
439   std::vector<wasm::WasmImport *> ImportedGlobals;
440   std::vector<wasm::WasmImport *> ImportedFunctions;
441   ImportedGlobals.reserve(Imports.size());
442   ImportedFunctions.reserve(Imports.size());
443   for (auto &I : Imports) {
444     if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)
445       ImportedFunctions.emplace_back(&I);
446     else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)
447       ImportedGlobals.emplace_back(&I);
448   }
449 
450   while (Count--) {
451     wasm::WasmSymbolInfo Info;
452     const wasm::WasmSignature *FunctionType = nullptr;
453     const wasm::WasmGlobalType *GlobalType = nullptr;
454 
455     Info.Kind = readUint8(Ctx);
456     Info.Flags = readVaruint32(Ctx);
457     bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;
458 
459     switch (Info.Kind) {
460     case wasm::WASM_SYMBOL_TYPE_FUNCTION:
461       Info.ElementIndex = readVaruint32(Ctx);
462       if (!isValidFunctionIndex(Info.ElementIndex) ||
463           IsDefined != isDefinedFunctionIndex(Info.ElementIndex))
464         return make_error<GenericBinaryError>("invalid function symbol index",
465                                               object_error::parse_failed);
466       if (IsDefined) {
467         Info.Name = readString(Ctx);
468         unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
469         FunctionType = &Signatures[FunctionTypes[FuncIndex]];
470         wasm::WasmFunction &Function = Functions[FuncIndex];
471         if (Function.SymbolName.empty())
472           Function.SymbolName = Info.Name;
473       } else {
474         wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];
475         FunctionType = &Signatures[Import.SigIndex];
476         Info.Name = Import.Field;
477         Info.Module = Import.Module;
478       }
479       break;
480 
481     case wasm::WASM_SYMBOL_TYPE_GLOBAL:
482       Info.ElementIndex = readVaruint32(Ctx);
483       if (!isValidGlobalIndex(Info.ElementIndex) ||
484           IsDefined != isDefinedGlobalIndex(Info.ElementIndex))
485         return make_error<GenericBinaryError>("invalid global symbol index",
486                                               object_error::parse_failed);
487       if (!IsDefined &&
488           (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
489               wasm::WASM_SYMBOL_BINDING_WEAK)
490         return make_error<GenericBinaryError>("undefined weak global symbol",
491                                               object_error::parse_failed);
492       if (IsDefined) {
493         Info.Name = readString(Ctx);
494         unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;
495         wasm::WasmGlobal &Global = Globals[GlobalIndex];
496         GlobalType = &Global.Type;
497         if (Global.SymbolName.empty())
498           Global.SymbolName = Info.Name;
499       } else {
500         wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];
501         Info.Name = Import.Field;
502         GlobalType = &Import.Global;
503       }
504       break;
505 
506     case wasm::WASM_SYMBOL_TYPE_DATA:
507       Info.Name = readString(Ctx);
508       if (IsDefined) {
509         uint32_t Index = readVaruint32(Ctx);
510         if (Index >= DataSegments.size())
511           return make_error<GenericBinaryError>("invalid data symbol index",
512                                                 object_error::parse_failed);
513         uint32_t Offset = readVaruint32(Ctx);
514         uint32_t Size = readVaruint32(Ctx);
515         if (Offset + Size > DataSegments[Index].Data.Content.size())
516           return make_error<GenericBinaryError>("invalid data symbol offset",
517                                                 object_error::parse_failed);
518         Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
519       }
520       break;
521 
522     case wasm::WASM_SYMBOL_TYPE_SECTION: {
523       if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
524           wasm::WASM_SYMBOL_BINDING_LOCAL)
525         return make_error<GenericBinaryError>(
526             "Section symbols must have local binding",
527             object_error::parse_failed);
528       Info.ElementIndex = readVaruint32(Ctx);
529       // Use somewhat unique section name as symbol name.
530       StringRef SectionName = Sections[Info.ElementIndex].Name;
531       Info.Name = SectionName;
532       break;
533     }
534 
535     default:
536       return make_error<GenericBinaryError>("Invalid symbol type",
537                                             object_error::parse_failed);
538     }
539 
540     if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
541             wasm::WASM_SYMBOL_BINDING_LOCAL &&
542         !SymbolNames.insert(Info.Name).second)
543       return make_error<GenericBinaryError>("Duplicate symbol name " +
544                                                 Twine(Info.Name),
545                                             object_error::parse_failed);
546     LinkingData.SymbolTable.emplace_back(Info);
547     Symbols.emplace_back(LinkingData.SymbolTable.back(), FunctionType,
548                          GlobalType);
549     LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
550   }
551 
552   return Error::success();
553 }
554 
555 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {
556   uint32_t ComdatCount = readVaruint32(Ctx);
557   StringSet<> ComdatSet;
558   for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {
559     StringRef Name = readString(Ctx);
560     if (Name.empty() || !ComdatSet.insert(Name).second)
561       return make_error<GenericBinaryError>("Bad/duplicate COMDAT name " + Twine(Name),
562                                             object_error::parse_failed);
563     LinkingData.Comdats.emplace_back(Name);
564     uint32_t Flags = readVaruint32(Ctx);
565     if (Flags != 0)
566       return make_error<GenericBinaryError>("Unsupported COMDAT flags",
567                                             object_error::parse_failed);
568 
569     uint32_t EntryCount = readVaruint32(Ctx);
570     while (EntryCount--) {
571       unsigned Kind = readVaruint32(Ctx);
572       unsigned Index = readVaruint32(Ctx);
573       switch (Kind) {
574       default:
575         return make_error<GenericBinaryError>("Invalid COMDAT entry type",
576                                               object_error::parse_failed);
577       case wasm::WASM_COMDAT_DATA:
578         if (Index >= DataSegments.size())
579           return make_error<GenericBinaryError>("COMDAT data index out of range",
580                                                 object_error::parse_failed);
581         if (DataSegments[Index].Data.Comdat != UINT32_MAX)
582           return make_error<GenericBinaryError>("Data segment in two COMDATs",
583                                                 object_error::parse_failed);
584         DataSegments[Index].Data.Comdat = ComdatIndex;
585         break;
586       case wasm::WASM_COMDAT_FUNCTION:
587         if (!isDefinedFunctionIndex(Index))
588           return make_error<GenericBinaryError>("COMDAT function index out of range",
589                                                 object_error::parse_failed);
590         if (getDefinedFunction(Index).Comdat != UINT32_MAX)
591           return make_error<GenericBinaryError>("Function in two COMDATs",
592                                                 object_error::parse_failed);
593         getDefinedFunction(Index).Comdat = ComdatIndex;
594         break;
595       }
596     }
597   }
598   return Error::success();
599 }
600 
601 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {
602   uint32_t SectionIndex = readVaruint32(Ctx);
603   if (SectionIndex >= Sections.size())
604     return make_error<GenericBinaryError>("Invalid section index",
605                                           object_error::parse_failed);
606   WasmSection& Section = Sections[SectionIndex];
607   uint32_t RelocCount = readVaruint32(Ctx);
608   uint32_t EndOffset = Section.Content.size();
609   uint32_t PreviousOffset = 0;
610   while (RelocCount--) {
611     wasm::WasmRelocation Reloc = {};
612     Reloc.Type = readVaruint32(Ctx);
613     Reloc.Offset = readVaruint32(Ctx);
614     if (Reloc.Offset < PreviousOffset)
615       return make_error<GenericBinaryError>("Relocations not in offset order",
616                                             object_error::parse_failed);
617     PreviousOffset = Reloc.Offset;
618     Reloc.Index = readVaruint32(Ctx);
619     switch (Reloc.Type) {
620     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
621     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
622     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
623       if (!isValidFunctionSymbol(Reloc.Index))
624         return make_error<GenericBinaryError>("Bad relocation function index",
625                                               object_error::parse_failed);
626       break;
627     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
628       if (Reloc.Index >= Signatures.size())
629         return make_error<GenericBinaryError>("Bad relocation type index",
630                                               object_error::parse_failed);
631       break;
632     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
633       if (!isValidGlobalSymbol(Reloc.Index))
634         return make_error<GenericBinaryError>("Bad relocation global index",
635                                               object_error::parse_failed);
636       break;
637     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
638     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
639     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
640       if (!isValidDataSymbol(Reloc.Index))
641         return make_error<GenericBinaryError>("Bad relocation data index",
642                                               object_error::parse_failed);
643       Reloc.Addend = readVarint32(Ctx);
644       break;
645     case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
646       if (!isValidFunctionSymbol(Reloc.Index))
647         return make_error<GenericBinaryError>("Bad relocation function index",
648                                               object_error::parse_failed);
649       Reloc.Addend = readVarint32(Ctx);
650       break;
651     case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
652       if (!isValidSectionSymbol(Reloc.Index))
653         return make_error<GenericBinaryError>("Bad relocation section index",
654                                               object_error::parse_failed);
655       Reloc.Addend = readVarint32(Ctx);
656       break;
657     default:
658       return make_error<GenericBinaryError>("Bad relocation type: " +
659                                                 Twine(Reloc.Type),
660                                             object_error::parse_failed);
661     }
662 
663     // Relocations must fit inside the section, and must appear in order.  They
664     // also shouldn't overlap a function/element boundary, but we don't bother
665     // to check that.
666     uint64_t Size = 5;
667     if (Reloc.Type == wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 ||
668         Reloc.Type == wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32 ||
669         Reloc.Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32 ||
670         Reloc.Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32)
671       Size = 4;
672     if (Reloc.Offset + Size > EndOffset)
673       return make_error<GenericBinaryError>("Bad relocation offset",
674                                             object_error::parse_failed);
675 
676     Section.Relocations.push_back(Reloc);
677   }
678   if (Ctx.Ptr != Ctx.End)
679     return make_error<GenericBinaryError>("Reloc section ended prematurely",
680                                           object_error::parse_failed);
681   return Error::success();
682 }
683 
684 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {
685   if (Sec.Name == "name") {
686     if (Error Err = parseNameSection(Ctx))
687       return Err;
688   } else if (Sec.Name == "linking") {
689     if (Error Err = parseLinkingSection(Ctx))
690       return Err;
691   } else if (Sec.Name.startswith("reloc.")) {
692     if (Error Err = parseRelocSection(Sec.Name, Ctx))
693       return Err;
694   }
695   return Error::success();
696 }
697 
698 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {
699   uint32_t Count = readVaruint32(Ctx);
700   Signatures.reserve(Count);
701   while (Count--) {
702     wasm::WasmSignature Sig;
703     Sig.ReturnType = wasm::WASM_TYPE_NORESULT;
704     uint8_t Form = readUint8(Ctx);
705     if (Form != wasm::WASM_TYPE_FUNC) {
706       return make_error<GenericBinaryError>("Invalid signature type",
707                                             object_error::parse_failed);
708     }
709     uint32_t ParamCount = readVaruint32(Ctx);
710     Sig.ParamTypes.reserve(ParamCount);
711     while (ParamCount--) {
712       uint32_t ParamType = readUint8(Ctx);
713       Sig.ParamTypes.push_back(ParamType);
714     }
715     uint32_t ReturnCount = readVaruint32(Ctx);
716     if (ReturnCount) {
717       if (ReturnCount != 1) {
718         return make_error<GenericBinaryError>(
719             "Multiple return types not supported", object_error::parse_failed);
720       }
721       Sig.ReturnType = readUint8(Ctx);
722     }
723     Signatures.push_back(Sig);
724   }
725   if (Ctx.Ptr != Ctx.End)
726     return make_error<GenericBinaryError>("Type section ended prematurely",
727                                           object_error::parse_failed);
728   return Error::success();
729 }
730 
731 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {
732   uint32_t Count = readVaruint32(Ctx);
733   Imports.reserve(Count);
734   for (uint32_t i = 0; i < Count; i++) {
735     wasm::WasmImport Im;
736     Im.Module = readString(Ctx);
737     Im.Field = readString(Ctx);
738     Im.Kind = readUint8(Ctx);
739     switch (Im.Kind) {
740     case wasm::WASM_EXTERNAL_FUNCTION:
741       NumImportedFunctions++;
742       Im.SigIndex = readVaruint32(Ctx);
743       break;
744     case wasm::WASM_EXTERNAL_GLOBAL:
745       NumImportedGlobals++;
746       Im.Global.Type = readUint8(Ctx);
747       Im.Global.Mutable = readVaruint1(Ctx);
748       break;
749     case wasm::WASM_EXTERNAL_MEMORY:
750       Im.Memory = readLimits(Ctx);
751       break;
752     case wasm::WASM_EXTERNAL_TABLE:
753       Im.Table = readTable(Ctx);
754       if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC)
755         return make_error<GenericBinaryError>("Invalid table element type",
756                                               object_error::parse_failed);
757       break;
758     default:
759       return make_error<GenericBinaryError>(
760           "Unexpected import kind", object_error::parse_failed);
761     }
762     Imports.push_back(Im);
763   }
764   if (Ctx.Ptr != Ctx.End)
765     return make_error<GenericBinaryError>("Import section ended prematurely",
766                                           object_error::parse_failed);
767   return Error::success();
768 }
769 
770 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {
771   uint32_t Count = readVaruint32(Ctx);
772   FunctionTypes.reserve(Count);
773   uint32_t NumTypes = Signatures.size();
774   while (Count--) {
775     uint32_t Type = readVaruint32(Ctx);
776     if (Type >= NumTypes)
777       return make_error<GenericBinaryError>("Invalid function type",
778                                             object_error::parse_failed);
779     FunctionTypes.push_back(Type);
780   }
781   if (Ctx.Ptr != Ctx.End)
782     return make_error<GenericBinaryError>("Function section ended prematurely",
783                                           object_error::parse_failed);
784   return Error::success();
785 }
786 
787 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {
788   uint32_t Count = readVaruint32(Ctx);
789   Tables.reserve(Count);
790   while (Count--) {
791     Tables.push_back(readTable(Ctx));
792     if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
793       return make_error<GenericBinaryError>("Invalid table element type",
794                                             object_error::parse_failed);
795     }
796   }
797   if (Ctx.Ptr != Ctx.End)
798     return make_error<GenericBinaryError>("Table section ended prematurely",
799                                           object_error::parse_failed);
800   return Error::success();
801 }
802 
803 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {
804   uint32_t Count = readVaruint32(Ctx);
805   Memories.reserve(Count);
806   while (Count--) {
807     Memories.push_back(readLimits(Ctx));
808   }
809   if (Ctx.Ptr != Ctx.End)
810     return make_error<GenericBinaryError>("Memory section ended prematurely",
811                                           object_error::parse_failed);
812   return Error::success();
813 }
814 
815 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {
816   GlobalSection = Sections.size();
817   uint32_t Count = readVaruint32(Ctx);
818   Globals.reserve(Count);
819   while (Count--) {
820     wasm::WasmGlobal Global;
821     Global.Index = NumImportedGlobals + Globals.size();
822     Global.Type.Type = readUint8(Ctx);
823     Global.Type.Mutable = readVaruint1(Ctx);
824     if (Error Err = readInitExpr(Global.InitExpr, Ctx))
825       return Err;
826     Globals.push_back(Global);
827   }
828   if (Ctx.Ptr != Ctx.End)
829     return make_error<GenericBinaryError>("Global section ended prematurely",
830                                           object_error::parse_failed);
831   return Error::success();
832 }
833 
834 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {
835   uint32_t Count = readVaruint32(Ctx);
836   Exports.reserve(Count);
837   for (uint32_t i = 0; i < Count; i++) {
838     wasm::WasmExport Ex;
839     Ex.Name = readString(Ctx);
840     Ex.Kind = readUint8(Ctx);
841     Ex.Index = readVaruint32(Ctx);
842     switch (Ex.Kind) {
843     case wasm::WASM_EXTERNAL_FUNCTION:
844       if (!isValidFunctionIndex(Ex.Index))
845         return make_error<GenericBinaryError>("Invalid function export",
846                                               object_error::parse_failed);
847       break;
848     case wasm::WASM_EXTERNAL_GLOBAL:
849       if (!isValidGlobalIndex(Ex.Index))
850         return make_error<GenericBinaryError>("Invalid global export",
851                                               object_error::parse_failed);
852       break;
853     case wasm::WASM_EXTERNAL_MEMORY:
854     case wasm::WASM_EXTERNAL_TABLE:
855       break;
856     default:
857       return make_error<GenericBinaryError>(
858           "Unexpected export kind", object_error::parse_failed);
859     }
860     Exports.push_back(Ex);
861   }
862   if (Ctx.Ptr != Ctx.End)
863     return make_error<GenericBinaryError>("Export section ended prematurely",
864                                           object_error::parse_failed);
865   return Error::success();
866 }
867 
868 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
869   return Index < NumImportedFunctions + FunctionTypes.size();
870 }
871 
872 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {
873   return Index >= NumImportedFunctions && isValidFunctionIndex(Index);
874 }
875 
876 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {
877   return Index < NumImportedGlobals + Globals.size();
878 }
879 
880 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {
881   return Index >= NumImportedGlobals && isValidGlobalIndex(Index);
882 }
883 
884 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {
885   return Index < Symbols.size() && Symbols[Index].isTypeFunction();
886 }
887 
888 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {
889   return Index < Symbols.size() && Symbols[Index].isTypeGlobal();
890 }
891 
892 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {
893   return Index < Symbols.size() && Symbols[Index].isTypeData();
894 }
895 
896 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {
897   return Index < Symbols.size() && Symbols[Index].isTypeSection();
898 }
899 
900 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {
901   assert(isDefinedFunctionIndex(Index));
902   return Functions[Index - NumImportedFunctions];
903 }
904 
905 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) {
906   assert(isDefinedGlobalIndex(Index));
907   return Globals[Index - NumImportedGlobals];
908 }
909 
910 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {
911   StartFunction = readVaruint32(Ctx);
912   if (!isValidFunctionIndex(StartFunction))
913     return make_error<GenericBinaryError>("Invalid start function",
914                                           object_error::parse_failed);
915   return Error::success();
916 }
917 
918 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {
919   CodeSection = Sections.size();
920   uint32_t FunctionCount = readVaruint32(Ctx);
921   if (FunctionCount != FunctionTypes.size()) {
922     return make_error<GenericBinaryError>("Invalid function count",
923                                           object_error::parse_failed);
924   }
925 
926   while (FunctionCount--) {
927     wasm::WasmFunction Function;
928     const uint8_t *FunctionStart = Ctx.Ptr;
929     uint32_t Size = readVaruint32(Ctx);
930     const uint8_t *FunctionEnd = Ctx.Ptr + Size;
931 
932     Function.CodeOffset = Ctx.Ptr - FunctionStart;
933     Function.Index = NumImportedFunctions + Functions.size();
934     Function.CodeSectionOffset = FunctionStart - Ctx.Start;
935     Function.Size = FunctionEnd - FunctionStart;
936 
937     uint32_t NumLocalDecls = readVaruint32(Ctx);
938     Function.Locals.reserve(NumLocalDecls);
939     while (NumLocalDecls--) {
940       wasm::WasmLocalDecl Decl;
941       Decl.Count = readVaruint32(Ctx);
942       Decl.Type = readUint8(Ctx);
943       Function.Locals.push_back(Decl);
944     }
945 
946     uint32_t BodySize = FunctionEnd - Ctx.Ptr;
947     Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);
948     // This will be set later when reading in the linking metadata section.
949     Function.Comdat = UINT32_MAX;
950     Ctx.Ptr += BodySize;
951     assert(Ctx.Ptr == FunctionEnd);
952     Functions.push_back(Function);
953   }
954   if (Ctx.Ptr != Ctx.End)
955     return make_error<GenericBinaryError>("Code section ended prematurely",
956                                           object_error::parse_failed);
957   return Error::success();
958 }
959 
960 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {
961   uint32_t Count = readVaruint32(Ctx);
962   ElemSegments.reserve(Count);
963   while (Count--) {
964     wasm::WasmElemSegment Segment;
965     Segment.TableIndex = readVaruint32(Ctx);
966     if (Segment.TableIndex != 0) {
967       return make_error<GenericBinaryError>("Invalid TableIndex",
968                                             object_error::parse_failed);
969     }
970     if (Error Err = readInitExpr(Segment.Offset, Ctx))
971       return Err;
972     uint32_t NumElems = readVaruint32(Ctx);
973     while (NumElems--) {
974       Segment.Functions.push_back(readVaruint32(Ctx));
975     }
976     ElemSegments.push_back(Segment);
977   }
978   if (Ctx.Ptr != Ctx.End)
979     return make_error<GenericBinaryError>("Elem section ended prematurely",
980                                           object_error::parse_failed);
981   return Error::success();
982 }
983 
984 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {
985   DataSection = Sections.size();
986   uint32_t Count = readVaruint32(Ctx);
987   DataSegments.reserve(Count);
988   while (Count--) {
989     WasmSegment Segment;
990     Segment.Data.MemoryIndex = readVaruint32(Ctx);
991     if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
992       return Err;
993     uint32_t Size = readVaruint32(Ctx);
994     if (Size > (size_t)(Ctx.End - Ctx.Ptr))
995       return make_error<GenericBinaryError>("Invalid segment size",
996                                             object_error::parse_failed);
997     Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
998     // The rest of these Data fields are set later, when reading in the linking
999     // metadata section.
1000     Segment.Data.Alignment = 0;
1001     Segment.Data.Flags = 0;
1002     Segment.Data.Comdat = UINT32_MAX;
1003     Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
1004     Ctx.Ptr += Size;
1005     DataSegments.push_back(Segment);
1006   }
1007   if (Ctx.Ptr != Ctx.End)
1008     return make_error<GenericBinaryError>("Data section ended prematurely",
1009                                           object_error::parse_failed);
1010   return Error::success();
1011 }
1012 
1013 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
1014   return reinterpret_cast<const uint8_t *>(getData().data() + Offset);
1015 }
1016 
1017 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
1018   return Header;
1019 }
1020 
1021 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
1022 
1023 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
1024   uint32_t Result = SymbolRef::SF_None;
1025   const WasmSymbol &Sym = getWasmSymbol(Symb);
1026 
1027   LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
1028   if (Sym.isBindingWeak())
1029     Result |= SymbolRef::SF_Weak;
1030   if (!Sym.isBindingLocal())
1031     Result |= SymbolRef::SF_Global;
1032   if (Sym.isHidden())
1033     Result |= SymbolRef::SF_Hidden;
1034   if (!Sym.isDefined())
1035     Result |= SymbolRef::SF_Undefined;
1036   if (Sym.isTypeFunction())
1037     Result |= SymbolRef::SF_Executable;
1038   return Result;
1039 }
1040 
1041 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
1042   DataRefImpl Ref;
1043   Ref.d.a = 0;
1044   return BasicSymbolRef(Ref, this);
1045 }
1046 
1047 basic_symbol_iterator WasmObjectFile::symbol_end() const {
1048   DataRefImpl Ref;
1049   Ref.d.a = Symbols.size();
1050   return BasicSymbolRef(Ref, this);
1051 }
1052 
1053 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
1054   return Symbols[Symb.d.a];
1055 }
1056 
1057 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
1058   return getWasmSymbol(Symb.getRawDataRefImpl());
1059 }
1060 
1061 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
1062   return getWasmSymbol(Symb).Info.Name;
1063 }
1064 
1065 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
1066   return getSymbolValue(Symb);
1067 }
1068 
1069 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol& Sym) const {
1070   switch (Sym.Info.Kind) {
1071   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1072   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1073     return Sym.Info.ElementIndex;
1074   case wasm::WASM_SYMBOL_TYPE_DATA: {
1075     // The value of a data symbol is the segment offset, plus the symbol
1076     // offset within the segment.
1077     uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
1078     const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
1079     assert(Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST);
1080     return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset;
1081   }
1082   case wasm::WASM_SYMBOL_TYPE_SECTION:
1083     return 0;
1084   }
1085   llvm_unreachable("invalid symbol type");
1086 }
1087 
1088 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
1089   return getWasmSymbolValue(getWasmSymbol(Symb));
1090 }
1091 
1092 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
1093   llvm_unreachable("not yet implemented");
1094   return 0;
1095 }
1096 
1097 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
1098   llvm_unreachable("not yet implemented");
1099   return 0;
1100 }
1101 
1102 Expected<SymbolRef::Type>
1103 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
1104   const WasmSymbol &Sym = getWasmSymbol(Symb);
1105 
1106   switch (Sym.Info.Kind) {
1107   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1108     return SymbolRef::ST_Function;
1109   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1110     return SymbolRef::ST_Other;
1111   case wasm::WASM_SYMBOL_TYPE_DATA:
1112     return SymbolRef::ST_Data;
1113   case wasm::WASM_SYMBOL_TYPE_SECTION:
1114     return SymbolRef::ST_Debug;
1115   }
1116 
1117   llvm_unreachable("Unknown WasmSymbol::SymbolType");
1118   return SymbolRef::ST_Other;
1119 }
1120 
1121 Expected<section_iterator>
1122 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
1123   const WasmSymbol& Sym = getWasmSymbol(Symb);
1124   if (Sym.isUndefined())
1125     return section_end();
1126 
1127   DataRefImpl Ref;
1128   switch (Sym.Info.Kind) {
1129   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1130     Ref.d.a = CodeSection;
1131     break;
1132   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1133     Ref.d.a = GlobalSection;
1134     break;
1135   case wasm::WASM_SYMBOL_TYPE_DATA:
1136     Ref.d.a = DataSection;
1137     break;
1138   case wasm::WASM_SYMBOL_TYPE_SECTION: {
1139     Ref.d.a = Sym.Info.ElementIndex;
1140     break;
1141   }
1142   default:
1143     llvm_unreachable("Unknown WasmSymbol::SymbolType");
1144   }
1145   return section_iterator(SectionRef(Ref, this));
1146 }
1147 
1148 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
1149 
1150 std::error_code WasmObjectFile::getSectionName(DataRefImpl Sec,
1151                                                StringRef &Res) const {
1152   const WasmSection &S = Sections[Sec.d.a];
1153 #define ECase(X)                                                               \
1154   case wasm::WASM_SEC_##X:                                                     \
1155     Res = #X;                                                                  \
1156     break
1157   switch (S.Type) {
1158     ECase(TYPE);
1159     ECase(IMPORT);
1160     ECase(FUNCTION);
1161     ECase(TABLE);
1162     ECase(MEMORY);
1163     ECase(GLOBAL);
1164     ECase(EXPORT);
1165     ECase(START);
1166     ECase(ELEM);
1167     ECase(CODE);
1168     ECase(DATA);
1169   case wasm::WASM_SEC_CUSTOM:
1170     Res = S.Name;
1171     break;
1172   default:
1173     return object_error::invalid_section_index;
1174   }
1175 #undef ECase
1176   return std::error_code();
1177 }
1178 
1179 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
1180 
1181 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
1182   return Sec.d.a;
1183 }
1184 
1185 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
1186   const WasmSection &S = Sections[Sec.d.a];
1187   return S.Content.size();
1188 }
1189 
1190 std::error_code WasmObjectFile::getSectionContents(DataRefImpl Sec,
1191                                                    StringRef &Res) const {
1192   const WasmSection &S = Sections[Sec.d.a];
1193   // This will never fail since wasm sections can never be empty (user-sections
1194   // must have a name and non-user sections each have a defined structure).
1195   Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
1196                   S.Content.size());
1197   return std::error_code();
1198 }
1199 
1200 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1201   return 1;
1202 }
1203 
1204 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1205   return false;
1206 }
1207 
1208 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
1209   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
1210 }
1211 
1212 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
1213   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
1214 }
1215 
1216 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
1217 
1218 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
1219 
1220 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
1221 
1222 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
1223   DataRefImpl RelocRef;
1224   RelocRef.d.a = Ref.d.a;
1225   RelocRef.d.b = 0;
1226   return relocation_iterator(RelocationRef(RelocRef, this));
1227 }
1228 
1229 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
1230   const WasmSection &Sec = getWasmSection(Ref);
1231   DataRefImpl RelocRef;
1232   RelocRef.d.a = Ref.d.a;
1233   RelocRef.d.b = Sec.Relocations.size();
1234   return relocation_iterator(RelocationRef(RelocRef, this));
1235 }
1236 
1237 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1238   Rel.d.b++;
1239 }
1240 
1241 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1242   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1243   return Rel.Offset;
1244 }
1245 
1246 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
1247   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1248   if (Rel.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1249     return symbol_end();
1250   DataRefImpl Sym;
1251   Sym.d.a = Rel.Index;
1252   Sym.d.b = 0;
1253   return symbol_iterator(SymbolRef(Sym, this));
1254 }
1255 
1256 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1257   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1258   return Rel.Type;
1259 }
1260 
1261 void WasmObjectFile::getRelocationTypeName(
1262     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1263   const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
1264   StringRef Res = "Unknown";
1265 
1266 #define WASM_RELOC(name, value)  \
1267   case wasm::name:              \
1268     Res = #name;               \
1269     break;
1270 
1271   switch (Rel.Type) {
1272 #include "llvm/BinaryFormat/WasmRelocs.def"
1273   }
1274 
1275 #undef WASM_RELOC
1276 
1277   Result.append(Res.begin(), Res.end());
1278 }
1279 
1280 section_iterator WasmObjectFile::section_begin() const {
1281   DataRefImpl Ref;
1282   Ref.d.a = 0;
1283   return section_iterator(SectionRef(Ref, this));
1284 }
1285 
1286 section_iterator WasmObjectFile::section_end() const {
1287   DataRefImpl Ref;
1288   Ref.d.a = Sections.size();
1289   return section_iterator(SectionRef(Ref, this));
1290 }
1291 
1292 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1293 
1294 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1295 
1296 Triple::ArchType WasmObjectFile::getArch() const { return Triple::wasm32; }
1297 
1298 SubtargetFeatures WasmObjectFile::getFeatures() const {
1299   return SubtargetFeatures();
1300 }
1301 
1302 bool WasmObjectFile::isRelocatableObject() const {
1303   return HasLinkingSection;
1304 }
1305 
1306 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1307   assert(Ref.d.a < Sections.size());
1308   return Sections[Ref.d.a];
1309 }
1310 
1311 const WasmSection &
1312 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1313   return getWasmSection(Section.getRawDataRefImpl());
1314 }
1315 
1316 const wasm::WasmRelocation &
1317 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1318   return getWasmRelocation(Ref.getRawDataRefImpl());
1319 }
1320 
1321 const wasm::WasmRelocation &
1322 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1323   assert(Ref.d.a < Sections.size());
1324   const WasmSection& Sec = Sections[Ref.d.a];
1325   assert(Ref.d.b < Sec.Relocations.size());
1326   return Sec.Relocations[Ref.d.b];
1327 }
1328