LLVM  5.0.0
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) {
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",
189  Section.Content = ArrayRef<uint8_t>(Ptr, Size);
190  Ptr += Size;
191  return Error::success();
192 }
193 
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",
204  return;
205  }
206  const uint8_t *Ptr = getPtr(4);
207  Header.Version = readUint32(Ptr);
208  if (Header.Version != wasm::WasmVersion) {
209  Err = make_error<StringError>("Bad version number",
211  return;
212  }
213 
214  const uint8_t *Eof = getPtr(getData().size());
215  WasmSection Sec;
216  while (Ptr < Eof) {
217  if ((Err = readSection(Sec, Ptr, getPtr(0))))
218  return;
219  if ((Err = parseSection(Sec)))
220  return;
221 
222  Sections.push_back(Sec);
223  }
224 }
225 
226 Error WasmObjectFile::parseSection(WasmSection &Sec) {
227  const uint8_t* Start = Sec.Content.data();
228  const uint8_t* End = Start + Sec.Content.size();
229  switch (Sec.Type) {
231  return parseCustomSection(Sec, Start, End);
232  case wasm::WASM_SEC_TYPE:
233  return parseTypeSection(Start, End);
235  return parseImportSection(Start, End);
237  return parseFunctionSection(Start, End);
239  return parseTableSection(Start, End);
241  return parseMemorySection(Start, End);
243  return parseGlobalSection(Start, End);
245  return parseExportSection(Start, End);
247  return parseStartSection(Start, End);
248  case wasm::WASM_SEC_ELEM:
249  return parseElemSection(Start, End);
250  case wasm::WASM_SEC_CODE:
251  return parseCodeSection(Start, End);
252  case wasm::WASM_SEC_DATA:
253  return parseDataSection(Start, End);
254  default:
255  return make_error<GenericBinaryError>("Bad section type",
257  }
258 }
259 
260 Error WasmObjectFile::parseNameSection(const uint8_t *Ptr, const uint8_t *End) {
261  while (Ptr < End) {
262  uint8_t Type = readVarint7(Ptr);
263  uint32_t Size = readVaruint32(Ptr);
264  const uint8_t *SubSectionEnd = Ptr + Size;
265  switch (Type) {
267  uint32_t Count = readVaruint32(Ptr);
268  while (Count--) {
269  uint32_t Index = readVaruint32(Ptr);
270  StringRef Name = readString(Ptr);
271  if (!Name.empty())
272  Symbols.emplace_back(Name,
274  Sections.size(), Index);
275  }
276  break;
277  }
278  // Ignore local names for now
280  default:
281  Ptr += Size;
282  break;
283  }
284  if (Ptr != SubSectionEnd)
285  return make_error<GenericBinaryError>("Name sub-section ended prematurely",
287  }
288 
289  if (Ptr != End)
290  return make_error<GenericBinaryError>("Name section ended prematurely",
292  return Error::success();
293 }
294 
295 Error WasmObjectFile::parseLinkingSection(const uint8_t *Ptr,
296  const uint8_t *End) {
297  HasLinkingSection = true;
298  while (Ptr < End) {
299  uint8_t Type = readVarint7(Ptr);
300  uint32_t Size = readVaruint32(Ptr);
301  const uint8_t *SubSectionEnd = Ptr + Size;
302  switch (Type) {
303  case wasm::WASM_SYMBOL_INFO: {
304  uint32_t Count = readVaruint32(Ptr);
305  while (Count--) {
306  StringRef Symbol = readString(Ptr);
307  DEBUG(dbgs() << "reading syminfo: " << Symbol << "\n");
309  auto iter = SymbolMap.find(Symbol);
310  if (iter == SymbolMap.end()) {
311  return make_error<GenericBinaryError>(
312  "Invalid symbol name in linking section: " + Symbol,
314  }
315  uint32_t SymIndex = iter->second;
316  assert(SymIndex < Symbols.size());
317  Symbols[SymIndex].Flags = Flags;
318  DEBUG(dbgs() << "Set symbol flags index:"
319  << SymIndex << " name:"
320  << Symbols[SymIndex].Name << " exptected:"
321  << Symbol << " flags: " << Flags << "\n");
322  }
323  break;
324  }
326  LinkingData.DataSize = readVaruint32(Ptr);
327  break;
329  LinkingData.DataAlignment = readVaruint32(Ptr);
330  break;
332  default:
333  Ptr += Size;
334  break;
335  }
336  if (Ptr != SubSectionEnd)
337  return make_error<GenericBinaryError>(
338  "Linking sub-section ended prematurely", object_error::parse_failed);
339  }
340  if (Ptr != End)
341  return make_error<GenericBinaryError>("Linking section ended prematurely",
343  return Error::success();
344 }
345 
346 WasmSection* WasmObjectFile::findCustomSectionByName(StringRef Name) {
347  for (WasmSection& Section : Sections) {
348  if (Section.Type == wasm::WASM_SEC_CUSTOM && Section.Name == Name)
349  return &Section;
350  }
351  return nullptr;
352 }
353 
354 WasmSection* WasmObjectFile::findSectionByType(uint32_t Type) {
355  assert(Type != wasm::WASM_SEC_CUSTOM);
356  for (WasmSection& Section : Sections) {
357  if (Section.Type == Type)
358  return &Section;
359  }
360  return nullptr;
361 }
362 
363 Error WasmObjectFile::parseRelocSection(StringRef Name, const uint8_t *Ptr,
364  const uint8_t *End) {
365  uint8_t SectionCode = readVarint7(Ptr);
366  WasmSection* Section = nullptr;
367  if (SectionCode == wasm::WASM_SEC_CUSTOM) {
368  StringRef Name = readString(Ptr);
369  Section = findCustomSectionByName(Name);
370  } else {
371  Section = findSectionByType(SectionCode);
372  }
373  if (!Section)
374  return make_error<GenericBinaryError>("Invalid section code",
376  uint32_t RelocCount = readVaruint32(Ptr);
377  while (RelocCount--) {
378  wasm::WasmRelocation Reloc;
379  memset(&Reloc, 0, sizeof(Reloc));
380  Reloc.Type = readVaruint32(Ptr);
381  Reloc.Offset = readVaruint32(Ptr);
382  Reloc.Index = readVaruint32(Ptr);
383  switch (Reloc.Type) {
384  case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
385  case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
386  case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
387  case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
388  case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
389  break;
390  case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
391  case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
392  case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
393  Reloc.Addend = readVarint32(Ptr);
394  break;
395  default:
396  return make_error<GenericBinaryError>("Bad relocation type: " +
397  Twine(Reloc.Type),
399  }
400  Section->Relocations.push_back(Reloc);
401  }
402  if (Ptr != End)
403  return make_error<GenericBinaryError>("Reloc section ended prematurely",
405  return Error::success();
406 }
407 
408 Error WasmObjectFile::parseCustomSection(WasmSection &Sec,
409  const uint8_t *Ptr, const uint8_t *End) {
410  Sec.Name = readString(Ptr);
411  if (Sec.Name == "name") {
412  if (Error Err = parseNameSection(Ptr, End))
413  return Err;
414  } else if (Sec.Name == "linking") {
415  if (Error Err = parseLinkingSection(Ptr, End))
416  return Err;
417  } else if (Sec.Name.startswith("reloc.")) {
418  if (Error Err = parseRelocSection(Sec.Name, Ptr, End))
419  return Err;
420  }
421  return Error::success();
422 }
423 
424 Error WasmObjectFile::parseTypeSection(const uint8_t *Ptr, const uint8_t *End) {
425  uint32_t Count = readVaruint32(Ptr);
426  Signatures.reserve(Count);
427  while (Count--) {
430  int8_t Form = readVarint7(Ptr);
431  if (Form != wasm::WASM_TYPE_FUNC) {
432  return make_error<GenericBinaryError>("Invalid signature type",
434  }
435  uint32_t ParamCount = readVaruint32(Ptr);
436  Sig.ParamTypes.reserve(ParamCount);
437  while (ParamCount--) {
438  uint32_t ParamType = readVarint7(Ptr);
439  Sig.ParamTypes.push_back(ParamType);
440  }
441  uint32_t ReturnCount = readVaruint32(Ptr);
442  if (ReturnCount) {
443  if (ReturnCount != 1) {
444  return make_error<GenericBinaryError>(
445  "Multiple return types not supported", object_error::parse_failed);
446  }
447  Sig.ReturnType = readVarint7(Ptr);
448  }
449  Signatures.push_back(Sig);
450  }
451  if (Ptr != End)
452  return make_error<GenericBinaryError>("Type section ended prematurely",
454  return Error::success();
455 }
456 
457 Error WasmObjectFile::parseImportSection(const uint8_t *Ptr, const uint8_t *End) {
458  uint32_t Count = readVaruint32(Ptr);
459  Imports.reserve(Count);
460  for (uint32_t i = 0; i < Count; i++) {
461  wasm::WasmImport Im;
462  Im.Module = readString(Ptr);
463  Im.Field = readString(Ptr);
464  Im.Kind = readUint8(Ptr);
465  switch (Im.Kind) {
467  Im.SigIndex = readVaruint32(Ptr);
468  SymbolMap.try_emplace(Im.Field, Symbols.size());
469  Symbols.emplace_back(Im.Field, WasmSymbol::SymbolType::FUNCTION_IMPORT,
470  Sections.size(), i);
471  DEBUG(dbgs() << "Adding import: " << Symbols.back()
472  << " sym index:" << Symbols.size() << "\n");
473  break;
475  Im.Global.Type = readVarint7(Ptr);
476  Im.Global.Mutable = readVaruint1(Ptr);
477  SymbolMap.try_emplace(Im.Field, Symbols.size());
478  Symbols.emplace_back(Im.Field, WasmSymbol::SymbolType::GLOBAL_IMPORT,
479  Sections.size(), i);
480  DEBUG(dbgs() << "Adding import: " << Symbols.back()
481  << " sym index:" << Symbols.size() << "\n");
482  break;
484  Im.Memory = readLimits(Ptr);
485  break;
487  Im.Table = readTable(Ptr);
489  return make_error<GenericBinaryError>("Invalid table element type",
491  }
492  break;
493  default:
494  return make_error<GenericBinaryError>(
495  "Unexpected import kind", object_error::parse_failed);
496  }
497  Imports.push_back(Im);
498  }
499  if (Ptr != End)
500  return make_error<GenericBinaryError>("Import section ended prematurely",
502  return Error::success();
503 }
504 
505 Error WasmObjectFile::parseFunctionSection(const uint8_t *Ptr, const uint8_t *End) {
506  uint32_t Count = readVaruint32(Ptr);
507  FunctionTypes.reserve(Count);
508  while (Count--) {
509  FunctionTypes.push_back(readVaruint32(Ptr));
510  }
511  if (Ptr != End)
512  return make_error<GenericBinaryError>("Function section ended prematurely",
514  return Error::success();
515 }
516 
517 Error WasmObjectFile::parseTableSection(const uint8_t *Ptr, const uint8_t *End) {
518  uint32_t Count = readVaruint32(Ptr);
519  Tables.reserve(Count);
520  while (Count--) {
521  Tables.push_back(readTable(Ptr));
522  if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
523  return make_error<GenericBinaryError>("Invalid table element type",
525  }
526  }
527  if (Ptr != End)
528  return make_error<GenericBinaryError>("Table section ended prematurely",
530  return Error::success();
531 }
532 
533 Error WasmObjectFile::parseMemorySection(const uint8_t *Ptr, const uint8_t *End) {
534  uint32_t Count = readVaruint32(Ptr);
535  Memories.reserve(Count);
536  while (Count--) {
537  Memories.push_back(readLimits(Ptr));
538  }
539  if (Ptr != End)
540  return make_error<GenericBinaryError>("Memory section ended prematurely",
542  return Error::success();
543 }
544 
545 Error WasmObjectFile::parseGlobalSection(const uint8_t *Ptr, const uint8_t *End) {
546  uint32_t Count = readVaruint32(Ptr);
547  Globals.reserve(Count);
548  while (Count--) {
550  Global.Type = readVarint7(Ptr);
551  Global.Mutable = readVaruint1(Ptr);
552  if (Error Err = readInitExpr(Global.InitExpr, Ptr))
553  return Err;
554  Globals.push_back(Global);
555  }
556  if (Ptr != End)
557  return make_error<GenericBinaryError>("Global section ended prematurely",
559  return Error::success();
560 }
561 
562 Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) {
563  uint32_t Count = readVaruint32(Ptr);
564  Exports.reserve(Count);
565  for (uint32_t i = 0; i < Count; i++) {
566  wasm::WasmExport Ex;
567  Ex.Name = readString(Ptr);
568  Ex.Kind = readUint8(Ptr);
569  Ex.Index = readVaruint32(Ptr);
570  WasmSymbol::SymbolType ExportType;
571  bool MakeSymbol = false;
572  switch (Ex.Kind) {
575  MakeSymbol = true;
576  break;
579  MakeSymbol = true;
580  break;
583  break;
584  default:
585  return make_error<GenericBinaryError>(
586  "Unexpected export kind", object_error::parse_failed);
587  }
588  if (MakeSymbol) {
589  auto Pair = SymbolMap.try_emplace(Ex.Name, Symbols.size());
590  if (Pair.second) {
591  Symbols.emplace_back(Ex.Name, ExportType,
592  Sections.size(), i);
593  DEBUG(dbgs() << "Adding export: " << Symbols.back()
594  << " sym index:" << Symbols.size() << "\n");
595  } else {
596  uint32_t SymIndex = Pair.first->second;
597  Symbols[SymIndex] = WasmSymbol(Ex.Name, ExportType, Sections.size(), i);
598  DEBUG(dbgs() << "Replacing existing symbol: " << Symbols[SymIndex]
599  << " sym index:" << SymIndex << "\n");
600  }
601  }
602  Exports.push_back(Ex);
603  }
604  if (Ptr != End)
605  return make_error<GenericBinaryError>("Export section ended prematurely",
607  return Error::success();
608 }
609 
610 Error WasmObjectFile::parseStartSection(const uint8_t *Ptr, const uint8_t *End) {
611  StartFunction = readVaruint32(Ptr);
612  if (StartFunction >= FunctionTypes.size())
613  return make_error<GenericBinaryError>("Invalid start function",
615  return Error::success();
616 }
617 
618 Error WasmObjectFile::parseCodeSection(const uint8_t *Ptr, const uint8_t *End) {
619  uint32_t FunctionCount = readVaruint32(Ptr);
620  if (FunctionCount != FunctionTypes.size()) {
621  return make_error<GenericBinaryError>("Invalid function count",
623  }
624 
625  CodeSection = ArrayRef<uint8_t>(Ptr, End - Ptr);
626 
627  while (FunctionCount--) {
629  uint32_t FunctionSize = readVaruint32(Ptr);
630  const uint8_t *FunctionEnd = Ptr + FunctionSize;
631 
632  uint32_t NumLocalDecls = readVaruint32(Ptr);
633  Function.Locals.reserve(NumLocalDecls);
634  while (NumLocalDecls--) {
635  wasm::WasmLocalDecl Decl;
636  Decl.Count = readVaruint32(Ptr);
637  Decl.Type = readVarint7(Ptr);
638  Function.Locals.push_back(Decl);
639  }
640 
641  uint32_t BodySize = FunctionEnd - Ptr;
642  Function.Body = ArrayRef<uint8_t>(Ptr, BodySize);
643  Ptr += BodySize;
644  assert(Ptr == FunctionEnd);
645  Functions.push_back(Function);
646  }
647  if (Ptr != End)
648  return make_error<GenericBinaryError>("Code section ended prematurely",
650  return Error::success();
651 }
652 
653 Error WasmObjectFile::parseElemSection(const uint8_t *Ptr, const uint8_t *End) {
654  uint32_t Count = readVaruint32(Ptr);
655  ElemSegments.reserve(Count);
656  while (Count--) {
657  wasm::WasmElemSegment Segment;
658  Segment.TableIndex = readVaruint32(Ptr);
659  if (Segment.TableIndex != 0) {
660  return make_error<GenericBinaryError>("Invalid TableIndex",
662  }
663  if (Error Err = readInitExpr(Segment.Offset, Ptr))
664  return Err;
665  uint32_t NumElems = readVaruint32(Ptr);
666  while (NumElems--) {
667  Segment.Functions.push_back(readVaruint32(Ptr));
668  }
669  ElemSegments.push_back(Segment);
670  }
671  if (Ptr != End)
672  return make_error<GenericBinaryError>("Elem section ended prematurely",
674  return Error::success();
675 }
676 
677 Error WasmObjectFile::parseDataSection(const uint8_t *Ptr, const uint8_t *End) {
678  const uint8_t *Start = Ptr;
679  uint32_t Count = readVaruint32(Ptr);
680  DataSegments.reserve(Count);
681  while (Count--) {
682  WasmSegment Segment;
683  Segment.Data.MemoryIndex = readVaruint32(Ptr);
684  if (Error Err = readInitExpr(Segment.Data.Offset, Ptr))
685  return Err;
686  uint32_t Size = readVaruint32(Ptr);
687  Segment.Data.Content = ArrayRef<uint8_t>(Ptr, Size);
688  Segment.SectionOffset = Ptr - Start;
689  Ptr += Size;
690  DataSegments.push_back(Segment);
691  }
692  if (Ptr != End)
693  return make_error<GenericBinaryError>("Data section ended prematurely",
695  return Error::success();
696 }
697 
698 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
699  return reinterpret_cast<const uint8_t *>(getData().substr(Offset, 1).data());
700 }
701 
703  return Header;
704 }
705 
706 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
707 
709  uint32_t Result = SymbolRef::SF_None;
710  const WasmSymbol &Sym = getWasmSymbol(Symb);
711 
712  DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
714  Result |= SymbolRef::SF_Weak;
715 
716  switch (Sym.Type) {
719  break;
722  break;
724  Result |= SymbolRef::SF_Executable;
726  break;
728  Result |= SymbolRef::SF_Undefined;
729  break;
731  Result |= SymbolRef::SF_Global;
732  break;
733  }
734 
735  return Result;
736 }
737 
739  DataRefImpl Ref;
740  Ref.d.a = 0;
741  return BasicSymbolRef(Ref, this);
742 }
743 
745  DataRefImpl Ref;
746  Ref.d.a = Symbols.size();
747  return BasicSymbolRef(Ref, this);
748 }
749 
750 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
751  return Symbols[Symb.d.a];
752 }
753 
754 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
755  return getWasmSymbol(Symb.getRawDataRefImpl());
756 }
757 
759  return getWasmSymbol(Symb).Name;
760 }
761 
763  return getSymbolValue(Symb);
764 }
765 
767  const WasmSymbol& Sym = getWasmSymbol(Symb);
768  switch (Sym.Type) {
771  return 0;
774  return Exports[Sym.ElementIndex].Index;
776  return Sym.ElementIndex;
777  }
778  llvm_unreachable("invalid symbol type");
779 }
780 
782  llvm_unreachable("not yet implemented");
783  return 0;
784 }
785 
787  llvm_unreachable("not yet implemented");
788  return 0;
789 }
790 
793  const WasmSymbol &Sym = getWasmSymbol(Symb);
794 
795  switch (Sym.Type) {
799  return SymbolRef::ST_Function;
802  return SymbolRef::ST_Data;
803  }
804 
805  llvm_unreachable("Unknown WasmSymbol::SymbolType");
806  return SymbolRef::ST_Other;
807 }
808 
811  DataRefImpl Ref;
812  Ref.d.a = getWasmSymbol(Symb).Section;
813  return section_iterator(SectionRef(Ref, this));
814 }
815 
816 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
817 
819  StringRef &Res) const {
820  const WasmSection &S = Sections[Sec.d.a];
821 #define ECase(X) \
822  case wasm::WASM_SEC_##X: \
823  Res = #X; \
824  break
825  switch (S.Type) {
826  ECase(TYPE);
827  ECase(IMPORT);
828  ECase(FUNCTION);
829  ECase(TABLE);
830  ECase(MEMORY);
831  ECase(GLOBAL);
832  ECase(EXPORT);
833  ECase(START);
834  ECase(ELEM);
835  ECase(CODE);
836  ECase(DATA);
838  Res = S.Name;
839  break;
840  default:
842  }
843 #undef ECase
844  return std::error_code();
845 }
846 
847 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
848 
850  return Sec.d.a;
851 }
852 
854  const WasmSection &S = Sections[Sec.d.a];
855  return S.Content.size();
856 }
857 
859  StringRef &Res) const {
860  const WasmSection &S = Sections[Sec.d.a];
861  // This will never fail since wasm sections can never be empty (user-sections
862  // must have a name and non-user sections each have a defined structure).
863  Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
864  S.Content.size());
865  return std::error_code();
866 }
867 
869  return 1;
870 }
871 
873  return false;
874 }
875 
877  return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
878 }
879 
881  return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
882 }
883 
884 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
885 
886 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
887 
888 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
889 
891  DataRefImpl RelocRef;
892  RelocRef.d.a = Ref.d.a;
893  RelocRef.d.b = 0;
894  return relocation_iterator(RelocationRef(RelocRef, this));
895 }
896 
898  const WasmSection &Sec = getWasmSection(Ref);
899  DataRefImpl RelocRef;
900  RelocRef.d.a = Ref.d.a;
901  RelocRef.d.b = Sec.Relocations.size();
902  return relocation_iterator(RelocationRef(RelocRef, this));
903 }
904 
906  Rel.d.b++;
907 }
908 
910  const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
911  return Rel.Offset;
912 }
913 
915  llvm_unreachable("not yet implemented");
916  SymbolRef Ref;
917  return symbol_iterator(Ref);
918 }
919 
921  const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
922  return Rel.Type;
923 }
924 
926  DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
927  const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
928  StringRef Res = "Unknown";
929 
930 #define WASM_RELOC(name, value) \
931  case wasm::name: \
932  Res = #name; \
933  break;
934 
935  switch (Rel.Type) {
936 #include "llvm/BinaryFormat/WasmRelocs/WebAssembly.def"
937  }
938 
939 #undef WASM_RELOC
940 
941  Result.append(Res.begin(), Res.end());
942 }
943 
945  DataRefImpl Ref;
946  Ref.d.a = 0;
947  return section_iterator(SectionRef(Ref, this));
948 }
949 
951  DataRefImpl Ref;
952  Ref.d.a = Sections.size();
953  return section_iterator(SectionRef(Ref, this));
954 }
955 
956 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
957 
959 
960 unsigned WasmObjectFile::getArch() const { return Triple::wasm32; }
961 
963  return SubtargetFeatures();
964 }
965 
967  return HasLinkingSection;
968 }
969 
971  assert(Ref.d.a < Sections.size());
972  return Sections[Ref.d.a];
973 }
974 
975 const WasmSection &
976 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
977  return getWasmSection(Section.getRawDataRefImpl());
978 }
979 
980 const wasm::WasmRelocation &
981 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
982  return getWasmRelocation(Ref.getRawDataRefImpl());
983 }
984 
985 const wasm::WasmRelocation &
986 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
987  assert(Ref.d.a < Sections.size());
988  const WasmSection& Sec = Sections[Ref.d.a];
989  assert(Ref.d.b < Sec.Relocations.size());
990  return Sec.Relocations[Ref.d.b];
991 }
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
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
static Error readInitExpr(wasm::WasmInitExpr &Expr, const uint8_t *&Ptr)
const wasm::WasmRelocation & getWasmRelocation(const RelocationRef &Ref) const
static wasm::WasmLimits readLimits(const uint8_t *&Ptr)
iterator find(StringRef Key)
Definition: StringMap.h:333
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)
void getRelocationTypeName(DataRefImpl Rel, SmallVectorImpl< char > &Result) const override
static int64_t readVarint64(const uint8_t *&Ptr)
StringRef Name
Definition: Wasm.h:49
std::vector< wasm::WasmRelocation > Relocations
Definition: Wasm.h:79
#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
const WasmSection & getWasmSection(const SectionRef &Section) const
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:147
StringRef getData() const
Definition: Binary.cpp:39
StringRef Module
Definition: Wasm.h:75
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
static Error readSection(WasmSection &Section, const uint8_t *&Ptr, const uint8_t *Start)
static int64_t readLEB128(const uint8_t *&Ptr)
const uint32_t WasmVersion
Definition: Wasm.h:26
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:48
ArrayRef< uint8_t > Body
Definition: Wasm.h:93
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 size_t size() const
size - Get the string size.
Definition: StringRef.h:138
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
const char * Name
uint32_t SigIndex
Definition: Wasm.h:79
iterator begin() const
Definition: StringRef.h:106
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:105
uint32_t Kind
Definition: Wasm.h:77
static int64_t readFloat64(const uint8_t *&Ptr)
ArrayRef< uint8_t > Content
Definition: Wasm.h:78
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
uint32_t Flags
Definition: Wasm.h:47
section_iterator section_end() const override
static uint8_t readOpcode(const uint8_t *&Ptr)
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
const wasm::WasmObjectHeader & getHeader() const
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:114
static int32_t readVarint32(const uint8_t *&Ptr)
static const unsigned End
uint64_t getSectionAlignment(DataRefImpl Sec) const override
union llvm::wasm::WasmInitExpr::@125 Value
bool isSectionBSS(DataRefImpl Sec) const override
static uint8_t readVaruint1(const uint8_t *&Ptr)
struct llvm::object::DataRefImpl::@230 d
bool isSectionData(DataRefImpl Sec) const override
uint32_t Kind
Definition: Wasm.h:42
basic_symbol_iterator symbol_begin() const override
static Expected< std::unique_ptr< WasmObjectFile > > createWasmObjectFile(MemoryBufferRef Object)
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't already in the map...
Definition: StringMap.h:395
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:311
static uint64_t readULEB128(const uint8_t *&Ptr)
const WasmSymbol & getWasmSymbol(const DataRefImpl &Symb) const
friend class RelocationRef
Definition: ObjectFile.h:244
WasmInitExpr InitExpr
Definition: Wasm.h:71
WasmGlobal Global
Definition: Wasm.h:80
void moveSymbolNext(DataRefImpl &Symb) const override
SymbolType Type
Definition: Wasm.h:50
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:51
Helper for Errors used as out-parameters.
Definition: Error.h:621
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
This is a value type class that represents a single symbol in the list of symbols in the object file...
Definition: ObjectFile.h:128
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:395
uint32_t ElementIndex
Definition: Wasm.h:56
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
WasmLimits Limits
Definition: Wasm.h:54
Expected< StringRef > getSymbolName(DataRefImpl Symb) const override
void moveRelocationNext(DataRefImpl &Rel) const override
uint64_t getSymbolValue(DataRefImpl Symb) const
Definition: ObjectFile.cpp:51
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
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
content_iterator< RelocationRef > relocation_iterator
Definition: ObjectFile.h:77
iterator end() const
Definition: StringRef.h:108
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
#define DEBUG(X)
Definition: Debug.h:118
StringRef Name
Definition: Wasm.h:41
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool isSectionVirtual(DataRefImpl Sec) const override
int * Ptr
Expected< section_iterator > getSymbolSection(DataRefImpl Symb) const override
uint32_t getSymbolFlags(DataRefImpl Symb) const override
static uint8_t readUint8(const uint8_t *&Ptr)
std::vector< WasmLocalDecl > Locals
Definition: Wasm.h:92
const T * data() const
Definition: ArrayRef.h:146
WasmInitExpr Offset
Definition: Wasm.h:104
uint32_t Maximum
Definition: Wasm.h:49
#define ECase(X)
iterator end()
Definition: StringMap.h:318
relocation_iterator section_rel_end(DataRefImpl Sec) const override
StringRef Field
Definition: Wasm.h:76
WasmObjectFile(MemoryBufferRef Object, Error &Err)
basic_symbol_iterator symbol_end() const override