OSDN Git Service

[WebAssembly] Expose the offset of each data segment
[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/STLExtras.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/BinaryFormat/Wasm.h"
15 #include "llvm/MC/SubtargetFeature.h"
16 #include "llvm/Object/Binary.h"
17 #include "llvm/Object/Error.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/Object/SymbolicFile.h"
20 #include "llvm/Object/Wasm.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstdint>
28 #include <cstring>
29 #include <system_error>
30
31 #define DEBUG_TYPE "wasm-object"
32
33 using namespace llvm;
34 using namespace object;
35
36 Expected<std::unique_ptr<WasmObjectFile>>
37 ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {
38   Error Err = Error::success();
39   auto ObjectFile = llvm::make_unique<WasmObjectFile>(Buffer, Err);
40   if (Err)
41     return std::move(Err);
42
43   return std::move(ObjectFile);
44 }
45
46 #define VARINT7_MAX ((1<<7)-1)
47 #define VARINT7_MIN (-(1<<7))
48 #define VARUINT7_MAX (1<<7)
49 #define VARUINT1_MAX (1)
50
51 static uint8_t readUint8(const uint8_t *&Ptr) { return *Ptr++; }
52
53 static uint32_t readUint32(const uint8_t *&Ptr) {
54   uint32_t Result = support::endian::read32le(Ptr);
55   Ptr += sizeof(Result);
56   return Result;
57 }
58
59 static int32_t readFloat32(const uint8_t *&Ptr) {
60   int32_t Result = 0;
61   memcpy(&Result, Ptr, sizeof(Result));
62   Ptr += sizeof(Result);
63   return Result;
64 }
65
66 static int64_t readFloat64(const uint8_t *&Ptr) {
67   int64_t Result = 0;
68   memcpy(&Result, Ptr, sizeof(Result));
69   Ptr += sizeof(Result);
70   return Result;
71 }
72
73 static uint64_t readULEB128(const uint8_t *&Ptr) {
74   unsigned Count;
75   uint64_t Result = decodeULEB128(Ptr, &Count);
76   Ptr += Count;
77   return Result;
78 }
79
80 static StringRef readString(const uint8_t *&Ptr) {
81   uint32_t StringLen = readULEB128(Ptr);
82   StringRef Return = StringRef(reinterpret_cast<const char *>(Ptr), StringLen);
83   Ptr += StringLen;
84   return Return;
85 }
86
87 static int64_t readLEB128(const uint8_t *&Ptr) {
88   unsigned Count;
89   uint64_t Result = decodeSLEB128(Ptr, &Count);
90   Ptr += Count;
91   return Result;
92 }
93
94 static uint8_t readVaruint1(const uint8_t *&Ptr) {
95   int64_t result = readLEB128(Ptr);
96   assert(result <= VARUINT1_MAX && result >= 0);
97   return result;
98 }
99
100 static int8_t readVarint7(const uint8_t *&Ptr) {
101   int64_t result = readLEB128(Ptr);
102   assert(result <= VARINT7_MAX && result >= VARINT7_MIN);
103   return result;
104 }
105
106 static uint8_t readVaruint7(const uint8_t *&Ptr) {
107   uint64_t result = readULEB128(Ptr);
108   assert(result <= VARUINT7_MAX);
109   return result;
110 }
111
112 static int32_t readVarint32(const uint8_t *&Ptr) {
113   int64_t result = readLEB128(Ptr);
114   assert(result <= INT32_MAX && result >= INT32_MIN);
115   return result;
116 }
117
118 static uint32_t readVaruint32(const uint8_t *&Ptr) {
119   uint64_t result = readULEB128(Ptr);
120   assert(result <= UINT32_MAX);
121   return result;
122 }
123
124 static int64_t readVarint64(const uint8_t *&Ptr) {
125   return readLEB128(Ptr);
126 }
127
128 static uint8_t readOpcode(const uint8_t *&Ptr) {
129   return readUint8(Ptr);
130 }
131
132 static Error readInitExpr(wasm::WasmInitExpr &Expr, const uint8_t *&Ptr) {
133   Expr.Opcode = readOpcode(Ptr);
134
135   switch (Expr.Opcode) {
136   case wasm::WASM_OPCODE_I32_CONST:
137     Expr.Value.Int32 = readVarint32(Ptr);
138     break;
139   case wasm::WASM_OPCODE_I64_CONST:
140     Expr.Value.Int64 = readVarint64(Ptr);
141     break;
142   case wasm::WASM_OPCODE_F32_CONST:
143     Expr.Value.Float32 = readFloat32(Ptr);
144     break;
145   case wasm::WASM_OPCODE_F64_CONST:
146     Expr.Value.Float64 = readFloat64(Ptr);
147     break;
148   case wasm::WASM_OPCODE_GET_GLOBAL:
149     Expr.Value.Global = readULEB128(Ptr);
150     break;
151   default:
152     return make_error<GenericBinaryError>("Invalid opcode in init_expr",
153                                           object_error::parse_failed);
154   }
155
156   uint8_t EndOpcode = readOpcode(Ptr);
157   if (EndOpcode != wasm::WASM_OPCODE_END) {
158     return make_error<GenericBinaryError>("Invalid init_expr",
159                                           object_error::parse_failed);
160   }
161   return Error::success();
162 }
163
164 static wasm::WasmLimits readLimits(const uint8_t *&Ptr) {
165   wasm::WasmLimits Result;
166   Result.Flags = readVaruint1(Ptr);
167   Result.Initial = readVaruint32(Ptr);
168   if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
169     Result.Maximum = readVaruint32(Ptr);
170   return Result;
171 }
172
173 static wasm::WasmTable readTable(const uint8_t *&Ptr) {
174   wasm::WasmTable Table;
175   Table.ElemType = readVarint7(Ptr);
176   Table.Limits = readLimits(Ptr);
177   return Table;
178 }
179
180 static Error readSection(WasmSection &Section, const uint8_t *&Ptr,
181                          const uint8_t *Start) {
182   // TODO(sbc): Avoid reading past EOF in the case of malformed files.
183   Section.Offset = Ptr - Start;
184   Section.Type = readVaruint7(Ptr);
185   uint32_t Size = readVaruint32(Ptr);
186   if (Size == 0)
187     return make_error<StringError>("Zero length section",
188                                    object_error::parse_failed);
189   Section.Content = ArrayRef<uint8_t>(Ptr, Size);
190   Ptr += Size;
191   return Error::success();
192 }
193
194 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
195     : ObjectFile(Binary::ID_Wasm, Buffer) {
196   LinkingData.DataAlignment = 0;
197   LinkingData.DataSize = 0;
198
199   ErrorAsOutParameter ErrAsOutParam(&Err);
200   Header.Magic = getData().substr(0, 4);
201   if (Header.Magic != StringRef("\0asm", 4)) {
202     Err = make_error<StringError>("Bad magic number",
203                                   object_error::parse_failed);
204     return;
205   }
206   const uint8_t *Ptr = getPtr(4);
207   Header.Version = readUint32(Ptr);
208   if (Header.Version != wasm::WasmVersion) {
209     Err = make_error<StringError>("Bad version number",
210                                   object_error::parse_failed);
211     return;
212   }
213
214   const uint8_t *Eof = getPtr(getData().size());
215   WasmSection Sec;
216   while (Ptr < Eof) {
217     if ((Err = readSection(Sec, Ptr, getPtr(0))))
218       return;
219     if ((Err = parseSection(Sec)))
220       return;
221
222     Sections.push_back(Sec);
223   }
224 }
225
226 Error WasmObjectFile::parseSection(WasmSection &Sec) {
227   const uint8_t* Start = Sec.Content.data();
228   const uint8_t* End = Start + Sec.Content.size();
229   switch (Sec.Type) {
230   case wasm::WASM_SEC_CUSTOM:
231     return parseCustomSection(Sec, Start, End);
232   case wasm::WASM_SEC_TYPE:
233     return parseTypeSection(Start, End);
234   case wasm::WASM_SEC_IMPORT:
235     return parseImportSection(Start, End);
236   case wasm::WASM_SEC_FUNCTION:
237     return parseFunctionSection(Start, End);
238   case wasm::WASM_SEC_TABLE:
239     return parseTableSection(Start, End);
240   case wasm::WASM_SEC_MEMORY:
241     return parseMemorySection(Start, End);
242   case wasm::WASM_SEC_GLOBAL:
243     return parseGlobalSection(Start, End);
244   case wasm::WASM_SEC_EXPORT:
245     return parseExportSection(Start, End);
246   case wasm::WASM_SEC_START:
247     return parseStartSection(Start, End);
248   case wasm::WASM_SEC_ELEM:
249     return parseElemSection(Start, End);
250   case wasm::WASM_SEC_CODE:
251     return parseCodeSection(Start, End);
252   case wasm::WASM_SEC_DATA:
253     return parseDataSection(Start, End);
254   default:
255     return make_error<GenericBinaryError>("Bad section type",
256                                           object_error::parse_failed);
257   }
258 }
259
260 Error WasmObjectFile::parseNameSection(const uint8_t *Ptr, const uint8_t *End) {
261   while (Ptr < End) {
262     uint8_t Type = readVarint7(Ptr);
263     uint32_t Size = readVaruint32(Ptr);
264     const uint8_t *SubSectionEnd = Ptr + Size;
265     switch (Type) {
266     case wasm::WASM_NAMES_FUNCTION: {
267       uint32_t Count = readVaruint32(Ptr);
268       while (Count--) {
269         uint32_t Index = readVaruint32(Ptr);
270         StringRef Name = readString(Ptr);
271         if (!Name.empty())
272           Symbols.emplace_back(Name,
273                                WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME,
274                                Sections.size(), Index);
275       }
276       break;
277     }
278     // Ignore local names for now
279     case wasm::WASM_NAMES_LOCAL:
280     default:
281       Ptr += Size;
282       break;
283     }
284     if (Ptr != SubSectionEnd)
285       return make_error<GenericBinaryError>("Name sub-section ended prematurely",
286                                             object_error::parse_failed);
287   }
288
289   if (Ptr != End)
290     return make_error<GenericBinaryError>("Name section ended prematurely",
291                                           object_error::parse_failed);
292   return Error::success();
293 }
294
295 Error WasmObjectFile::parseLinkingSection(const uint8_t *Ptr,
296                                           const uint8_t *End) {
297   HasLinkingSection = true;
298   while (Ptr < End) {
299     uint8_t Type = readVarint7(Ptr);
300     uint32_t Size = readVaruint32(Ptr);
301     const uint8_t *SubSectionEnd = Ptr + Size;
302     switch (Type) {
303     case wasm::WASM_SYMBOL_INFO: {
304       uint32_t Count = readVaruint32(Ptr);
305       while (Count--) {
306         StringRef Symbol = readString(Ptr);
307         DEBUG(dbgs() << "reading syminfo: " << Symbol << "\n");
308         uint32_t Flags = readVaruint32(Ptr);
309         auto iter = SymbolMap.find(Symbol);
310         if (iter == SymbolMap.end()) {
311           return make_error<GenericBinaryError>(
312               "Invalid symbol name in linking section: " + Symbol,
313               object_error::parse_failed);
314         }
315         uint32_t SymIndex = iter->second;
316         assert(SymIndex < Symbols.size());
317         Symbols[SymIndex].Flags = Flags;
318         DEBUG(dbgs() << "Set symbol flags index:"
319                      << SymIndex << " name:"
320                      << Symbols[SymIndex].Name << " exptected:"
321                      << Symbol << " flags: " << Flags << "\n");
322       }
323       break;
324     }
325     case wasm::WASM_DATA_SIZE:
326       LinkingData.DataSize = readVaruint32(Ptr);
327       break;
328     case wasm::WASM_DATA_ALIGNMENT:
329       LinkingData.DataAlignment = readVaruint32(Ptr);
330       break;
331     case wasm::WASM_STACK_POINTER:
332     default:
333       Ptr += Size;
334       break;
335     }
336     if (Ptr != SubSectionEnd)
337       return make_error<GenericBinaryError>(
338           "Linking sub-section ended prematurely", object_error::parse_failed);
339   }
340   if (Ptr != End)
341     return make_error<GenericBinaryError>("Linking section ended prematurely",
342                                           object_error::parse_failed);
343   return Error::success();
344 }
345
346 WasmSection* WasmObjectFile::findCustomSectionByName(StringRef Name) {
347   for (WasmSection& Section : Sections) {
348     if (Section.Type == wasm::WASM_SEC_CUSTOM && Section.Name == Name)
349       return &Section;
350   }
351   return nullptr;
352 }
353
354 WasmSection* WasmObjectFile::findSectionByType(uint32_t Type) {
355   assert(Type != wasm::WASM_SEC_CUSTOM);
356   for (WasmSection& Section : Sections) {
357     if (Section.Type == Type)
358       return &Section;
359   }
360   return nullptr;
361 }
362
363 Error WasmObjectFile::parseRelocSection(StringRef Name, const uint8_t *Ptr,
364                                         const uint8_t *End) {
365   uint8_t SectionCode = readVarint7(Ptr);
366   WasmSection* Section = nullptr;
367   if (SectionCode == wasm::WASM_SEC_CUSTOM) {
368     StringRef Name = readString(Ptr);
369     Section = findCustomSectionByName(Name);
370   } else {
371     Section = findSectionByType(SectionCode);
372   }
373   if (!Section)
374     return make_error<GenericBinaryError>("Invalid section code",
375                                           object_error::parse_failed);
376   uint32_t RelocCount = readVaruint32(Ptr);
377   while (RelocCount--) {
378     wasm::WasmRelocation Reloc;
379     memset(&Reloc, 0, sizeof(Reloc));
380     Reloc.Type = readVaruint32(Ptr);
381     Reloc.Offset = readVaruint32(Ptr);
382     Reloc.Index = readVaruint32(Ptr);
383     switch (Reloc.Type) {
384     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
385     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
386     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
387     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
388     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
389       break;
390     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
391     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
392     case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
393       Reloc.Addend = readVarint32(Ptr);
394       break;
395     default:
396       return make_error<GenericBinaryError>("Bad relocation type: " +
397                                                 Twine(Reloc.Type),
398                                             object_error::parse_failed);
399     }
400     Section->Relocations.push_back(Reloc);
401   }
402   if (Ptr != End)
403     return make_error<GenericBinaryError>("Reloc section ended prematurely",
404                                           object_error::parse_failed);
405   return Error::success();
406 }
407
408 Error WasmObjectFile::parseCustomSection(WasmSection &Sec,
409                                          const uint8_t *Ptr, const uint8_t *End) {
410   Sec.Name = readString(Ptr);
411   if (Sec.Name == "name") {
412     if (Error Err = parseNameSection(Ptr, End))
413       return Err;
414   } else if (Sec.Name == "linking") {
415     if (Error Err = parseLinkingSection(Ptr, End))
416       return Err;
417   } else if (Sec.Name.startswith("reloc.")) {
418     if (Error Err = parseRelocSection(Sec.Name, Ptr, End))
419       return Err;
420   }
421   return Error::success();
422 }
423
424 Error WasmObjectFile::parseTypeSection(const uint8_t *Ptr, const uint8_t *End) {
425   uint32_t Count = readVaruint32(Ptr);
426   Signatures.reserve(Count);
427   while (Count--) {
428     wasm::WasmSignature Sig;
429     Sig.ReturnType = wasm::WASM_TYPE_NORESULT;
430     int8_t Form = readVarint7(Ptr);
431     if (Form != wasm::WASM_TYPE_FUNC) {
432       return make_error<GenericBinaryError>("Invalid signature type",
433                                             object_error::parse_failed);
434     }
435     uint32_t ParamCount = readVaruint32(Ptr);
436     Sig.ParamTypes.reserve(ParamCount);
437     while (ParamCount--) {
438       uint32_t ParamType = readVarint7(Ptr);
439       Sig.ParamTypes.push_back(ParamType);
440     }
441     uint32_t ReturnCount = readVaruint32(Ptr);
442     if (ReturnCount) {
443       if (ReturnCount != 1) {
444         return make_error<GenericBinaryError>(
445             "Multiple return types not supported", object_error::parse_failed);
446       }
447       Sig.ReturnType = readVarint7(Ptr);
448     }
449     Signatures.push_back(Sig);
450   }
451   if (Ptr != End)
452     return make_error<GenericBinaryError>("Type section ended prematurely",
453                                           object_error::parse_failed);
454   return Error::success();
455 }
456
457 Error WasmObjectFile::parseImportSection(const uint8_t *Ptr, const uint8_t *End) {
458   uint32_t Count = readVaruint32(Ptr);
459   Imports.reserve(Count);
460   for (uint32_t i = 0; i < Count; i++) {
461     wasm::WasmImport Im;
462     Im.Module = readString(Ptr);
463     Im.Field = readString(Ptr);
464     Im.Kind = readUint8(Ptr);
465     switch (Im.Kind) {
466     case wasm::WASM_EXTERNAL_FUNCTION:
467       Im.SigIndex = readVaruint32(Ptr);
468       SymbolMap.try_emplace(Im.Field, Symbols.size());
469       Symbols.emplace_back(Im.Field, WasmSymbol::SymbolType::FUNCTION_IMPORT,
470                            Sections.size(), i);
471       DEBUG(dbgs() << "Adding import: " << Symbols.back()
472                    << " sym index:" << Symbols.size() << "\n");
473       break;
474     case wasm::WASM_EXTERNAL_GLOBAL:
475       Im.Global.Type = readVarint7(Ptr);
476       Im.Global.Mutable = readVaruint1(Ptr);
477       SymbolMap.try_emplace(Im.Field, Symbols.size());
478       Symbols.emplace_back(Im.Field, WasmSymbol::SymbolType::GLOBAL_IMPORT,
479                            Sections.size(), i);
480       DEBUG(dbgs() << "Adding import: " << Symbols.back()
481                    << " sym index:" << Symbols.size() << "\n");
482       break;
483     case wasm::WASM_EXTERNAL_MEMORY:
484       Im.Memory = readLimits(Ptr);
485       break;
486     case wasm::WASM_EXTERNAL_TABLE:
487       Im.Table = readTable(Ptr);
488       if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC) {
489         return make_error<GenericBinaryError>("Invalid table element type",
490                                               object_error::parse_failed);
491       }
492       break;
493     default:
494       return make_error<GenericBinaryError>(
495           "Unexpected import kind", object_error::parse_failed);
496     }
497     Imports.push_back(Im);
498   }
499   if (Ptr != End)
500     return make_error<GenericBinaryError>("Import section ended prematurely",
501                                           object_error::parse_failed);
502   return Error::success();
503 }
504
505 Error WasmObjectFile::parseFunctionSection(const uint8_t *Ptr, const uint8_t *End) {
506   uint32_t Count = readVaruint32(Ptr);
507   FunctionTypes.reserve(Count);
508   while (Count--) {
509     FunctionTypes.push_back(readVaruint32(Ptr));
510   }
511   if (Ptr != End)
512     return make_error<GenericBinaryError>("Function section ended prematurely",
513                                           object_error::parse_failed);
514   return Error::success();
515 }
516
517 Error WasmObjectFile::parseTableSection(const uint8_t *Ptr, const uint8_t *End) {
518   uint32_t Count = readVaruint32(Ptr);
519   Tables.reserve(Count);
520   while (Count--) {
521     Tables.push_back(readTable(Ptr));
522     if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
523       return make_error<GenericBinaryError>("Invalid table element type",
524                                             object_error::parse_failed);
525     }
526   }
527   if (Ptr != End)
528     return make_error<GenericBinaryError>("Table section ended prematurely",
529                                           object_error::parse_failed);
530   return Error::success();
531 }
532
533 Error WasmObjectFile::parseMemorySection(const uint8_t *Ptr, const uint8_t *End) {
534   uint32_t Count = readVaruint32(Ptr);
535   Memories.reserve(Count);
536   while (Count--) {
537     Memories.push_back(readLimits(Ptr));
538   }
539   if (Ptr != End)
540     return make_error<GenericBinaryError>("Memory section ended prematurely",
541                                           object_error::parse_failed);
542   return Error::success();
543 }
544
545 Error WasmObjectFile::parseGlobalSection(const uint8_t *Ptr, const uint8_t *End) {
546   uint32_t Count = readVaruint32(Ptr);
547   Globals.reserve(Count);
548   while (Count--) {
549     wasm::WasmGlobal Global;
550     Global.Type = readVarint7(Ptr);
551     Global.Mutable = readVaruint1(Ptr);
552     if (Error Err = readInitExpr(Global.InitExpr, Ptr))
553       return Err;
554     Globals.push_back(Global);
555   }
556   if (Ptr != End)
557     return make_error<GenericBinaryError>("Global section ended prematurely",
558                                           object_error::parse_failed);
559   return Error::success();
560 }
561
562 Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) {
563   uint32_t Count = readVaruint32(Ptr);
564   Exports.reserve(Count);
565   for (uint32_t i = 0; i < Count; i++) {
566     wasm::WasmExport Ex;
567     Ex.Name = readString(Ptr);
568     Ex.Kind = readUint8(Ptr);
569     Ex.Index = readVaruint32(Ptr);
570     WasmSymbol::SymbolType ExportType;
571     bool MakeSymbol = false;
572     switch (Ex.Kind) {
573     case wasm::WASM_EXTERNAL_FUNCTION:
574       ExportType = WasmSymbol::SymbolType::FUNCTION_EXPORT;
575       MakeSymbol = true;
576       break;
577     case wasm::WASM_EXTERNAL_GLOBAL:
578       ExportType = WasmSymbol::SymbolType::GLOBAL_EXPORT;
579       MakeSymbol = true;
580       break;
581     case wasm::WASM_EXTERNAL_MEMORY:
582     case wasm::WASM_EXTERNAL_TABLE:
583       break;
584     default:
585       return make_error<GenericBinaryError>(
586           "Unexpected export kind", object_error::parse_failed);
587     }
588     if (MakeSymbol) {
589       auto Pair = SymbolMap.try_emplace(Ex.Name, Symbols.size());
590       if (Pair.second) {
591         Symbols.emplace_back(Ex.Name, ExportType,
592                              Sections.size(), i);
593         DEBUG(dbgs() << "Adding export: " << Symbols.back()
594                      << " sym index:" << Symbols.size() << "\n");
595       } else {
596         uint32_t SymIndex = Pair.first->second;
597         Symbols[SymIndex] = WasmSymbol(Ex.Name, ExportType, Sections.size(), i);
598         DEBUG(dbgs() << "Replacing existing symbol:  " << Symbols[SymIndex]
599                      << " sym index:" << SymIndex << "\n");
600       }
601     }
602     Exports.push_back(Ex);
603   }
604   if (Ptr != End)
605     return make_error<GenericBinaryError>("Export section ended prematurely",
606                                           object_error::parse_failed);
607   return Error::success();
608 }
609
610 Error WasmObjectFile::parseStartSection(const uint8_t *Ptr, const uint8_t *End) {
611   StartFunction = readVaruint32(Ptr);
612   if (StartFunction >= FunctionTypes.size())
613     return make_error<GenericBinaryError>("Invalid start function",
614                                           object_error::parse_failed);
615   return Error::success();
616 }
617
618 Error WasmObjectFile::parseCodeSection(const uint8_t *Ptr, const uint8_t *End) {
619   uint32_t FunctionCount = readVaruint32(Ptr);
620   if (FunctionCount != FunctionTypes.size()) {
621     return make_error<GenericBinaryError>("Invalid function count",
622                                           object_error::parse_failed);
623   }
624
625   CodeSection = ArrayRef<uint8_t>(Ptr, End - Ptr);
626
627   while (FunctionCount--) {
628     wasm::WasmFunction Function;
629     uint32_t FunctionSize = readVaruint32(Ptr);
630     const uint8_t *FunctionEnd = Ptr + FunctionSize;
631
632     uint32_t NumLocalDecls = readVaruint32(Ptr);
633     Function.Locals.reserve(NumLocalDecls);
634     while (NumLocalDecls--) {
635       wasm::WasmLocalDecl Decl;
636       Decl.Count = readVaruint32(Ptr);
637       Decl.Type = readVarint7(Ptr);
638       Function.Locals.push_back(Decl);
639     }
640
641     uint32_t BodySize = FunctionEnd - Ptr;
642     Function.Body = ArrayRef<uint8_t>(Ptr, BodySize);
643     Ptr += BodySize;
644     assert(Ptr == FunctionEnd);
645     Functions.push_back(Function);
646   }
647   if (Ptr != End)
648     return make_error<GenericBinaryError>("Code section ended prematurely",
649                                           object_error::parse_failed);
650   return Error::success();
651 }
652
653 Error WasmObjectFile::parseElemSection(const uint8_t *Ptr, const uint8_t *End) {
654   uint32_t Count = readVaruint32(Ptr);
655   ElemSegments.reserve(Count);
656   while (Count--) {
657     wasm::WasmElemSegment Segment;
658     Segment.TableIndex = readVaruint32(Ptr);
659     if (Segment.TableIndex != 0) {
660       return make_error<GenericBinaryError>("Invalid TableIndex",
661                                             object_error::parse_failed);
662     }
663     if (Error Err = readInitExpr(Segment.Offset, Ptr))
664       return Err;
665     uint32_t NumElems = readVaruint32(Ptr);
666     while (NumElems--) {
667       Segment.Functions.push_back(readVaruint32(Ptr));
668     }
669     ElemSegments.push_back(Segment);
670   }
671   if (Ptr != End)
672     return make_error<GenericBinaryError>("Elem section ended prematurely",
673                                           object_error::parse_failed);
674   return Error::success();
675 }
676
677 Error WasmObjectFile::parseDataSection(const uint8_t *Ptr, const uint8_t *End) {
678   const uint8_t *Start = Ptr;
679   uint32_t Count = readVaruint32(Ptr);
680   DataSegments.reserve(Count);
681   while (Count--) {
682     WasmSegment Segment;
683     Segment.Data.MemoryIndex = readVaruint32(Ptr);
684     if (Error Err = readInitExpr(Segment.Data.Offset, Ptr))
685       return Err;
686     uint32_t Size = readVaruint32(Ptr);
687     Segment.Data.Content = ArrayRef<uint8_t>(Ptr, Size);
688     Segment.SectionOffset = Ptr - Start;
689     Ptr += Size;
690     DataSegments.push_back(Segment);
691   }
692   if (Ptr != End)
693     return make_error<GenericBinaryError>("Data section ended prematurely",
694                                           object_error::parse_failed);
695   return Error::success();
696 }
697
698 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
699   return reinterpret_cast<const uint8_t *>(getData().substr(Offset, 1).data());
700 }
701
702 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
703   return Header;
704 }
705
706 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
707
708 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
709   uint32_t Result = SymbolRef::SF_None;
710   const WasmSymbol &Sym = getWasmSymbol(Symb);
711
712   DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
713   if (Sym.Flags & wasm::WASM_SYMBOL_FLAG_WEAK)
714     Result |= SymbolRef::SF_Weak;
715
716   switch (Sym.Type) {
717   case WasmSymbol::SymbolType::FUNCTION_IMPORT:
718     Result |= SymbolRef::SF_Undefined | SymbolRef::SF_Executable;
719     break;
720   case WasmSymbol::SymbolType::FUNCTION_EXPORT:
721     Result |= SymbolRef::SF_Global | SymbolRef::SF_Executable;
722     break;
723   case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
724     Result |= SymbolRef::SF_Executable;
725     Result |= SymbolRef::SF_FormatSpecific;
726     break;
727   case WasmSymbol::SymbolType::GLOBAL_IMPORT:
728     Result |= SymbolRef::SF_Undefined;
729     break;
730   case WasmSymbol::SymbolType::GLOBAL_EXPORT:
731     Result |= SymbolRef::SF_Global;
732     break;
733   }
734
735   return Result;
736 }
737
738 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
739   DataRefImpl Ref;
740   Ref.d.a = 0;
741   return BasicSymbolRef(Ref, this);
742 }
743
744 basic_symbol_iterator WasmObjectFile::symbol_end() const {
745   DataRefImpl Ref;
746   Ref.d.a = Symbols.size();
747   return BasicSymbolRef(Ref, this);
748 }
749
750 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
751   return Symbols[Symb.d.a];
752 }
753
754 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
755   return getWasmSymbol(Symb.getRawDataRefImpl());
756 }
757
758 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
759   return getWasmSymbol(Symb).Name;
760 }
761
762 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
763   return getSymbolValue(Symb);
764 }
765
766 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
767   const WasmSymbol& Sym = getWasmSymbol(Symb);
768   switch (Sym.Type) {
769   case WasmSymbol::SymbolType::FUNCTION_IMPORT:
770   case WasmSymbol::SymbolType::GLOBAL_IMPORT:
771     return 0;
772   case WasmSymbol::SymbolType::FUNCTION_EXPORT:
773   case WasmSymbol::SymbolType::GLOBAL_EXPORT:
774     return Exports[Sym.ElementIndex].Index;
775   case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
776     return Sym.ElementIndex;
777   }
778   llvm_unreachable("invalid symbol type");
779 }
780
781 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
782   llvm_unreachable("not yet implemented");
783   return 0;
784 }
785
786 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
787   llvm_unreachable("not yet implemented");
788   return 0;
789 }
790
791 Expected<SymbolRef::Type>
792 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
793   const WasmSymbol &Sym = getWasmSymbol(Symb);
794
795   switch (Sym.Type) {
796   case WasmSymbol::SymbolType::FUNCTION_IMPORT:
797   case WasmSymbol::SymbolType::FUNCTION_EXPORT:
798   case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
799     return SymbolRef::ST_Function;
800   case WasmSymbol::SymbolType::GLOBAL_IMPORT:
801   case WasmSymbol::SymbolType::GLOBAL_EXPORT:
802     return SymbolRef::ST_Data;
803   }
804
805   llvm_unreachable("Unknown WasmSymbol::SymbolType");
806   return SymbolRef::ST_Other;
807 }
808
809 Expected<section_iterator>
810 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
811   DataRefImpl Ref;
812   Ref.d.a = getWasmSymbol(Symb).Section;
813   return section_iterator(SectionRef(Ref, this));
814 }
815
816 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
817
818 std::error_code WasmObjectFile::getSectionName(DataRefImpl Sec,
819                                                StringRef &Res) const {
820   const WasmSection &S = Sections[Sec.d.a];
821 #define ECase(X)                                                               \
822   case wasm::WASM_SEC_##X:                                                     \
823     Res = #X;                                                                  \
824     break
825   switch (S.Type) {
826     ECase(TYPE);
827     ECase(IMPORT);
828     ECase(FUNCTION);
829     ECase(TABLE);
830     ECase(MEMORY);
831     ECase(GLOBAL);
832     ECase(EXPORT);
833     ECase(START);
834     ECase(ELEM);
835     ECase(CODE);
836     ECase(DATA);
837   case wasm::WASM_SEC_CUSTOM:
838     Res = S.Name;
839     break;
840   default:
841     return object_error::invalid_section_index;
842   }
843 #undef ECase
844   return std::error_code();
845 }
846
847 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
848
849 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
850   return Sec.d.a;
851 }
852
853 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
854   const WasmSection &S = Sections[Sec.d.a];
855   return S.Content.size();
856 }
857
858 std::error_code WasmObjectFile::getSectionContents(DataRefImpl Sec,
859                                                    StringRef &Res) const {
860   const WasmSection &S = Sections[Sec.d.a];
861   // This will never fail since wasm sections can never be empty (user-sections
862   // must have a name and non-user sections each have a defined structure).
863   Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
864                   S.Content.size());
865   return std::error_code();
866 }
867
868 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
869   return 1;
870 }
871
872 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
873   return false;
874 }
875
876 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
877   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
878 }
879
880 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
881   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
882 }
883
884 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
885
886 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
887
888 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
889
890 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
891   DataRefImpl RelocRef;
892   RelocRef.d.a = Ref.d.a;
893   RelocRef.d.b = 0;
894   return relocation_iterator(RelocationRef(RelocRef, this));
895 }
896
897 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
898   const WasmSection &Sec = getWasmSection(Ref);
899   DataRefImpl RelocRef;
900   RelocRef.d.a = Ref.d.a;
901   RelocRef.d.b = Sec.Relocations.size();
902   return relocation_iterator(RelocationRef(RelocRef, this));
903 }
904
905 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
906   Rel.d.b++;
907 }
908
909 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
910   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
911   return Rel.Offset;
912 }
913
914 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
915   llvm_unreachable("not yet implemented");
916   SymbolRef Ref;
917   return symbol_iterator(Ref);
918 }
919
920 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
921   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
922   return Rel.Type;
923 }
924
925 void WasmObjectFile::getRelocationTypeName(
926     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
927   const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
928   StringRef Res = "Unknown";
929
930 #define WASM_RELOC(name, value)  \
931   case wasm::name:              \
932     Res = #name;               \
933     break;
934
935   switch (Rel.Type) {
936 #include "llvm/BinaryFormat/WasmRelocs/WebAssembly.def"
937   }
938
939 #undef WASM_RELOC
940
941   Result.append(Res.begin(), Res.end());
942 }
943
944 section_iterator WasmObjectFile::section_begin() const {
945   DataRefImpl Ref;
946   Ref.d.a = 0;
947   return section_iterator(SectionRef(Ref, this));
948 }
949
950 section_iterator WasmObjectFile::section_end() const {
951   DataRefImpl Ref;
952   Ref.d.a = Sections.size();
953   return section_iterator(SectionRef(Ref, this));
954 }
955
956 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
957
958 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
959
960 unsigned WasmObjectFile::getArch() const { return Triple::wasm32; }
961
962 SubtargetFeatures WasmObjectFile::getFeatures() const {
963   return SubtargetFeatures();
964 }
965
966 bool WasmObjectFile::isRelocatableObject() const {
967   return HasLinkingSection;
968 }
969
970 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
971   assert(Ref.d.a < Sections.size());
972   return Sections[Ref.d.a];
973 }
974
975 const WasmSection &
976 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
977   return getWasmSection(Section.getRawDataRefImpl());
978 }
979
980 const wasm::WasmRelocation &
981 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
982   return getWasmRelocation(Ref.getRawDataRefImpl());
983 }
984
985 const wasm::WasmRelocation &
986 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
987   assert(Ref.d.a < Sections.size());
988   const WasmSection& Sec = Sections[Ref.d.a];
989   assert(Ref.d.b < Sec.Relocations.size());
990   return Sec.Relocations[Ref.d.b];
991 }