OSDN Git Service

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