LLVM  6.0.0svn
WasmObjectFile.cpp
Go to the documentation of this file.
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"
16 #include "llvm/Object/Binary.h"
17 #include "llvm/Object/Error.h"
18 #include "llvm/Object/ObjectFile.h"
20 #include "llvm/Object/Wasm.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/Error.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 
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) {
137  Expr.Value.Int32 = readVarint32(Ptr);
138  break;
140  Expr.Value.Int64 = readVarint64(Ptr);
141  break;
143  Expr.Value.Float32 = readFloat32(Ptr);
144  break;
146  Expr.Value.Float64 = readFloat64(Ptr);
147  break;
149  Expr.Value.Global = readULEB128(Ptr);
150  break;
151  default:
152  return make_error<GenericBinaryError>("Invalid opcode in init_expr",
154  }
155 
156  uint8_t EndOpcode = readOpcode(Ptr);
157  if (EndOpcode != wasm::WASM_OPCODE_END) {
158  return make_error<GenericBinaryError>("Invalid init_expr",
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);
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",
188  if (Ptr + Size > Eof)
189  return make_error<StringError>("Section too large",
191  Section.Content = ArrayRef<uint8_t>(Ptr, Size);
192  Ptr += Size;
193  return Error::success();
194 }
195 
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",
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",
214  return;
215  }
216 
217  Header.Version = readUint32(Ptr);
218  if (Header.Version != wasm::WasmVersion) {
219  Err = make_error<StringError>("Bad version number",
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) {
240  return parseCustomSection(Sec, Start, End);
241  case wasm::WASM_SEC_TYPE:
242  return parseTypeSection(Start, End);
244  return parseImportSection(Start, End);
246  return parseFunctionSection(Start, End);
248  return parseTableSection(Start, End);
250  return parseMemorySection(Start, End);
252  return parseGlobalSection(Start, End);
254  return parseExportSection(Start, End);
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",
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) {
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,
283  Sections.size(), Index);
284  }
285  break;
286  }
287  // Ignore local names for now
289  default:
290  Ptr += Size;
291  break;
292  }
293  if (Ptr != SubSectionEnd)
294  return make_error<GenericBinaryError>("Name sub-section ended prematurely",
296  }
297 
298  if (Ptr != End)
299  return make_error<GenericBinaryError>("Name section ended prematurely",
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) {
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;
320  SymbolMap.try_emplace(Import.Field, Symbols.size());
321  Symbols.emplace_back(Import.Field,
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 ||
337  WasmSymbol::SymbolType ExportType =
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,
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 << " exptected:"
382  << Symbol << " flags: " << Flags << "\n");
383  }
384  break;
385  }
387  LinkingData.DataSize = readVaruint32(Ptr);
388  break;
390  uint32_t Count = readVaruint32(Ptr);
391  if (Count > DataSegments.size())
392  return make_error<GenericBinaryError>("Too many segment names",
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  }
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",
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",
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),
469  }
470  Section->Relocations.push_back(Reloc);
471  }
472  if (Ptr != End)
473  return make_error<GenericBinaryError>("Reloc section ended prematurely",
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--) {
500  int8_t Form = readVarint7(Ptr);
501  if (Form != wasm::WASM_TYPE_FUNC) {
502  return make_error<GenericBinaryError>("Invalid signature type",
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",
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) {
538  NumImportedFunctions++;
539  Im.SigIndex = readVaruint32(Ptr);
540  break;
542  NumImportedGlobals++;
543  Im.Global.Type = readVarint7(Ptr);
544  Im.Global.Mutable = readVaruint1(Ptr);
545  break;
547  Im.Memory = readLimits(Ptr);
548  break;
550  Im.Table = readTable(Ptr);
552  return make_error<GenericBinaryError>("Invalid table element type",
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",
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",
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",
587  }
588  }
589  if (Ptr != End)
590  return make_error<GenericBinaryError>("Table section ended prematurely",
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",
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",
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) {
635  if (Ex.Index >= FunctionTypes.size() + NumImportedFunctions)
636  return make_error<GenericBinaryError>("Invalid function export",
638  break;
640  if (Ex.Index >= Globals.size() + NumImportedGlobals)
641  return make_error<GenericBinaryError>("Invalid global export",
643  break;
644  }
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",
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",
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",
673  }
674 
675  CodeSection = ArrayRef<uint8_t>(Ptr, End - Ptr);
676 
677  while (FunctionCount--) {
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",
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",
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",
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",
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 
755  return Header;
756 }
757 
758 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
759 
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 
770  switch (Sym.Type) {
773  break;
775  Result |= SymbolRef::SF_Executable;
776  break;
778  Result |= SymbolRef::SF_Executable;
780  break;
782  Result |= SymbolRef::SF_Undefined;
783  break;
785  break;
786  }
787 
788  return Result;
789 }
790 
792  DataRefImpl Ref;
793  Ref.d.a = 0;
794  return BasicSymbolRef(Ref, this);
795 }
796 
798  DataRefImpl Ref;
799  Ref.d.a = Symbols.size();
800  return BasicSymbolRef(Ref, this);
801 }
802 
804  return Symbols[Symb.d.a];
805 }
806 
807 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
808  return getWasmSymbol(Symb.getRawDataRefImpl());
809 }
810 
812  return getWasmSymbol(Symb).Name;
813 }
814 
816  return getSymbolValue(Symb);
817 }
818 
819 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol& Sym) const {
820  switch (Sym.Type) {
825  return Sym.ElementIndex;
827  uint32_t GlobalIndex = Sym.ElementIndex - NumImportedGlobals;
828  assert(GlobalIndex < Globals.size());
829  const wasm::WasmGlobal& Global = Globals[GlobalIndex];
830  // WasmSymbols correspond only to I32_CONST globals
831  assert(Global.InitExpr.Opcode == wasm::WASM_OPCODE_I32_CONST);
832  return Global.InitExpr.Value.Int32;
833  }
834  }
835  llvm_unreachable("invalid symbol type");
836 }
837 
839  return getWasmSymbolValue(getWasmSymbol(Symb));
840 }
841 
843  llvm_unreachable("not yet implemented");
844  return 0;
845 }
846 
848  llvm_unreachable("not yet implemented");
849  return 0;
850 }
851 
854  const WasmSymbol &Sym = getWasmSymbol(Symb);
855 
856  switch (Sym.Type) {
860  return SymbolRef::ST_Function;
863  return SymbolRef::ST_Data;
864  }
865 
866  llvm_unreachable("Unknown WasmSymbol::SymbolType");
867  return SymbolRef::ST_Other;
868 }
869 
872  DataRefImpl Ref;
873  Ref.d.a = getWasmSymbol(Symb).Section;
874  return section_iterator(SectionRef(Ref, this));
875 }
876 
877 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
878 
880  StringRef &Res) const {
881  const WasmSection &S = Sections[Sec.d.a];
882 #define ECase(X) \
883  case wasm::WASM_SEC_##X: \
884  Res = #X; \
885  break
886  switch (S.Type) {
887  ECase(TYPE);
888  ECase(IMPORT);
889  ECase(FUNCTION);
890  ECase(TABLE);
891  ECase(MEMORY);
892  ECase(GLOBAL);
893  ECase(EXPORT);
894  ECase(START);
895  ECase(ELEM);
896  ECase(CODE);
897  ECase(DATA);
899  Res = S.Name;
900  break;
901  default:
903  }
904 #undef ECase
905  return std::error_code();
906 }
907 
908 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
909 
911  return Sec.d.a;
912 }
913 
915  const WasmSection &S = Sections[Sec.d.a];
916  return S.Content.size();
917 }
918 
920  StringRef &Res) const {
921  const WasmSection &S = Sections[Sec.d.a];
922  // This will never fail since wasm sections can never be empty (user-sections
923  // must have a name and non-user sections each have a defined structure).
924  Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
925  S.Content.size());
926  return std::error_code();
927 }
928 
930  return 1;
931 }
932 
934  return false;
935 }
936 
938  return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
939 }
940 
942  return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
943 }
944 
945 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
946 
947 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
948 
949 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
950 
952  DataRefImpl RelocRef;
953  RelocRef.d.a = Ref.d.a;
954  RelocRef.d.b = 0;
955  return relocation_iterator(RelocationRef(RelocRef, this));
956 }
957 
959  const WasmSection &Sec = getWasmSection(Ref);
960  DataRefImpl RelocRef;
961  RelocRef.d.a = Ref.d.a;
962  RelocRef.d.b = Sec.Relocations.size();
963  return relocation_iterator(RelocationRef(RelocRef, this));
964 }
965 
967  Rel.d.b++;
968 }
969 
971  const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
972  return Rel.Offset;
973 }
974 
976  llvm_unreachable("not yet implemented");
977  SymbolRef Ref;
978  return symbol_iterator(Ref);
979 }
980 
982  const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
983  return Rel.Type;
984 }
985 
987  DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
988  const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
989  StringRef Res = "Unknown";
990 
991 #define WASM_RELOC(name, value) \
992  case wasm::name: \
993  Res = #name; \
994  break;
995 
996  switch (Rel.Type) {
997 #include "llvm/BinaryFormat/WasmRelocs/WebAssembly.def"
998  }
999 
1000 #undef WASM_RELOC
1001 
1002  Result.append(Res.begin(), Res.end());
1003 }
1004 
1006  DataRefImpl Ref;
1007  Ref.d.a = 0;
1008  return section_iterator(SectionRef(Ref, this));
1009 }
1010 
1012  DataRefImpl Ref;
1013  Ref.d.a = Sections.size();
1014  return section_iterator(SectionRef(Ref, this));
1015 }
1016 
1017 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1018 
1020 
1021 unsigned WasmObjectFile::getArch() const { return Triple::wasm32; }
1022 
1024  return SubtargetFeatures();
1025 }
1026 
1028  return HasLinkingSection;
1029 }
1030 
1032  assert(Ref.d.a < Sections.size());
1033  return Sections[Ref.d.a];
1034 }
1035 
1036 const WasmSection &
1038  return getWasmSection(Section.getRawDataRefImpl());
1039 }
1040 
1041 const wasm::WasmRelocation &
1043  return getWasmRelocation(Ref.getRawDataRefImpl());
1044 }
1045 
1046 const wasm::WasmRelocation &
1048  assert(Ref.d.a < Sections.size());
1049  const WasmSection& Sec = Sections[Ref.d.a];
1050  assert(Ref.d.b < Sec.Relocations.size());
1051  return Sec.Relocations[Ref.d.b];
1052 }
bool isSectionText(DataRefImpl Sec) const override
uint64_t getRelocationType(DataRefImpl Rel) const override
uint64_t getSectionAddress(DataRefImpl Sec) const override
uint64_t getSymbolValueImpl(DataRefImpl Symb) const override
StringRef getFileFormatName() const override
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
uint64_t getSectionSize(DataRefImpl Sec) const override
#define VARINT7_MIN
static uint8_t readVaruint7(const uint8_t *&Ptr)
section_iterator section_begin() const override
friend class SectionRef
Definition: ObjectFile.h:221
const WasmSymbol & getWasmSymbol(const DataRefImpl &Symb) const
union llvm::wasm::WasmInitExpr::@131 Value
static Error readInitExpr(wasm::WasmInitExpr &Expr, const uint8_t *&Ptr)
uint32_t SectionOffset
Definition: Wasm.h:106
static wasm::WasmLimits readLimits(const uint8_t *&Ptr)
iterator find(StringRef Key)
Definition: StringMap.h:337
This class is the base class for all object file types.
Definition: ObjectFile.h:189
uint8_t getBytesInAddress() const override
The number of bytes used to represent an address in this object file format.
uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override
unsigned getArch() const override
std::error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const override
std::error_code getSectionName(DataRefImpl Sec, StringRef &Res) const override
static StringRef readString(const uint8_t *&Ptr)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
void getRelocationTypeName(DataRefImpl Rel, SmallVectorImpl< char > &Result) const override
Export information to summary.
static int64_t readVarint64(const uint8_t *&Ptr)
StringRef Name
Definition: Wasm.h:50
std::vector< wasm::WasmRelocation > Relocations
Definition: Wasm.h:102
#define VARUINT7_MAX
uint64_t getRelocationOffset(DataRefImpl Rel) const override
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
uint32_t getSymbolAlignment(DataRefImpl Symb) const override
DataRefImpl getRawDataRefImpl() const
Definition: SymbolicFile.h:205
static int32_t readFloat32(const uint8_t *&Ptr)
WasmTable Table
Definition: Wasm.h:81
int64_t decodeSLEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a SLEB128 value.
Definition: LEB128.h:157
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition: ObjectFile.h:51
static Error readSection(WasmSection &Section, const uint8_t *&Ptr, const uint8_t *Start, const uint8_t *Eof)
StringRef Module
Definition: Wasm.h:75
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
static int64_t readLEB128(const uint8_t *&Ptr)
const uint32_t WasmVersion
Definition: Wasm.h:26
ArrayRef< uint8_t > Content
Definition: Wasm.h:99
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:47
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
ArrayRef< uint8_t > Body
Definition: Wasm.h:93
wasm::WasmDataSegment Data
Definition: Wasm.h:107
bool isLocal() const
Definition: Wasm.h:76
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
static uint32_t readVaruint32(const uint8_t *&Ptr)
uint32_t Initial
Definition: Wasm.h:48
bool isSectionBitcode(DataRefImpl Sec) const override
Expected< SymbolRef::Type > getSymbolType(DataRefImpl Symb) const override
uint64_t getSectionIndex(DataRefImpl Sec) const override
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&... Args)
Emplace a new element for the specified key into the map if the key isn&#39;t already in the map...
Definition: StringMap.h:399
uint32_t SigIndex
Definition: Wasm.h:79
WasmLimits Memory
Definition: Wasm.h:82
void moveSectionNext(DataRefImpl &Sec) const override
bool isRelocatableObject() const override
True if this is a relocatable object (.o/.obj).
std::vector< uint32_t > Functions
Definition: Wasm.h:108
uint32_t Kind
Definition: Wasm.h:77
static int64_t readFloat64(const uint8_t *&Ptr)
Import information from summary.
ArrayRef< uint8_t > Content
Definition: Wasm.h:101
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
uint64_t getWasmSymbolValue(const WasmSymbol &Sym) const
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
uint32_t Flags
Definition: Wasm.h:47
section_iterator section_end() const override
static uint8_t readOpcode(const uint8_t *&Ptr)
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
Definition: LEB128.h:124
static int32_t readVarint32(const uint8_t *&Ptr)
static const unsigned End
WasmInitExpr Offset
Definition: Wasm.h:98
const wasm::WasmRelocation & getWasmRelocation(const RelocationRef &Ref) const
uint64_t getSectionAlignment(DataRefImpl Sec) const override
struct llvm::object::DataRefImpl::@254 d
bool isSectionBSS(DataRefImpl Sec) const override
static uint8_t readVaruint1(const uint8_t *&Ptr)
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:462
bool isSectionData(DataRefImpl Sec) const override
bool isWeak() const
Definition: Wasm.h:68
uint32_t Kind
Definition: Wasm.h:42
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const T * data() const
Definition: ArrayRef.h:146
basic_symbol_iterator symbol_begin() const override
static Expected< std::unique_ptr< WasmObjectFile > > createWasmObjectFile(MemoryBufferRef Object)
SubtargetFeatures getFeatures() const override
static int8_t readVarint7(const uint8_t *&Ptr)
bool isSectionCompressed(DataRefImpl Sec) const override
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
static uint64_t readULEB128(const uint8_t *&Ptr)
friend class RelocationRef
Definition: ObjectFile.h:245
WasmInitExpr InitExpr
Definition: Wasm.h:71
WasmGlobal Global
Definition: Wasm.h:80
void moveSymbolNext(DataRefImpl &Symb) const override
SymbolType Type
Definition: Wasm.h:51
uint64_t getSymbolValue(DataRefImpl Symb) const
Definition: ObjectFile.cpp:51
symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Manages the enabling and disabling of subtarget specific features.
uint32_t Section
Definition: Wasm.h:52
const wasm::WasmObjectHeader & getHeader() const
Helper for Errors used as out-parameters.
Definition: Error.h:990
This is a value type class that represents a single symbol in the list of symbols in the object file...
Definition: ObjectFile.h:128
iterator begin() const
Definition: StringRef.h:106
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:398
uint32_t ElementIndex
Definition: Wasm.h:56
WasmLimits Limits
Definition: Wasm.h:54
Expected< StringRef > getSymbolName(DataRefImpl Symb) const override
void moveRelocationNext(DataRefImpl &Rel) const override
int32_t ElemType
Definition: Wasm.h:53
uint32_t read32le(const void *P)
Definition: Endian.h:369
This is a value type class that represents a single symbol in the list of symbols in the object file...
Definition: SymbolicFile.h:99
static wasm::WasmTable readTable(const uint8_t *&Ptr)
Expected< uint64_t > getSymbolAddress(DataRefImpl Symb) const override
uint32_t Index
Definition: Wasm.h:43
static uint32_t readUint32(const uint8_t *&Ptr)
relocation_iterator section_rel_begin(DataRefImpl Sec) const override
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::vector< int32_t > ParamTypes
Definition: Wasm.h:36
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
content_iterator< RelocationRef > relocation_iterator
Definition: ObjectFile.h:76
#define DEBUG(X)
Definition: Debug.h:118
StringRef Name
Definition: Wasm.h:41
const WasmSection & getWasmSection(const SectionRef &Section) const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool isSectionVirtual(DataRefImpl Sec) const override
Expected< section_iterator > getSymbolSection(DataRefImpl Symb) const override
uint32_t getSymbolFlags(DataRefImpl Symb) const override
static uint8_t readUint8(const uint8_t *&Ptr)
iterator end() const
Definition: StringRef.h:108
std::vector< WasmLocalDecl > Locals
Definition: Wasm.h:92
StringRef getData() const
Definition: Binary.cpp:39
WasmInitExpr Offset
Definition: Wasm.h:107
uint32_t Maximum
Definition: Wasm.h:49
#define ECase(X)
iterator end()
Definition: StringMap.h:322
relocation_iterator section_rel_end(DataRefImpl Sec) const override
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:500
StringRef Field
Definition: Wasm.h:76
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:80
WasmObjectFile(MemoryBufferRef Object, Error &Err)
basic_symbol_iterator symbol_end() const override