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