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