OSDN Git Service

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