1 //===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
29 #include <system_error>
31 #define DEBUG_TYPE "wasm-object"
34 using namespace object;
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);
41 return std::move(Err);
43 return std::move(ObjectFile);
46 #define VARINT7_MAX ((1<<7)-1)
47 #define VARINT7_MIN (-(1<<7))
48 #define VARUINT7_MAX (1<<7)
49 #define VARUINT1_MAX (1)
51 static uint8_t readUint8(const uint8_t *&Ptr) { return *Ptr++; }
53 static uint32_t readUint32(const uint8_t *&Ptr) {
54 uint32_t Result = support::endian::read32le(Ptr);
55 Ptr += sizeof(Result);
59 static int32_t readFloat32(const uint8_t *&Ptr) {
61 memcpy(&Result, Ptr, sizeof(Result));
62 Ptr += sizeof(Result);
66 static int64_t readFloat64(const uint8_t *&Ptr) {
68 memcpy(&Result, Ptr, sizeof(Result));
69 Ptr += sizeof(Result);
73 static uint64_t readULEB128(const uint8_t *&Ptr) {
75 uint64_t Result = decodeULEB128(Ptr, &Count);
80 static StringRef readString(const uint8_t *&Ptr) {
81 uint32_t StringLen = readULEB128(Ptr);
82 StringRef Return = StringRef(reinterpret_cast<const char *>(Ptr), StringLen);
87 static int64_t readLEB128(const uint8_t *&Ptr) {
89 uint64_t Result = decodeSLEB128(Ptr, &Count);
94 static uint8_t readVaruint1(const uint8_t *&Ptr) {
95 int64_t result = readLEB128(Ptr);
96 assert(result <= VARUINT1_MAX && result >= 0);
100 static int8_t readVarint7(const uint8_t *&Ptr) {
101 int64_t result = readLEB128(Ptr);
102 assert(result <= VARINT7_MAX && result >= VARINT7_MIN);
106 static uint8_t readVaruint7(const uint8_t *&Ptr) {
107 uint64_t result = readULEB128(Ptr);
108 assert(result <= VARUINT7_MAX);
112 static int32_t readVarint32(const uint8_t *&Ptr) {
113 int64_t result = readLEB128(Ptr);
114 assert(result <= INT32_MAX && result >= INT32_MIN);
118 static uint32_t readVaruint32(const uint8_t *&Ptr) {
119 uint64_t result = readULEB128(Ptr);
120 assert(result <= UINT32_MAX);
124 static int64_t readVarint64(const uint8_t *&Ptr) {
125 return readLEB128(Ptr);
128 static uint8_t readOpcode(const uint8_t *&Ptr) {
129 return readUint8(Ptr);
132 static Error readInitExpr(wasm::WasmInitExpr &Expr, const uint8_t *&Ptr) {
133 Expr.Opcode = readOpcode(Ptr);
135 switch (Expr.Opcode) {
136 case wasm::WASM_OPCODE_I32_CONST:
137 Expr.Value.Int32 = readVarint32(Ptr);
139 case wasm::WASM_OPCODE_I64_CONST:
140 Expr.Value.Int64 = readVarint64(Ptr);
142 case wasm::WASM_OPCODE_F32_CONST:
143 Expr.Value.Float32 = readFloat32(Ptr);
145 case wasm::WASM_OPCODE_F64_CONST:
146 Expr.Value.Float64 = readFloat64(Ptr);
148 case wasm::WASM_OPCODE_GET_GLOBAL:
149 Expr.Value.Global = readULEB128(Ptr);
152 return make_error<GenericBinaryError>("Invalid opcode in init_expr",
153 object_error::parse_failed);
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);
161 return Error::success();
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);
173 static wasm::WasmTable readTable(const uint8_t *&Ptr) {
174 wasm::WasmTable Table;
175 Table.ElemType = readVarint7(Ptr);
176 Table.Limits = readLimits(Ptr);
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);
187 return make_error<StringError>("Zero length section",
188 object_error::parse_failed);
189 Section.Content = ArrayRef<uint8_t>(Ptr, Size);
191 return Error::success();
194 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
195 : ObjectFile(Binary::ID_Wasm, Buffer) {
196 LinkingData.DataAlignment = 0;
197 LinkingData.DataSize = 0;
199 ErrorAsOutParameter ErrAsOutParam(&Err);
200 Header.Magic = getData().substr(0, 4);
201 if (Header.Magic != StringRef("\0asm", 4)) {
202 Err = make_error<StringError>("Bad magic number",
203 object_error::parse_failed);
207 const uint8_t *Eof = getPtr(getData().size());
208 const uint8_t *Ptr = getPtr(4);
211 Err = make_error<StringError>("Missing version number",
212 object_error::parse_failed);
216 Header.Version = readUint32(Ptr);
217 if (Header.Version != wasm::WasmVersion) {
218 Err = make_error<StringError>("Bad version number",
219 object_error::parse_failed);
225 if ((Err = readSection(Sec, Ptr, getPtr(0))))
227 if ((Err = parseSection(Sec)))
230 Sections.push_back(Sec);
234 Error WasmObjectFile::parseSection(WasmSection &Sec) {
235 const uint8_t* Start = Sec.Content.data();
236 const uint8_t* End = Start + Sec.Content.size();
238 case wasm::WASM_SEC_CUSTOM:
239 return parseCustomSection(Sec, Start, End);
240 case wasm::WASM_SEC_TYPE:
241 return parseTypeSection(Start, End);
242 case wasm::WASM_SEC_IMPORT:
243 return parseImportSection(Start, End);
244 case wasm::WASM_SEC_FUNCTION:
245 return parseFunctionSection(Start, End);
246 case wasm::WASM_SEC_TABLE:
247 return parseTableSection(Start, End);
248 case wasm::WASM_SEC_MEMORY:
249 return parseMemorySection(Start, End);
250 case wasm::WASM_SEC_GLOBAL:
251 return parseGlobalSection(Start, End);
252 case wasm::WASM_SEC_EXPORT:
253 return parseExportSection(Start, End);
254 case wasm::WASM_SEC_START:
255 return parseStartSection(Start, End);
256 case wasm::WASM_SEC_ELEM:
257 return parseElemSection(Start, End);
258 case wasm::WASM_SEC_CODE:
259 return parseCodeSection(Start, End);
260 case wasm::WASM_SEC_DATA:
261 return parseDataSection(Start, End);
263 return make_error<GenericBinaryError>("Bad section type",
264 object_error::parse_failed);
268 Error WasmObjectFile::parseNameSection(const uint8_t *Ptr, const uint8_t *End) {
270 uint8_t Type = readVarint7(Ptr);
271 uint32_t Size = readVaruint32(Ptr);
272 const uint8_t *SubSectionEnd = Ptr + Size;
274 case wasm::WASM_NAMES_FUNCTION: {
275 uint32_t Count = readVaruint32(Ptr);
277 uint32_t Index = readVaruint32(Ptr);
278 StringRef Name = readString(Ptr);
280 Symbols.emplace_back(Name,
281 WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME,
282 Sections.size(), Index);
286 // Ignore local names for now
287 case wasm::WASM_NAMES_LOCAL:
292 if (Ptr != SubSectionEnd)
293 return make_error<GenericBinaryError>("Name sub-section ended prematurely",
294 object_error::parse_failed);
298 return make_error<GenericBinaryError>("Name section ended prematurely",
299 object_error::parse_failed);
300 return Error::success();
303 void WasmObjectFile::populateSymbolTable() {
304 // Add imports to symbol table
305 size_t ImportIndex = 0;
306 size_t GlobalIndex = 0;
307 size_t FunctionIndex = 0;
308 for (const wasm::WasmImport& Import : Imports) {
309 switch (Import.Kind) {
310 case wasm::WASM_EXTERNAL_GLOBAL:
311 assert(Import.Global.Type == wasm::WASM_TYPE_I32);
312 SymbolMap.try_emplace(Import.Field, Symbols.size());
313 Symbols.emplace_back(Import.Field, WasmSymbol::SymbolType::GLOBAL_IMPORT,
314 ImportSection, GlobalIndex++, ImportIndex);
315 DEBUG(dbgs() << "Adding import: " << Symbols.back()
316 << " sym index:" << Symbols.size() << "\n");
318 case wasm::WASM_EXTERNAL_FUNCTION:
319 SymbolMap.try_emplace(Import.Field, Symbols.size());
320 Symbols.emplace_back(Import.Field,
321 WasmSymbol::SymbolType::FUNCTION_IMPORT,
322 ImportSection, FunctionIndex++, ImportIndex);
323 DEBUG(dbgs() << "Adding import: " << Symbols.back()
324 << " sym index:" << Symbols.size() << "\n");
332 // Add exports to symbol table
333 for (const wasm::WasmExport& Export : Exports) {
334 if (Export.Kind == wasm::WASM_EXTERNAL_FUNCTION ||
335 Export.Kind == wasm::WASM_EXTERNAL_GLOBAL) {
336 WasmSymbol::SymbolType ExportType =
337 Export.Kind == wasm::WASM_EXTERNAL_FUNCTION
338 ? WasmSymbol::SymbolType::FUNCTION_EXPORT
339 : WasmSymbol::SymbolType::GLOBAL_EXPORT;
340 SymbolMap.try_emplace(Export.Name, Symbols.size());
341 Symbols.emplace_back(Export.Name, ExportType,
342 ExportSection, Export.Index);
343 DEBUG(dbgs() << "Adding export: " << Symbols.back()
344 << " sym index:" << Symbols.size() << "\n");
349 Error WasmObjectFile::parseLinkingSection(const uint8_t *Ptr,
350 const uint8_t *End) {
351 HasLinkingSection = true;
353 // Only populate the symbol table with imports and exports if the object
354 // has a linking section (i.e. its a relocatable object file). Otherwise
355 // the global might not represent symbols at all.
356 populateSymbolTable();
359 uint8_t Type = readVarint7(Ptr);
360 uint32_t Size = readVaruint32(Ptr);
361 const uint8_t *SubSectionEnd = Ptr + Size;
363 case wasm::WASM_SYMBOL_INFO: {
364 uint32_t Count = readVaruint32(Ptr);
366 StringRef Symbol = readString(Ptr);
367 DEBUG(dbgs() << "reading syminfo: " << Symbol << "\n");
368 uint32_t Flags = readVaruint32(Ptr);
369 auto iter = SymbolMap.find(Symbol);
370 if (iter == SymbolMap.end()) {
371 return make_error<GenericBinaryError>(
372 "Invalid symbol name in linking section: " + Symbol,
373 object_error::parse_failed);
375 uint32_t SymIndex = iter->second;
376 assert(SymIndex < Symbols.size());
377 Symbols[SymIndex].Flags = Flags;
378 DEBUG(dbgs() << "Set symbol flags index:"
379 << SymIndex << " name:"
380 << Symbols[SymIndex].Name << " exptected:"
381 << Symbol << " flags: " << Flags << "\n");
385 case wasm::WASM_DATA_SIZE:
386 LinkingData.DataSize = readVaruint32(Ptr);
388 case wasm::WASM_DATA_ALIGNMENT:
389 LinkingData.DataAlignment = readVaruint32(Ptr);
391 case wasm::WASM_SEGMENT_NAMES: {
392 uint32_t Count = readVaruint32(Ptr);
393 if (Count > DataSegments.size())
394 return make_error<GenericBinaryError>("Too many segment names",
395 object_error::parse_failed);
396 for (uint32_t i = 0; i < Count; i++)
397 DataSegments[i].Data.Name = readString(Ptr);
400 case wasm::WASM_STACK_POINTER:
405 if (Ptr != SubSectionEnd)
406 return make_error<GenericBinaryError>(
407 "Linking sub-section ended prematurely", object_error::parse_failed);
410 return make_error<GenericBinaryError>("Linking section ended prematurely",
411 object_error::parse_failed);
412 return Error::success();
415 WasmSection* WasmObjectFile::findCustomSectionByName(StringRef Name) {
416 for (WasmSection& Section : Sections) {
417 if (Section.Type == wasm::WASM_SEC_CUSTOM && Section.Name == Name)
423 WasmSection* WasmObjectFile::findSectionByType(uint32_t Type) {
424 assert(Type != wasm::WASM_SEC_CUSTOM);
425 for (WasmSection& Section : Sections) {
426 if (Section.Type == Type)
432 Error WasmObjectFile::parseRelocSection(StringRef Name, const uint8_t *Ptr,
433 const uint8_t *End) {
434 uint8_t SectionCode = readVarint7(Ptr);
435 WasmSection* Section = nullptr;
436 if (SectionCode == wasm::WASM_SEC_CUSTOM) {
437 StringRef Name = readString(Ptr);
438 Section = findCustomSectionByName(Name);
440 Section = findSectionByType(SectionCode);
443 return make_error<GenericBinaryError>("Invalid section code",
444 object_error::parse_failed);
445 uint32_t RelocCount = readVaruint32(Ptr);
446 while (RelocCount--) {
447 wasm::WasmRelocation Reloc;
448 memset(&Reloc, 0, sizeof(Reloc));
449 Reloc.Type = readVaruint32(Ptr);
450 Reloc.Offset = readVaruint32(Ptr);
451 Reloc.Index = readVaruint32(Ptr);
452 switch (Reloc.Type) {
453 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
454 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
455 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
456 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
457 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
459 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
460 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
461 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
462 Reloc.Addend = readVarint32(Ptr);
465 return make_error<GenericBinaryError>("Bad relocation type: " +
467 object_error::parse_failed);
469 Section->Relocations.push_back(Reloc);
472 return make_error<GenericBinaryError>("Reloc section ended prematurely",
473 object_error::parse_failed);
474 return Error::success();
477 Error WasmObjectFile::parseCustomSection(WasmSection &Sec,
478 const uint8_t *Ptr, const uint8_t *End) {
479 Sec.Name = readString(Ptr);
480 if (Sec.Name == "name") {
481 if (Error Err = parseNameSection(Ptr, End))
483 } else if (Sec.Name == "linking") {
484 if (Error Err = parseLinkingSection(Ptr, End))
486 } else if (Sec.Name.startswith("reloc.")) {
487 if (Error Err = parseRelocSection(Sec.Name, Ptr, End))
490 return Error::success();
493 Error WasmObjectFile::parseTypeSection(const uint8_t *Ptr, const uint8_t *End) {
494 uint32_t Count = readVaruint32(Ptr);
495 Signatures.reserve(Count);
497 wasm::WasmSignature Sig;
498 Sig.ReturnType = wasm::WASM_TYPE_NORESULT;
499 int8_t Form = readVarint7(Ptr);
500 if (Form != wasm::WASM_TYPE_FUNC) {
501 return make_error<GenericBinaryError>("Invalid signature type",
502 object_error::parse_failed);
504 uint32_t ParamCount = readVaruint32(Ptr);
505 Sig.ParamTypes.reserve(ParamCount);
506 while (ParamCount--) {
507 uint32_t ParamType = readVarint7(Ptr);
508 Sig.ParamTypes.push_back(ParamType);
510 uint32_t ReturnCount = readVaruint32(Ptr);
512 if (ReturnCount != 1) {
513 return make_error<GenericBinaryError>(
514 "Multiple return types not supported", object_error::parse_failed);
516 Sig.ReturnType = readVarint7(Ptr);
518 Signatures.push_back(Sig);
521 return make_error<GenericBinaryError>("Type section ended prematurely",
522 object_error::parse_failed);
523 return Error::success();
526 Error WasmObjectFile::parseImportSection(const uint8_t *Ptr, const uint8_t *End) {
527 ImportSection = Sections.size();
528 uint32_t Count = readVaruint32(Ptr);
529 Imports.reserve(Count);
530 for (uint32_t i = 0; i < Count; i++) {
532 Im.Module = readString(Ptr);
533 Im.Field = readString(Ptr);
534 Im.Kind = readUint8(Ptr);
536 case wasm::WASM_EXTERNAL_FUNCTION:
537 NumImportedFunctions++;
538 Im.SigIndex = readVaruint32(Ptr);
540 case wasm::WASM_EXTERNAL_GLOBAL:
541 NumImportedGlobals++;
542 Im.Global.Type = readVarint7(Ptr);
543 Im.Global.Mutable = readVaruint1(Ptr);
545 case wasm::WASM_EXTERNAL_MEMORY:
546 Im.Memory = readLimits(Ptr);
548 case wasm::WASM_EXTERNAL_TABLE:
549 Im.Table = readTable(Ptr);
550 if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC)
551 return make_error<GenericBinaryError>("Invalid table element type",
552 object_error::parse_failed);
555 return make_error<GenericBinaryError>(
556 "Unexpected import kind", object_error::parse_failed);
558 Imports.push_back(Im);
561 return make_error<GenericBinaryError>("Import section ended prematurely",
562 object_error::parse_failed);
563 return Error::success();
566 Error WasmObjectFile::parseFunctionSection(const uint8_t *Ptr, const uint8_t *End) {
567 uint32_t Count = readVaruint32(Ptr);
568 FunctionTypes.reserve(Count);
570 FunctionTypes.push_back(readVaruint32(Ptr));
573 return make_error<GenericBinaryError>("Function section ended prematurely",
574 object_error::parse_failed);
575 return Error::success();
578 Error WasmObjectFile::parseTableSection(const uint8_t *Ptr, const uint8_t *End) {
579 uint32_t Count = readVaruint32(Ptr);
580 Tables.reserve(Count);
582 Tables.push_back(readTable(Ptr));
583 if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
584 return make_error<GenericBinaryError>("Invalid table element type",
585 object_error::parse_failed);
589 return make_error<GenericBinaryError>("Table section ended prematurely",
590 object_error::parse_failed);
591 return Error::success();
594 Error WasmObjectFile::parseMemorySection(const uint8_t *Ptr, const uint8_t *End) {
595 uint32_t Count = readVaruint32(Ptr);
596 Memories.reserve(Count);
598 Memories.push_back(readLimits(Ptr));
601 return make_error<GenericBinaryError>("Memory section ended prematurely",
602 object_error::parse_failed);
603 return Error::success();
606 Error WasmObjectFile::parseGlobalSection(const uint8_t *Ptr, const uint8_t *End) {
607 uint32_t Count = readVaruint32(Ptr);
608 Globals.reserve(Count);
610 wasm::WasmGlobal Global;
611 Global.Type = readVarint7(Ptr);
612 Global.Mutable = readVaruint1(Ptr);
613 if (Error Err = readInitExpr(Global.InitExpr, Ptr))
615 Globals.push_back(Global);
618 return make_error<GenericBinaryError>("Global section ended prematurely",
619 object_error::parse_failed);
620 return Error::success();
623 Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) {
624 ExportSection = Sections.size();
625 uint32_t Count = readVaruint32(Ptr);
626 Exports.reserve(Count);
627 for (uint32_t i = 0; i < Count; i++) {
629 Ex.Name = readString(Ptr);
630 Ex.Kind = readUint8(Ptr);
631 Ex.Index = readVaruint32(Ptr);
633 case wasm::WASM_EXTERNAL_FUNCTION:
634 if (Ex.Index >= FunctionTypes.size() + NumImportedFunctions)
635 return make_error<GenericBinaryError>("Invalid function export",
636 object_error::parse_failed);
638 case wasm::WASM_EXTERNAL_GLOBAL: {
639 if (Ex.Index >= Globals.size() + NumImportedGlobals)
640 return make_error<GenericBinaryError>("Invalid global export",
641 object_error::parse_failed);
644 case wasm::WASM_EXTERNAL_MEMORY:
645 case wasm::WASM_EXTERNAL_TABLE:
648 return make_error<GenericBinaryError>(
649 "Unexpected export kind", object_error::parse_failed);
651 Exports.push_back(Ex);
654 return make_error<GenericBinaryError>("Export section ended prematurely",
655 object_error::parse_failed);
656 return Error::success();
659 Error WasmObjectFile::parseStartSection(const uint8_t *Ptr, const uint8_t *End) {
660 StartFunction = readVaruint32(Ptr);
661 if (StartFunction >= FunctionTypes.size())
662 return make_error<GenericBinaryError>("Invalid start function",
663 object_error::parse_failed);
664 return Error::success();
667 Error WasmObjectFile::parseCodeSection(const uint8_t *Ptr, const uint8_t *End) {
668 uint32_t FunctionCount = readVaruint32(Ptr);
669 if (FunctionCount != FunctionTypes.size()) {
670 return make_error<GenericBinaryError>("Invalid function count",
671 object_error::parse_failed);
674 CodeSection = ArrayRef<uint8_t>(Ptr, End - Ptr);
676 while (FunctionCount--) {
677 wasm::WasmFunction Function;
678 uint32_t FunctionSize = readVaruint32(Ptr);
679 const uint8_t *FunctionEnd = Ptr + FunctionSize;
681 uint32_t NumLocalDecls = readVaruint32(Ptr);
682 Function.Locals.reserve(NumLocalDecls);
683 while (NumLocalDecls--) {
684 wasm::WasmLocalDecl Decl;
685 Decl.Count = readVaruint32(Ptr);
686 Decl.Type = readVarint7(Ptr);
687 Function.Locals.push_back(Decl);
690 uint32_t BodySize = FunctionEnd - Ptr;
691 Function.Body = ArrayRef<uint8_t>(Ptr, BodySize);
693 assert(Ptr == FunctionEnd);
694 Functions.push_back(Function);
697 return make_error<GenericBinaryError>("Code section ended prematurely",
698 object_error::parse_failed);
699 return Error::success();
702 Error WasmObjectFile::parseElemSection(const uint8_t *Ptr, const uint8_t *End) {
703 uint32_t Count = readVaruint32(Ptr);
704 ElemSegments.reserve(Count);
706 wasm::WasmElemSegment Segment;
707 Segment.TableIndex = readVaruint32(Ptr);
708 if (Segment.TableIndex != 0) {
709 return make_error<GenericBinaryError>("Invalid TableIndex",
710 object_error::parse_failed);
712 if (Error Err = readInitExpr(Segment.Offset, Ptr))
714 uint32_t NumElems = readVaruint32(Ptr);
716 Segment.Functions.push_back(readVaruint32(Ptr));
718 ElemSegments.push_back(Segment);
721 return make_error<GenericBinaryError>("Elem section ended prematurely",
722 object_error::parse_failed);
723 return Error::success();
726 Error WasmObjectFile::parseDataSection(const uint8_t *Ptr, const uint8_t *End) {
727 const uint8_t *Start = Ptr;
728 uint32_t Count = readVaruint32(Ptr);
729 DataSegments.reserve(Count);
732 Segment.Data.MemoryIndex = readVaruint32(Ptr);
733 if (Error Err = readInitExpr(Segment.Data.Offset, Ptr))
735 uint32_t Size = readVaruint32(Ptr);
736 Segment.Data.Content = ArrayRef<uint8_t>(Ptr, Size);
737 Segment.SectionOffset = Ptr - Start;
739 DataSegments.push_back(Segment);
742 return make_error<GenericBinaryError>("Data section ended prematurely",
743 object_error::parse_failed);
744 return Error::success();
747 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
748 return reinterpret_cast<const uint8_t *>(getData().substr(Offset, 1).data());
751 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
755 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
757 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
758 uint32_t Result = SymbolRef::SF_None;
759 const WasmSymbol &Sym = getWasmSymbol(Symb);
761 DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
763 Result |= SymbolRef::SF_Weak;
765 Result |= SymbolRef::SF_Global;
768 case WasmSymbol::SymbolType::FUNCTION_IMPORT:
769 Result |= SymbolRef::SF_Undefined | SymbolRef::SF_Executable;
771 case WasmSymbol::SymbolType::FUNCTION_EXPORT:
772 Result |= SymbolRef::SF_Executable;
774 case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
775 Result |= SymbolRef::SF_Executable;
776 Result |= SymbolRef::SF_FormatSpecific;
778 case WasmSymbol::SymbolType::GLOBAL_IMPORT:
779 Result |= SymbolRef::SF_Undefined;
781 case WasmSymbol::SymbolType::GLOBAL_EXPORT:
788 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
791 return BasicSymbolRef(Ref, this);
794 basic_symbol_iterator WasmObjectFile::symbol_end() const {
796 Ref.d.a = Symbols.size();
797 return BasicSymbolRef(Ref, this);
800 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
801 return Symbols[Symb.d.a];
804 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
805 return getWasmSymbol(Symb.getRawDataRefImpl());
808 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
809 return getWasmSymbol(Symb).Name;
812 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
813 return getSymbolValue(Symb);
816 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol& Sym) const {
818 case WasmSymbol::SymbolType::FUNCTION_IMPORT:
819 case WasmSymbol::SymbolType::GLOBAL_IMPORT:
820 case WasmSymbol::SymbolType::FUNCTION_EXPORT:
821 case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
822 return Sym.ElementIndex;
823 case WasmSymbol::SymbolType::GLOBAL_EXPORT: {
824 uint32_t GlobalIndex = Sym.ElementIndex - NumImportedGlobals;
825 assert(GlobalIndex < Globals.size());
826 const wasm::WasmGlobal& Global = Globals[GlobalIndex];
827 // WasmSymbols correspond only to I32_CONST globals
828 assert(Global.InitExpr.Opcode == wasm::WASM_OPCODE_I32_CONST);
829 return Global.InitExpr.Value.Int32;
832 llvm_unreachable("invalid symbol type");
835 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
836 return getWasmSymbolValue(getWasmSymbol(Symb));
839 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
840 llvm_unreachable("not yet implemented");
844 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
845 llvm_unreachable("not yet implemented");
849 Expected<SymbolRef::Type>
850 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
851 const WasmSymbol &Sym = getWasmSymbol(Symb);
854 case WasmSymbol::SymbolType::FUNCTION_IMPORT:
855 case WasmSymbol::SymbolType::FUNCTION_EXPORT:
856 case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
857 return SymbolRef::ST_Function;
858 case WasmSymbol::SymbolType::GLOBAL_IMPORT:
859 case WasmSymbol::SymbolType::GLOBAL_EXPORT:
860 return SymbolRef::ST_Data;
863 llvm_unreachable("Unknown WasmSymbol::SymbolType");
864 return SymbolRef::ST_Other;
867 Expected<section_iterator>
868 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
870 Ref.d.a = getWasmSymbol(Symb).Section;
871 return section_iterator(SectionRef(Ref, this));
874 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
876 std::error_code WasmObjectFile::getSectionName(DataRefImpl Sec,
877 StringRef &Res) const {
878 const WasmSection &S = Sections[Sec.d.a];
880 case wasm::WASM_SEC_##X: \
895 case wasm::WASM_SEC_CUSTOM:
899 return object_error::invalid_section_index;
902 return std::error_code();
905 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
907 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
911 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
912 const WasmSection &S = Sections[Sec.d.a];
913 return S.Content.size();
916 std::error_code WasmObjectFile::getSectionContents(DataRefImpl Sec,
917 StringRef &Res) const {
918 const WasmSection &S = Sections[Sec.d.a];
919 // This will never fail since wasm sections can never be empty (user-sections
920 // must have a name and non-user sections each have a defined structure).
921 Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
923 return std::error_code();
926 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
930 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
934 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
935 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
938 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
939 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
942 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
944 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
946 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
948 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
949 DataRefImpl RelocRef;
950 RelocRef.d.a = Ref.d.a;
952 return relocation_iterator(RelocationRef(RelocRef, this));
955 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
956 const WasmSection &Sec = getWasmSection(Ref);
957 DataRefImpl RelocRef;
958 RelocRef.d.a = Ref.d.a;
959 RelocRef.d.b = Sec.Relocations.size();
960 return relocation_iterator(RelocationRef(RelocRef, this));
963 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
967 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
968 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
972 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
973 llvm_unreachable("not yet implemented");
975 return symbol_iterator(Ref);
978 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
979 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
983 void WasmObjectFile::getRelocationTypeName(
984 DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
985 const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
986 StringRef Res = "Unknown";
988 #define WASM_RELOC(name, value) \
994 #include "llvm/BinaryFormat/WasmRelocs/WebAssembly.def"
999 Result.append(Res.begin(), Res.end());
1002 section_iterator WasmObjectFile::section_begin() const {
1005 return section_iterator(SectionRef(Ref, this));
1008 section_iterator WasmObjectFile::section_end() const {
1010 Ref.d.a = Sections.size();
1011 return section_iterator(SectionRef(Ref, this));
1014 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1016 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1018 unsigned WasmObjectFile::getArch() const { return Triple::wasm32; }
1020 SubtargetFeatures WasmObjectFile::getFeatures() const {
1021 return SubtargetFeatures();
1024 bool WasmObjectFile::isRelocatableObject() const {
1025 return HasLinkingSection;
1028 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1029 assert(Ref.d.a < Sections.size());
1030 return Sections[Ref.d.a];
1034 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1035 return getWasmSection(Section.getRawDataRefImpl());
1038 const wasm::WasmRelocation &
1039 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1040 return getWasmRelocation(Ref.getRawDataRefImpl());
1043 const wasm::WasmRelocation &
1044 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1045 assert(Ref.d.a < Sections.size());
1046 const WasmSection& Sec = Sections[Ref.d.a];
1047 assert(Ref.d.b < Sec.Relocations.size());
1048 return Sec.Relocations[Ref.d.b];