OSDN Git Service

[WebAssembly] Model weakly defined symbols as wasm exports
[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
207   const uint8_t *Eof = getPtr(getData().size());
208   const uint8_t *Ptr = getPtr(4);
209
210   if (Ptr + 4 > Eof) {
211     Err = make_error<StringError>("Missing version number",
212                                   object_error::parse_failed);
213     return;
214   }
215
216   Header.Version = readUint32(Ptr);
217   if (Header.Version != wasm::WasmVersion) {
218     Err = make_error<StringError>("Bad version number",
219                                   object_error::parse_failed);
220     return;
221   }
222
223   WasmSection Sec;
224   while (Ptr < Eof) {
225     if ((Err = readSection(Sec, Ptr, getPtr(0))))
226       return;
227     if ((Err = parseSection(Sec)))
228       return;
229
230     Sections.push_back(Sec);
231   }
232 }
233
234 Error WasmObjectFile::parseSection(WasmSection &Sec) {
235   const uint8_t* Start = Sec.Content.data();
236   const uint8_t* End = Start + Sec.Content.size();
237   switch (Sec.Type) {
238   case wasm::WASM_SEC_CUSTOM:
239     return parseCustomSection(Sec, Start, End);
240   case wasm::WASM_SEC_TYPE:
241     return parseTypeSection(Start, End);
242   case wasm::WASM_SEC_IMPORT:
243     return parseImportSection(Start, End);
244   case wasm::WASM_SEC_FUNCTION:
245     return parseFunctionSection(Start, End);
246   case wasm::WASM_SEC_TABLE:
247     return parseTableSection(Start, End);
248   case wasm::WASM_SEC_MEMORY:
249     return parseMemorySection(Start, End);
250   case wasm::WASM_SEC_GLOBAL:
251     return parseGlobalSection(Start, End);
252   case wasm::WASM_SEC_EXPORT:
253     return parseExportSection(Start, End);
254   case wasm::WASM_SEC_START:
255     return parseStartSection(Start, End);
256   case wasm::WASM_SEC_ELEM:
257     return parseElemSection(Start, End);
258   case wasm::WASM_SEC_CODE:
259     return parseCodeSection(Start, End);
260   case wasm::WASM_SEC_DATA:
261     return parseDataSection(Start, End);
262   default:
263     return make_error<GenericBinaryError>("Bad section type",
264                                           object_error::parse_failed);
265   }
266 }
267
268 Error WasmObjectFile::parseNameSection(const uint8_t *Ptr, const uint8_t *End) {
269   while (Ptr < End) {
270     uint8_t Type = readVarint7(Ptr);
271     uint32_t Size = readVaruint32(Ptr);
272     const uint8_t *SubSectionEnd = Ptr + Size;
273     switch (Type) {
274     case wasm::WASM_NAMES_FUNCTION: {
275       uint32_t Count = readVaruint32(Ptr);
276       while (Count--) {
277         uint32_t Index = readVaruint32(Ptr);
278         StringRef Name = readString(Ptr);
279         if (!Name.empty())
280           Symbols.emplace_back(Name,
281                                WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME,
282                                Sections.size(), Index);
283       }
284       break;
285     }
286     // Ignore local names for now
287     case wasm::WASM_NAMES_LOCAL:
288     default:
289       Ptr += Size;
290       break;
291     }
292     if (Ptr != SubSectionEnd)
293       return make_error<GenericBinaryError>("Name sub-section ended prematurely",
294                                             object_error::parse_failed);
295   }
296
297   if (Ptr != End)
298     return make_error<GenericBinaryError>("Name section ended prematurely",
299                                           object_error::parse_failed);
300   return Error::success();
301 }
302
303 void WasmObjectFile::populateSymbolTable() {
304   // Add imports to symbol table
305   size_t ImportIndex = 0;
306   size_t GlobalIndex = 0;
307   size_t FunctionIndex = 0;
308   for (const wasm::WasmImport& Import : Imports) {
309     switch (Import.Kind) {
310     case wasm::WASM_EXTERNAL_GLOBAL:
311       assert(Import.Global.Type == wasm::WASM_TYPE_I32);
312       SymbolMap.try_emplace(Import.Field, Symbols.size());
313       Symbols.emplace_back(Import.Field, WasmSymbol::SymbolType::GLOBAL_IMPORT,
314                            ImportSection, GlobalIndex++, ImportIndex);
315       DEBUG(dbgs() << "Adding import: " << Symbols.back()
316                    << " sym index:" << Symbols.size() << "\n");
317       break;
318     case wasm::WASM_EXTERNAL_FUNCTION:
319       SymbolMap.try_emplace(Import.Field, Symbols.size());
320       Symbols.emplace_back(Import.Field,
321                            WasmSymbol::SymbolType::FUNCTION_IMPORT,
322                            ImportSection, FunctionIndex++, ImportIndex);
323       DEBUG(dbgs() << "Adding import: " << Symbols.back()
324                    << " sym index:" << Symbols.size() << "\n");
325       break;
326     default:
327       break;
328     }
329     ImportIndex++;
330   }
331
332   // Add exports to symbol table
333   for (const wasm::WasmExport& Export : Exports) {
334     if (Export.Kind == wasm::WASM_EXTERNAL_FUNCTION ||
335         Export.Kind == wasm::WASM_EXTERNAL_GLOBAL) {
336       WasmSymbol::SymbolType ExportType =
337           Export.Kind == wasm::WASM_EXTERNAL_FUNCTION
338               ? WasmSymbol::SymbolType::FUNCTION_EXPORT
339               : WasmSymbol::SymbolType::GLOBAL_EXPORT;
340       SymbolMap.try_emplace(Export.Name, Symbols.size());
341       Symbols.emplace_back(Export.Name, ExportType,
342                            ExportSection, Export.Index);
343       DEBUG(dbgs() << "Adding export: " << Symbols.back()
344                    << " sym index:" << Symbols.size() << "\n");
345     }
346   }
347 }
348
349 Error WasmObjectFile::parseLinkingSection(const uint8_t *Ptr,
350                                           const uint8_t *End) {
351   HasLinkingSection = true;
352
353   // Only populate the symbol table with imports and exports if the object
354   // has a linking section (i.e. its a relocatable object file). Otherwise
355   // the global might not represent symbols at all.
356   populateSymbolTable();
357
358   while (Ptr < End) {
359     uint8_t Type = readVarint7(Ptr);
360     uint32_t Size = readVaruint32(Ptr);
361     const uint8_t *SubSectionEnd = Ptr + Size;
362     switch (Type) {
363     case wasm::WASM_SYMBOL_INFO: {
364       uint32_t Count = readVaruint32(Ptr);
365       while (Count--) {
366         StringRef Symbol = readString(Ptr);
367         DEBUG(dbgs() << "reading syminfo: " << Symbol << "\n");
368         uint32_t Flags = readVaruint32(Ptr);
369         auto iter = SymbolMap.find(Symbol);
370         if (iter == SymbolMap.end()) {
371           return make_error<GenericBinaryError>(
372               "Invalid symbol name in linking section: " + Symbol,
373               object_error::parse_failed);
374         }
375         uint32_t SymIndex = iter->second;
376         assert(SymIndex < Symbols.size());
377         Symbols[SymIndex].Flags = Flags;
378         DEBUG(dbgs() << "Set symbol flags index:"
379                      << SymIndex << " name:"
380                      << Symbols[SymIndex].Name << " exptected:"
381                      << Symbol << " flags: " << Flags << "\n");
382       }
383       break;
384     }
385     case wasm::WASM_DATA_SIZE:
386       LinkingData.DataSize = readVaruint32(Ptr);
387       break;
388     case wasm::WASM_DATA_ALIGNMENT:
389       LinkingData.DataAlignment = readVaruint32(Ptr);
390       break;
391     case wasm::WASM_SEGMENT_NAMES: {
392       uint32_t Count = readVaruint32(Ptr);
393       if (Count > DataSegments.size())
394         return make_error<GenericBinaryError>("Too many segment names",
395                                               object_error::parse_failed);
396       for (uint32_t i = 0; i < Count; i++)
397         DataSegments[i].Data.Name = readString(Ptr);
398       break;
399     }
400     case wasm::WASM_STACK_POINTER:
401     default:
402       Ptr += Size;
403       break;
404     }
405     if (Ptr != SubSectionEnd)
406       return make_error<GenericBinaryError>(
407           "Linking sub-section ended prematurely", object_error::parse_failed);
408   }
409   if (Ptr != End)
410     return make_error<GenericBinaryError>("Linking section ended prematurely",
411                                           object_error::parse_failed);
412   return Error::success();
413 }
414
415 WasmSection* WasmObjectFile::findCustomSectionByName(StringRef Name) {
416   for (WasmSection& Section : Sections) {
417     if (Section.Type == wasm::WASM_SEC_CUSTOM && Section.Name == Name)
418       return &Section;
419   }
420   return nullptr;
421 }
422
423 WasmSection* WasmObjectFile::findSectionByType(uint32_t Type) {
424   assert(Type != wasm::WASM_SEC_CUSTOM);
425   for (WasmSection& Section : Sections) {
426     if (Section.Type == Type)
427       return &Section;
428   }
429   return nullptr;
430 }
431
432 Error WasmObjectFile::parseRelocSection(StringRef Name, const uint8_t *Ptr,
433                                         const uint8_t *End) {
434   uint8_t SectionCode = readVarint7(Ptr);
435   WasmSection* Section = nullptr;
436   if (SectionCode == wasm::WASM_SEC_CUSTOM) {
437     StringRef Name = readString(Ptr);
438     Section = findCustomSectionByName(Name);
439   } else {
440     Section = findSectionByType(SectionCode);
441   }
442   if (!Section)
443     return make_error<GenericBinaryError>("Invalid section code",
444                                           object_error::parse_failed);
445   uint32_t RelocCount = readVaruint32(Ptr);
446   while (RelocCount--) {
447     wasm::WasmRelocation Reloc;
448     memset(&Reloc, 0, sizeof(Reloc));
449     Reloc.Type = readVaruint32(Ptr);
450     Reloc.Offset = readVaruint32(Ptr);
451     Reloc.Index = readVaruint32(Ptr);
452     switch (Reloc.Type) {
453     case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
454     case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
455     case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
456     case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
457     case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
458       break;
459     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
460     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
461     case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
462       Reloc.Addend = readVarint32(Ptr);
463       break;
464     default:
465       return make_error<GenericBinaryError>("Bad relocation type: " +
466                                                 Twine(Reloc.Type),
467                                             object_error::parse_failed);
468     }
469     Section->Relocations.push_back(Reloc);
470   }
471   if (Ptr != End)
472     return make_error<GenericBinaryError>("Reloc section ended prematurely",
473                                           object_error::parse_failed);
474   return Error::success();
475 }
476
477 Error WasmObjectFile::parseCustomSection(WasmSection &Sec,
478                                          const uint8_t *Ptr, const uint8_t *End) {
479   Sec.Name = readString(Ptr);
480   if (Sec.Name == "name") {
481     if (Error Err = parseNameSection(Ptr, End))
482       return Err;
483   } else if (Sec.Name == "linking") {
484     if (Error Err = parseLinkingSection(Ptr, End))
485       return Err;
486   } else if (Sec.Name.startswith("reloc.")) {
487     if (Error Err = parseRelocSection(Sec.Name, Ptr, End))
488       return Err;
489   }
490   return Error::success();
491 }
492
493 Error WasmObjectFile::parseTypeSection(const uint8_t *Ptr, const uint8_t *End) {
494   uint32_t Count = readVaruint32(Ptr);
495   Signatures.reserve(Count);
496   while (Count--) {
497     wasm::WasmSignature Sig;
498     Sig.ReturnType = wasm::WASM_TYPE_NORESULT;
499     int8_t Form = readVarint7(Ptr);
500     if (Form != wasm::WASM_TYPE_FUNC) {
501       return make_error<GenericBinaryError>("Invalid signature type",
502                                             object_error::parse_failed);
503     }
504     uint32_t ParamCount = readVaruint32(Ptr);
505     Sig.ParamTypes.reserve(ParamCount);
506     while (ParamCount--) {
507       uint32_t ParamType = readVarint7(Ptr);
508       Sig.ParamTypes.push_back(ParamType);
509     }
510     uint32_t ReturnCount = readVaruint32(Ptr);
511     if (ReturnCount) {
512       if (ReturnCount != 1) {
513         return make_error<GenericBinaryError>(
514             "Multiple return types not supported", object_error::parse_failed);
515       }
516       Sig.ReturnType = readVarint7(Ptr);
517     }
518     Signatures.push_back(Sig);
519   }
520   if (Ptr != End)
521     return make_error<GenericBinaryError>("Type section ended prematurely",
522                                           object_error::parse_failed);
523   return Error::success();
524 }
525
526 Error WasmObjectFile::parseImportSection(const uint8_t *Ptr, const uint8_t *End) {
527   ImportSection = Sections.size();
528   uint32_t Count = readVaruint32(Ptr);
529   Imports.reserve(Count);
530   for (uint32_t i = 0; i < Count; i++) {
531     wasm::WasmImport Im;
532     Im.Module = readString(Ptr);
533     Im.Field = readString(Ptr);
534     Im.Kind = readUint8(Ptr);
535     switch (Im.Kind) {
536     case wasm::WASM_EXTERNAL_FUNCTION:
537       NumImportedFunctions++;
538       Im.SigIndex = readVaruint32(Ptr);
539       break;
540     case wasm::WASM_EXTERNAL_GLOBAL:
541       NumImportedGlobals++;
542       Im.Global.Type = readVarint7(Ptr);
543       Im.Global.Mutable = readVaruint1(Ptr);
544       break;
545     case wasm::WASM_EXTERNAL_MEMORY:
546       Im.Memory = readLimits(Ptr);
547       break;
548     case wasm::WASM_EXTERNAL_TABLE:
549       Im.Table = readTable(Ptr);
550       if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC)
551         return make_error<GenericBinaryError>("Invalid table element type",
552                                               object_error::parse_failed);
553       break;
554     default:
555       return make_error<GenericBinaryError>(
556           "Unexpected import kind", object_error::parse_failed);
557     }
558     Imports.push_back(Im);
559   }
560   if (Ptr != End)
561     return make_error<GenericBinaryError>("Import section ended prematurely",
562                                           object_error::parse_failed);
563   return Error::success();
564 }
565
566 Error WasmObjectFile::parseFunctionSection(const uint8_t *Ptr, const uint8_t *End) {
567   uint32_t Count = readVaruint32(Ptr);
568   FunctionTypes.reserve(Count);
569   while (Count--) {
570     FunctionTypes.push_back(readVaruint32(Ptr));
571   }
572   if (Ptr != End)
573     return make_error<GenericBinaryError>("Function section ended prematurely",
574                                           object_error::parse_failed);
575   return Error::success();
576 }
577
578 Error WasmObjectFile::parseTableSection(const uint8_t *Ptr, const uint8_t *End) {
579   uint32_t Count = readVaruint32(Ptr);
580   Tables.reserve(Count);
581   while (Count--) {
582     Tables.push_back(readTable(Ptr));
583     if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
584       return make_error<GenericBinaryError>("Invalid table element type",
585                                             object_error::parse_failed);
586     }
587   }
588   if (Ptr != End)
589     return make_error<GenericBinaryError>("Table section ended prematurely",
590                                           object_error::parse_failed);
591   return Error::success();
592 }
593
594 Error WasmObjectFile::parseMemorySection(const uint8_t *Ptr, const uint8_t *End) {
595   uint32_t Count = readVaruint32(Ptr);
596   Memories.reserve(Count);
597   while (Count--) {
598     Memories.push_back(readLimits(Ptr));
599   }
600   if (Ptr != End)
601     return make_error<GenericBinaryError>("Memory section ended prematurely",
602                                           object_error::parse_failed);
603   return Error::success();
604 }
605
606 Error WasmObjectFile::parseGlobalSection(const uint8_t *Ptr, const uint8_t *End) {
607   uint32_t Count = readVaruint32(Ptr);
608   Globals.reserve(Count);
609   while (Count--) {
610     wasm::WasmGlobal Global;
611     Global.Type = readVarint7(Ptr);
612     Global.Mutable = readVaruint1(Ptr);
613     if (Error Err = readInitExpr(Global.InitExpr, Ptr))
614       return Err;
615     Globals.push_back(Global);
616   }
617   if (Ptr != End)
618     return make_error<GenericBinaryError>("Global section ended prematurely",
619                                           object_error::parse_failed);
620   return Error::success();
621 }
622
623 Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) {
624   ExportSection = Sections.size();
625   uint32_t Count = readVaruint32(Ptr);
626   Exports.reserve(Count);
627   for (uint32_t i = 0; i < Count; i++) {
628     wasm::WasmExport Ex;
629     Ex.Name = readString(Ptr);
630     Ex.Kind = readUint8(Ptr);
631     Ex.Index = readVaruint32(Ptr);
632     switch (Ex.Kind) {
633     case wasm::WASM_EXTERNAL_FUNCTION:
634       if (Ex.Index >= FunctionTypes.size() + NumImportedFunctions)
635         return make_error<GenericBinaryError>("Invalid function export",
636                                               object_error::parse_failed);
637       break;
638     case wasm::WASM_EXTERNAL_GLOBAL: {
639       if (Ex.Index >= Globals.size() + NumImportedGlobals)
640         return make_error<GenericBinaryError>("Invalid global export",
641                                               object_error::parse_failed);
642       break;
643     }
644     case wasm::WASM_EXTERNAL_MEMORY:
645     case wasm::WASM_EXTERNAL_TABLE:
646       break;
647     default:
648       return make_error<GenericBinaryError>(
649           "Unexpected export kind", object_error::parse_failed);
650     }
651     Exports.push_back(Ex);
652   }
653   if (Ptr != End)
654     return make_error<GenericBinaryError>("Export section ended prematurely",
655                                           object_error::parse_failed);
656   return Error::success();
657 }
658
659 Error WasmObjectFile::parseStartSection(const uint8_t *Ptr, const uint8_t *End) {
660   StartFunction = readVaruint32(Ptr);
661   if (StartFunction >= FunctionTypes.size())
662     return make_error<GenericBinaryError>("Invalid start function",
663                                           object_error::parse_failed);
664   return Error::success();
665 }
666
667 Error WasmObjectFile::parseCodeSection(const uint8_t *Ptr, const uint8_t *End) {
668   uint32_t FunctionCount = readVaruint32(Ptr);
669   if (FunctionCount != FunctionTypes.size()) {
670     return make_error<GenericBinaryError>("Invalid function count",
671                                           object_error::parse_failed);
672   }
673
674   CodeSection = ArrayRef<uint8_t>(Ptr, End - Ptr);
675
676   while (FunctionCount--) {
677     wasm::WasmFunction Function;
678     uint32_t FunctionSize = readVaruint32(Ptr);
679     const uint8_t *FunctionEnd = Ptr + FunctionSize;
680
681     uint32_t NumLocalDecls = readVaruint32(Ptr);
682     Function.Locals.reserve(NumLocalDecls);
683     while (NumLocalDecls--) {
684       wasm::WasmLocalDecl Decl;
685       Decl.Count = readVaruint32(Ptr);
686       Decl.Type = readVarint7(Ptr);
687       Function.Locals.push_back(Decl);
688     }
689
690     uint32_t BodySize = FunctionEnd - Ptr;
691     Function.Body = ArrayRef<uint8_t>(Ptr, BodySize);
692     Ptr += BodySize;
693     assert(Ptr == FunctionEnd);
694     Functions.push_back(Function);
695   }
696   if (Ptr != End)
697     return make_error<GenericBinaryError>("Code section ended prematurely",
698                                           object_error::parse_failed);
699   return Error::success();
700 }
701
702 Error WasmObjectFile::parseElemSection(const uint8_t *Ptr, const uint8_t *End) {
703   uint32_t Count = readVaruint32(Ptr);
704   ElemSegments.reserve(Count);
705   while (Count--) {
706     wasm::WasmElemSegment Segment;
707     Segment.TableIndex = readVaruint32(Ptr);
708     if (Segment.TableIndex != 0) {
709       return make_error<GenericBinaryError>("Invalid TableIndex",
710                                             object_error::parse_failed);
711     }
712     if (Error Err = readInitExpr(Segment.Offset, Ptr))
713       return Err;
714     uint32_t NumElems = readVaruint32(Ptr);
715     while (NumElems--) {
716       Segment.Functions.push_back(readVaruint32(Ptr));
717     }
718     ElemSegments.push_back(Segment);
719   }
720   if (Ptr != End)
721     return make_error<GenericBinaryError>("Elem section ended prematurely",
722                                           object_error::parse_failed);
723   return Error::success();
724 }
725
726 Error WasmObjectFile::parseDataSection(const uint8_t *Ptr, const uint8_t *End) {
727   const uint8_t *Start = Ptr;
728   uint32_t Count = readVaruint32(Ptr);
729   DataSegments.reserve(Count);
730   while (Count--) {
731     WasmSegment Segment;
732     Segment.Data.MemoryIndex = readVaruint32(Ptr);
733     if (Error Err = readInitExpr(Segment.Data.Offset, Ptr))
734       return Err;
735     uint32_t Size = readVaruint32(Ptr);
736     Segment.Data.Content = ArrayRef<uint8_t>(Ptr, Size);
737     Segment.SectionOffset = Ptr - Start;
738     Ptr += Size;
739     DataSegments.push_back(Segment);
740   }
741   if (Ptr != End)
742     return make_error<GenericBinaryError>("Data section ended prematurely",
743                                           object_error::parse_failed);
744   return Error::success();
745 }
746
747 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
748   return reinterpret_cast<const uint8_t *>(getData().substr(Offset, 1).data());
749 }
750
751 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
752   return Header;
753 }
754
755 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
756
757 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
758   uint32_t Result = SymbolRef::SF_None;
759   const WasmSymbol &Sym = getWasmSymbol(Symb);
760
761   DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
762   if (Sym.isWeak())
763     Result |= SymbolRef::SF_Weak;
764   if (!Sym.isLocal())
765     Result |= SymbolRef::SF_Global;
766
767   switch (Sym.Type) {
768   case WasmSymbol::SymbolType::FUNCTION_IMPORT:
769     Result |= SymbolRef::SF_Undefined | SymbolRef::SF_Executable;
770     break;
771   case WasmSymbol::SymbolType::FUNCTION_EXPORT:
772     Result |= SymbolRef::SF_Executable;
773     break;
774   case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
775     Result |= SymbolRef::SF_Executable;
776     Result |= SymbolRef::SF_FormatSpecific;
777     break;
778   case WasmSymbol::SymbolType::GLOBAL_IMPORT:
779     Result |= SymbolRef::SF_Undefined;
780     break;
781   case WasmSymbol::SymbolType::GLOBAL_EXPORT:
782     break;
783   }
784
785   return Result;
786 }
787
788 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
789   DataRefImpl Ref;
790   Ref.d.a = 0;
791   return BasicSymbolRef(Ref, this);
792 }
793
794 basic_symbol_iterator WasmObjectFile::symbol_end() const {
795   DataRefImpl Ref;
796   Ref.d.a = Symbols.size();
797   return BasicSymbolRef(Ref, this);
798 }
799
800 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
801   return Symbols[Symb.d.a];
802 }
803
804 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
805   return getWasmSymbol(Symb.getRawDataRefImpl());
806 }
807
808 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
809   return getWasmSymbol(Symb).Name;
810 }
811
812 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
813   return getSymbolValue(Symb);
814 }
815
816 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol& Sym) const {
817   switch (Sym.Type) {
818   case WasmSymbol::SymbolType::FUNCTION_IMPORT:
819   case WasmSymbol::SymbolType::GLOBAL_IMPORT:
820   case WasmSymbol::SymbolType::FUNCTION_EXPORT:
821   case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
822     return Sym.ElementIndex;
823   case WasmSymbol::SymbolType::GLOBAL_EXPORT: {
824     uint32_t GlobalIndex = Sym.ElementIndex - NumImportedGlobals;
825     assert(GlobalIndex < Globals.size());
826     const wasm::WasmGlobal& Global = Globals[GlobalIndex];
827     // WasmSymbols correspond only to I32_CONST globals
828     assert(Global.InitExpr.Opcode == wasm::WASM_OPCODE_I32_CONST);
829     return Global.InitExpr.Value.Int32;
830   }
831   }
832   llvm_unreachable("invalid symbol type");
833 }
834
835 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
836   return getWasmSymbolValue(getWasmSymbol(Symb));
837 }
838
839 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
840   llvm_unreachable("not yet implemented");
841   return 0;
842 }
843
844 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
845   llvm_unreachable("not yet implemented");
846   return 0;
847 }
848
849 Expected<SymbolRef::Type>
850 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
851   const WasmSymbol &Sym = getWasmSymbol(Symb);
852
853   switch (Sym.Type) {
854   case WasmSymbol::SymbolType::FUNCTION_IMPORT:
855   case WasmSymbol::SymbolType::FUNCTION_EXPORT:
856   case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
857     return SymbolRef::ST_Function;
858   case WasmSymbol::SymbolType::GLOBAL_IMPORT:
859   case WasmSymbol::SymbolType::GLOBAL_EXPORT:
860     return SymbolRef::ST_Data;
861   }
862
863   llvm_unreachable("Unknown WasmSymbol::SymbolType");
864   return SymbolRef::ST_Other;
865 }
866
867 Expected<section_iterator>
868 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
869   DataRefImpl Ref;
870   Ref.d.a = getWasmSymbol(Symb).Section;
871   return section_iterator(SectionRef(Ref, this));
872 }
873
874 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
875
876 std::error_code WasmObjectFile::getSectionName(DataRefImpl Sec,
877                                                StringRef &Res) const {
878   const WasmSection &S = Sections[Sec.d.a];
879 #define ECase(X)                                                               \
880   case wasm::WASM_SEC_##X:                                                     \
881     Res = #X;                                                                  \
882     break
883   switch (S.Type) {
884     ECase(TYPE);
885     ECase(IMPORT);
886     ECase(FUNCTION);
887     ECase(TABLE);
888     ECase(MEMORY);
889     ECase(GLOBAL);
890     ECase(EXPORT);
891     ECase(START);
892     ECase(ELEM);
893     ECase(CODE);
894     ECase(DATA);
895   case wasm::WASM_SEC_CUSTOM:
896     Res = S.Name;
897     break;
898   default:
899     return object_error::invalid_section_index;
900   }
901 #undef ECase
902   return std::error_code();
903 }
904
905 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
906
907 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
908   return Sec.d.a;
909 }
910
911 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
912   const WasmSection &S = Sections[Sec.d.a];
913   return S.Content.size();
914 }
915
916 std::error_code WasmObjectFile::getSectionContents(DataRefImpl Sec,
917                                                    StringRef &Res) const {
918   const WasmSection &S = Sections[Sec.d.a];
919   // This will never fail since wasm sections can never be empty (user-sections
920   // must have a name and non-user sections each have a defined structure).
921   Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
922                   S.Content.size());
923   return std::error_code();
924 }
925
926 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
927   return 1;
928 }
929
930 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
931   return false;
932 }
933
934 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
935   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
936 }
937
938 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
939   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
940 }
941
942 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
943
944 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
945
946 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
947
948 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
949   DataRefImpl RelocRef;
950   RelocRef.d.a = Ref.d.a;
951   RelocRef.d.b = 0;
952   return relocation_iterator(RelocationRef(RelocRef, this));
953 }
954
955 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
956   const WasmSection &Sec = getWasmSection(Ref);
957   DataRefImpl RelocRef;
958   RelocRef.d.a = Ref.d.a;
959   RelocRef.d.b = Sec.Relocations.size();
960   return relocation_iterator(RelocationRef(RelocRef, this));
961 }
962
963 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
964   Rel.d.b++;
965 }
966
967 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
968   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
969   return Rel.Offset;
970 }
971
972 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
973   llvm_unreachable("not yet implemented");
974   SymbolRef Ref;
975   return symbol_iterator(Ref);
976 }
977
978 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
979   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
980   return Rel.Type;
981 }
982
983 void WasmObjectFile::getRelocationTypeName(
984     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
985   const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
986   StringRef Res = "Unknown";
987
988 #define WASM_RELOC(name, value)  \
989   case wasm::name:              \
990     Res = #name;               \
991     break;
992
993   switch (Rel.Type) {
994 #include "llvm/BinaryFormat/WasmRelocs/WebAssembly.def"
995   }
996
997 #undef WASM_RELOC
998
999   Result.append(Res.begin(), Res.end());
1000 }
1001
1002 section_iterator WasmObjectFile::section_begin() const {
1003   DataRefImpl Ref;
1004   Ref.d.a = 0;
1005   return section_iterator(SectionRef(Ref, this));
1006 }
1007
1008 section_iterator WasmObjectFile::section_end() const {
1009   DataRefImpl Ref;
1010   Ref.d.a = Sections.size();
1011   return section_iterator(SectionRef(Ref, this));
1012 }
1013
1014 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1015
1016 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1017
1018 unsigned WasmObjectFile::getArch() const { return Triple::wasm32; }
1019
1020 SubtargetFeatures WasmObjectFile::getFeatures() const {
1021   return SubtargetFeatures();
1022 }
1023
1024 bool WasmObjectFile::isRelocatableObject() const {
1025   return HasLinkingSection;
1026 }
1027
1028 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1029   assert(Ref.d.a < Sections.size());
1030   return Sections[Ref.d.a];
1031 }
1032
1033 const WasmSection &
1034 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1035   return getWasmSection(Section.getRawDataRefImpl());
1036 }
1037
1038 const wasm::WasmRelocation &
1039 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1040   return getWasmRelocation(Ref.getRawDataRefImpl());
1041 }
1042
1043 const wasm::WasmRelocation &
1044 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1045   assert(Ref.d.a < Sections.size());
1046   const WasmSection& Sec = Sections[Ref.d.a];
1047   assert(Ref.d.b < Sec.Relocations.size());
1048   return Sec.Relocations[Ref.d.b];
1049 }