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, const uint8_t *Eof) {
182 Section.Offset = Ptr - Start;
183 Section.Type = readVaruint7(Ptr);
184 uint32_t Size = readVaruint32(Ptr);
186 return make_error<StringError>("Zero length section",
187 object_error::parse_failed);
188 if (Ptr + Size > Eof)
189 return make_error<StringError>("Section too large",
190 object_error::parse_failed);
191 Section.Content = ArrayRef<uint8_t>(Ptr, Size);
193 return Error::success();
196 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
197 : ObjectFile(Binary::ID_Wasm, Buffer) {
198 LinkingData.DataSize = 0;
200 ErrorAsOutParameter ErrAsOutParam(&Err);
201 Header.Magic = getData().substr(0, 4);
202 if (Header.Magic != StringRef("\0asm", 4)) {
203 Err = make_error<StringError>("Bad magic number",
204 object_error::parse_failed);
208 const uint8_t *Eof = getPtr(getData().size());
209 const uint8_t *Ptr = getPtr(4);
212 Err = make_error<StringError>("Missing version number",
213 object_error::parse_failed);
217 Header.Version = readUint32(Ptr);
218 if (Header.Version != wasm::WasmVersion) {
219 Err = make_error<StringError>("Bad version number",
220 object_error::parse_failed);
226 if ((Err = readSection(Sec, Ptr, getPtr(0), Eof)))
228 if ((Err = parseSection(Sec)))
231 Sections.push_back(Sec);
235 Error WasmObjectFile::parseSection(WasmSection &Sec) {
236 const uint8_t* Start = Sec.Content.data();
237 const uint8_t* End = Start + Sec.Content.size();
239 case wasm::WASM_SEC_CUSTOM:
240 return parseCustomSection(Sec, Start, End);
241 case wasm::WASM_SEC_TYPE:
242 return parseTypeSection(Start, End);
243 case wasm::WASM_SEC_IMPORT:
244 return parseImportSection(Start, End);
245 case wasm::WASM_SEC_FUNCTION:
246 return parseFunctionSection(Start, End);
247 case wasm::WASM_SEC_TABLE:
248 return parseTableSection(Start, End);
249 case wasm::WASM_SEC_MEMORY:
250 return parseMemorySection(Start, End);
251 case wasm::WASM_SEC_GLOBAL:
252 return parseGlobalSection(Start, End);
253 case wasm::WASM_SEC_EXPORT:
254 return parseExportSection(Start, End);
255 case wasm::WASM_SEC_START:
256 return parseStartSection(Start, End);
257 case wasm::WASM_SEC_ELEM:
258 return parseElemSection(Start, End);
259 case wasm::WASM_SEC_CODE:
260 return parseCodeSection(Start, End);
261 case wasm::WASM_SEC_DATA:
262 return parseDataSection(Start, End);
264 return make_error<GenericBinaryError>("Bad section type",
265 object_error::parse_failed);
269 Error WasmObjectFile::parseNameSection(const uint8_t *Ptr, const uint8_t *End) {
271 uint8_t Type = readVarint7(Ptr);
272 uint32_t Size = readVaruint32(Ptr);
273 const uint8_t *SubSectionEnd = Ptr + Size;
275 case wasm::WASM_NAMES_FUNCTION: {
276 uint32_t Count = readVaruint32(Ptr);
278 uint32_t Index = readVaruint32(Ptr);
279 StringRef Name = readString(Ptr);
281 Symbols.emplace_back(Name,
282 WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME,
283 Sections.size(), Index);
287 // Ignore local names for now
288 case wasm::WASM_NAMES_LOCAL:
293 if (Ptr != SubSectionEnd)
294 return make_error<GenericBinaryError>("Name sub-section ended prematurely",
295 object_error::parse_failed);
299 return make_error<GenericBinaryError>("Name section ended prematurely",
300 object_error::parse_failed);
301 return Error::success();
304 void WasmObjectFile::populateSymbolTable() {
305 // Add imports to symbol table
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++);
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++, Import.SigIndex);
323 DEBUG(dbgs() << "Adding import: " << Symbols.back()
324 << " sym index:" << Symbols.size() << "\n");
331 // Add exports to symbol table
332 for (const wasm::WasmExport& Export : Exports) {
333 if (Export.Kind == wasm::WASM_EXTERNAL_FUNCTION ||
334 Export.Kind == wasm::WASM_EXTERNAL_GLOBAL) {
335 WasmSymbol::SymbolType ExportType =
336 Export.Kind == wasm::WASM_EXTERNAL_FUNCTION
337 ? WasmSymbol::SymbolType::FUNCTION_EXPORT
338 : WasmSymbol::SymbolType::GLOBAL_EXPORT;
339 auto Pair = 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");
346 uint32_t SymIndex = Pair.first->second;
347 const WasmSymbol &OldSym = Symbols[SymIndex];
348 WasmSymbol NewSym(Export.Name, ExportType, ExportSection, Export.Index);
349 NewSym.setAltIndex(OldSym.ElementIndex);
350 Symbols[SymIndex] = NewSym;
352 DEBUG(dbgs() << "Replacing existing symbol: " << NewSym
353 << " sym index:" << SymIndex << "\n");
359 Error WasmObjectFile::parseLinkingSection(const uint8_t *Ptr,
360 const uint8_t *End) {
361 HasLinkingSection = true;
363 // Only populate the symbol table with imports and exports if the object
364 // has a linking section (i.e. its a relocatable object file). Otherwise
365 // the global might not represent symbols at all.
366 populateSymbolTable();
369 uint8_t Type = readVarint7(Ptr);
370 uint32_t Size = readVaruint32(Ptr);
371 const uint8_t *SubSectionEnd = Ptr + Size;
373 case wasm::WASM_SYMBOL_INFO: {
374 uint32_t Count = readVaruint32(Ptr);
376 StringRef Symbol = readString(Ptr);
377 DEBUG(dbgs() << "reading syminfo: " << Symbol << "\n");
378 uint32_t Flags = readVaruint32(Ptr);
379 auto iter = SymbolMap.find(Symbol);
380 if (iter == SymbolMap.end()) {
381 return make_error<GenericBinaryError>(
382 "Invalid symbol name in linking section: " + Symbol,
383 object_error::parse_failed);
385 uint32_t SymIndex = iter->second;
386 assert(SymIndex < Symbols.size());
387 Symbols[SymIndex].Flags = Flags;
388 DEBUG(dbgs() << "Set symbol flags index:"
389 << SymIndex << " name:"
390 << Symbols[SymIndex].Name << " expected:"
391 << Symbol << " flags: " << Flags << "\n");
395 case wasm::WASM_DATA_SIZE:
396 LinkingData.DataSize = readVaruint32(Ptr);
398 case wasm::WASM_SEGMENT_INFO: {
399 uint32_t Count = readVaruint32(Ptr);
400 if (Count > DataSegments.size())
401 return make_error<GenericBinaryError>("Too many segment names",
402 object_error::parse_failed);
403 for (uint32_t i = 0; i < Count; i++) {
404 DataSegments[i].Data.Name = readString(Ptr);
405 DataSegments[i].Data.Alignment = readVaruint32(Ptr);
406 DataSegments[i].Data.Flags = readVaruint32(Ptr);
410 case wasm::WASM_INIT_FUNCS: {
411 uint32_t Count = readVaruint32(Ptr);
412 LinkingData.InitFunctions.reserve(Count);
413 for (uint32_t i = 0; i < Count; i++) {
414 wasm::WasmInitFunc Init;
415 Init.Priority = readVaruint32(Ptr);
416 Init.FunctionIndex = readVaruint32(Ptr);
417 if (!isValidFunctionIndex(Init.FunctionIndex))
418 return make_error<GenericBinaryError>("Invalid function index: " +
419 Twine(Init.FunctionIndex),
420 object_error::parse_failed);
421 LinkingData.InitFunctions.emplace_back(Init);
429 if (Ptr != SubSectionEnd)
430 return make_error<GenericBinaryError>(
431 "Linking sub-section ended prematurely", object_error::parse_failed);
434 return make_error<GenericBinaryError>("Linking section ended prematurely",
435 object_error::parse_failed);
436 return Error::success();
439 WasmSection* WasmObjectFile::findCustomSectionByName(StringRef Name) {
440 for (WasmSection& Section : Sections) {
441 if (Section.Type == wasm::WASM_SEC_CUSTOM && Section.Name == Name)
447 WasmSection* WasmObjectFile::findSectionByType(uint32_t Type) {
448 assert(Type != wasm::WASM_SEC_CUSTOM);
449 for (WasmSection& Section : Sections) {
450 if (Section.Type == Type)
456 Error WasmObjectFile::parseRelocSection(StringRef Name, const uint8_t *Ptr,
457 const uint8_t *End) {
458 uint8_t SectionCode = readVarint7(Ptr);
459 WasmSection* Section = nullptr;
460 if (SectionCode == wasm::WASM_SEC_CUSTOM) {
461 StringRef Name = readString(Ptr);
462 Section = findCustomSectionByName(Name);
464 Section = findSectionByType(SectionCode);
467 return make_error<GenericBinaryError>("Invalid section code",
468 object_error::parse_failed);
469 uint32_t RelocCount = readVaruint32(Ptr);
470 while (RelocCount--) {
471 wasm::WasmRelocation Reloc;
472 memset(&Reloc, 0, sizeof(Reloc));
473 Reloc.Type = readVaruint32(Ptr);
474 Reloc.Offset = readVaruint32(Ptr);
475 Reloc.Index = readVaruint32(Ptr);
476 switch (Reloc.Type) {
477 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
478 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
479 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
480 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
481 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
483 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
484 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
485 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
486 Reloc.Addend = readVarint32(Ptr);
489 return make_error<GenericBinaryError>("Bad relocation type: " +
491 object_error::parse_failed);
493 Section->Relocations.push_back(Reloc);
496 return make_error<GenericBinaryError>("Reloc section ended prematurely",
497 object_error::parse_failed);
498 return Error::success();
501 Error WasmObjectFile::parseCustomSection(WasmSection &Sec,
502 const uint8_t *Ptr, const uint8_t *End) {
503 Sec.Name = readString(Ptr);
504 if (Sec.Name == "name") {
505 if (Error Err = parseNameSection(Ptr, End))
507 } else if (Sec.Name == "linking") {
508 if (Error Err = parseLinkingSection(Ptr, End))
510 } else if (Sec.Name.startswith("reloc.")) {
511 if (Error Err = parseRelocSection(Sec.Name, Ptr, End))
514 return Error::success();
517 Error WasmObjectFile::parseTypeSection(const uint8_t *Ptr, const uint8_t *End) {
518 uint32_t Count = readVaruint32(Ptr);
519 Signatures.reserve(Count);
521 wasm::WasmSignature Sig;
522 Sig.ReturnType = wasm::WASM_TYPE_NORESULT;
523 int8_t Form = readVarint7(Ptr);
524 if (Form != wasm::WASM_TYPE_FUNC) {
525 return make_error<GenericBinaryError>("Invalid signature type",
526 object_error::parse_failed);
528 uint32_t ParamCount = readVaruint32(Ptr);
529 Sig.ParamTypes.reserve(ParamCount);
530 while (ParamCount--) {
531 uint32_t ParamType = readVarint7(Ptr);
532 Sig.ParamTypes.push_back(ParamType);
534 uint32_t ReturnCount = readVaruint32(Ptr);
536 if (ReturnCount != 1) {
537 return make_error<GenericBinaryError>(
538 "Multiple return types not supported", object_error::parse_failed);
540 Sig.ReturnType = readVarint7(Ptr);
542 Signatures.push_back(Sig);
545 return make_error<GenericBinaryError>("Type section ended prematurely",
546 object_error::parse_failed);
547 return Error::success();
550 Error WasmObjectFile::parseImportSection(const uint8_t *Ptr, const uint8_t *End) {
551 ImportSection = Sections.size();
552 uint32_t Count = readVaruint32(Ptr);
553 Imports.reserve(Count);
554 for (uint32_t i = 0; i < Count; i++) {
556 Im.Module = readString(Ptr);
557 Im.Field = readString(Ptr);
558 Im.Kind = readUint8(Ptr);
560 case wasm::WASM_EXTERNAL_FUNCTION:
561 NumImportedFunctions++;
562 Im.SigIndex = readVaruint32(Ptr);
564 case wasm::WASM_EXTERNAL_GLOBAL:
565 NumImportedGlobals++;
566 Im.Global.Type = readVarint7(Ptr);
567 Im.Global.Mutable = readVaruint1(Ptr);
569 case wasm::WASM_EXTERNAL_MEMORY:
570 Im.Memory = readLimits(Ptr);
572 case wasm::WASM_EXTERNAL_TABLE:
573 Im.Table = readTable(Ptr);
574 if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC)
575 return make_error<GenericBinaryError>("Invalid table element type",
576 object_error::parse_failed);
579 return make_error<GenericBinaryError>(
580 "Unexpected import kind", object_error::parse_failed);
582 Imports.push_back(Im);
585 return make_error<GenericBinaryError>("Import section ended prematurely",
586 object_error::parse_failed);
587 return Error::success();
590 Error WasmObjectFile::parseFunctionSection(const uint8_t *Ptr, const uint8_t *End) {
591 uint32_t Count = readVaruint32(Ptr);
592 FunctionTypes.reserve(Count);
594 FunctionTypes.push_back(readVaruint32(Ptr));
597 return make_error<GenericBinaryError>("Function section ended prematurely",
598 object_error::parse_failed);
599 return Error::success();
602 Error WasmObjectFile::parseTableSection(const uint8_t *Ptr, const uint8_t *End) {
603 uint32_t Count = readVaruint32(Ptr);
604 Tables.reserve(Count);
606 Tables.push_back(readTable(Ptr));
607 if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
608 return make_error<GenericBinaryError>("Invalid table element type",
609 object_error::parse_failed);
613 return make_error<GenericBinaryError>("Table section ended prematurely",
614 object_error::parse_failed);
615 return Error::success();
618 Error WasmObjectFile::parseMemorySection(const uint8_t *Ptr, const uint8_t *End) {
619 uint32_t Count = readVaruint32(Ptr);
620 Memories.reserve(Count);
622 Memories.push_back(readLimits(Ptr));
625 return make_error<GenericBinaryError>("Memory section ended prematurely",
626 object_error::parse_failed);
627 return Error::success();
630 Error WasmObjectFile::parseGlobalSection(const uint8_t *Ptr, const uint8_t *End) {
631 uint32_t Count = readVaruint32(Ptr);
632 Globals.reserve(Count);
634 wasm::WasmGlobal Global;
635 Global.Type = readVarint7(Ptr);
636 Global.Mutable = readVaruint1(Ptr);
637 if (Error Err = readInitExpr(Global.InitExpr, Ptr))
639 Globals.push_back(Global);
642 return make_error<GenericBinaryError>("Global section ended prematurely",
643 object_error::parse_failed);
644 return Error::success();
647 Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) {
648 ExportSection = Sections.size();
649 uint32_t Count = readVaruint32(Ptr);
650 Exports.reserve(Count);
651 for (uint32_t i = 0; i < Count; i++) {
653 Ex.Name = readString(Ptr);
654 Ex.Kind = readUint8(Ptr);
655 Ex.Index = readVaruint32(Ptr);
657 case wasm::WASM_EXTERNAL_FUNCTION:
658 if (Ex.Index >= FunctionTypes.size() + NumImportedFunctions)
659 return make_error<GenericBinaryError>("Invalid function export",
660 object_error::parse_failed);
662 case wasm::WASM_EXTERNAL_GLOBAL: {
663 if (Ex.Index >= Globals.size() + NumImportedGlobals)
664 return make_error<GenericBinaryError>("Invalid global export",
665 object_error::parse_failed);
668 case wasm::WASM_EXTERNAL_MEMORY:
669 case wasm::WASM_EXTERNAL_TABLE:
672 return make_error<GenericBinaryError>(
673 "Unexpected export kind", object_error::parse_failed);
675 Exports.push_back(Ex);
678 return make_error<GenericBinaryError>("Export section ended prematurely",
679 object_error::parse_failed);
680 return Error::success();
683 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
684 return Index < FunctionTypes.size() + NumImportedFunctions;
687 Error WasmObjectFile::parseStartSection(const uint8_t *Ptr, const uint8_t *End) {
688 StartFunction = readVaruint32(Ptr);
689 if (!isValidFunctionIndex(StartFunction))
690 return make_error<GenericBinaryError>("Invalid start function",
691 object_error::parse_failed);
692 return Error::success();
695 Error WasmObjectFile::parseCodeSection(const uint8_t *Ptr, const uint8_t *End) {
696 const uint8_t *CodeSectionStart = Ptr;
697 uint32_t FunctionCount = readVaruint32(Ptr);
698 if (FunctionCount != FunctionTypes.size()) {
699 return make_error<GenericBinaryError>("Invalid function count",
700 object_error::parse_failed);
703 while (FunctionCount--) {
704 wasm::WasmFunction Function;
705 const uint8_t *FunctionStart = Ptr;
706 uint32_t Size = readVaruint32(Ptr);
707 const uint8_t *FunctionEnd = Ptr + Size;
709 Function.CodeSectionOffset = FunctionStart - CodeSectionStart;
710 Function.Size = FunctionEnd - FunctionStart;
712 uint32_t NumLocalDecls = readVaruint32(Ptr);
713 Function.Locals.reserve(NumLocalDecls);
714 while (NumLocalDecls--) {
715 wasm::WasmLocalDecl Decl;
716 Decl.Count = readVaruint32(Ptr);
717 Decl.Type = readVarint7(Ptr);
718 Function.Locals.push_back(Decl);
721 uint32_t BodySize = FunctionEnd - Ptr;
722 Function.Body = ArrayRef<uint8_t>(Ptr, BodySize);
724 assert(Ptr == FunctionEnd);
725 Functions.push_back(Function);
728 return make_error<GenericBinaryError>("Code section ended prematurely",
729 object_error::parse_failed);
730 return Error::success();
733 Error WasmObjectFile::parseElemSection(const uint8_t *Ptr, const uint8_t *End) {
734 uint32_t Count = readVaruint32(Ptr);
735 ElemSegments.reserve(Count);
737 wasm::WasmElemSegment Segment;
738 Segment.TableIndex = readVaruint32(Ptr);
739 if (Segment.TableIndex != 0) {
740 return make_error<GenericBinaryError>("Invalid TableIndex",
741 object_error::parse_failed);
743 if (Error Err = readInitExpr(Segment.Offset, Ptr))
745 uint32_t NumElems = readVaruint32(Ptr);
747 Segment.Functions.push_back(readVaruint32(Ptr));
749 ElemSegments.push_back(Segment);
752 return make_error<GenericBinaryError>("Elem section ended prematurely",
753 object_error::parse_failed);
754 return Error::success();
757 Error WasmObjectFile::parseDataSection(const uint8_t *Ptr, const uint8_t *End) {
758 const uint8_t *Start = Ptr;
759 uint32_t Count = readVaruint32(Ptr);
760 DataSegments.reserve(Count);
763 Segment.Data.MemoryIndex = readVaruint32(Ptr);
764 if (Error Err = readInitExpr(Segment.Data.Offset, Ptr))
766 uint32_t Size = readVaruint32(Ptr);
767 Segment.Data.Content = ArrayRef<uint8_t>(Ptr, Size);
768 Segment.Data.Alignment = 0;
769 Segment.Data.Flags = 0;
770 Segment.SectionOffset = Ptr - Start;
772 DataSegments.push_back(Segment);
775 return make_error<GenericBinaryError>("Data section ended prematurely",
776 object_error::parse_failed);
777 return Error::success();
780 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
781 return reinterpret_cast<const uint8_t *>(getData().substr(Offset, 1).data());
784 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
788 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
790 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
791 uint32_t Result = SymbolRef::SF_None;
792 const WasmSymbol &Sym = getWasmSymbol(Symb);
794 DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
796 Result |= SymbolRef::SF_Weak;
798 Result |= SymbolRef::SF_Global;
800 Result |= SymbolRef::SF_Hidden;
803 case WasmSymbol::SymbolType::FUNCTION_IMPORT:
804 Result |= SymbolRef::SF_Undefined | SymbolRef::SF_Executable;
806 case WasmSymbol::SymbolType::FUNCTION_EXPORT:
807 Result |= SymbolRef::SF_Executable;
809 case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
810 Result |= SymbolRef::SF_Executable;
811 Result |= SymbolRef::SF_FormatSpecific;
813 case WasmSymbol::SymbolType::GLOBAL_IMPORT:
814 Result |= SymbolRef::SF_Undefined;
816 case WasmSymbol::SymbolType::GLOBAL_EXPORT:
823 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
826 return BasicSymbolRef(Ref, this);
829 basic_symbol_iterator WasmObjectFile::symbol_end() const {
831 Ref.d.a = Symbols.size();
832 return BasicSymbolRef(Ref, this);
835 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
836 return Symbols[Symb.d.a];
839 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
840 return getWasmSymbol(Symb.getRawDataRefImpl());
843 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
844 return getWasmSymbol(Symb).Name;
847 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
848 return getSymbolValue(Symb);
851 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol& Sym) const {
853 case WasmSymbol::SymbolType::FUNCTION_IMPORT:
854 case WasmSymbol::SymbolType::GLOBAL_IMPORT:
855 case WasmSymbol::SymbolType::FUNCTION_EXPORT:
856 case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
857 return Sym.ElementIndex;
858 case WasmSymbol::SymbolType::GLOBAL_EXPORT: {
859 uint32_t GlobalIndex = Sym.ElementIndex - NumImportedGlobals;
860 assert(GlobalIndex < Globals.size());
861 const wasm::WasmGlobal& Global = Globals[GlobalIndex];
862 // WasmSymbols correspond only to I32_CONST globals
863 assert(Global.InitExpr.Opcode == wasm::WASM_OPCODE_I32_CONST);
864 return Global.InitExpr.Value.Int32;
867 llvm_unreachable("invalid symbol type");
870 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
871 return getWasmSymbolValue(getWasmSymbol(Symb));
874 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
875 llvm_unreachable("not yet implemented");
879 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
880 llvm_unreachable("not yet implemented");
884 Expected<SymbolRef::Type>
885 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
886 const WasmSymbol &Sym = getWasmSymbol(Symb);
889 case WasmSymbol::SymbolType::FUNCTION_IMPORT:
890 case WasmSymbol::SymbolType::FUNCTION_EXPORT:
891 case WasmSymbol::SymbolType::DEBUG_FUNCTION_NAME:
892 return SymbolRef::ST_Function;
893 case WasmSymbol::SymbolType::GLOBAL_IMPORT:
894 case WasmSymbol::SymbolType::GLOBAL_EXPORT:
895 return SymbolRef::ST_Data;
898 llvm_unreachable("Unknown WasmSymbol::SymbolType");
899 return SymbolRef::ST_Other;
902 Expected<section_iterator>
903 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
905 Ref.d.a = getWasmSymbol(Symb).Section;
906 return section_iterator(SectionRef(Ref, this));
909 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
911 std::error_code WasmObjectFile::getSectionName(DataRefImpl Sec,
912 StringRef &Res) const {
913 const WasmSection &S = Sections[Sec.d.a];
915 case wasm::WASM_SEC_##X: \
930 case wasm::WASM_SEC_CUSTOM:
934 return object_error::invalid_section_index;
937 return std::error_code();
940 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
942 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
946 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
947 const WasmSection &S = Sections[Sec.d.a];
948 return S.Content.size();
951 std::error_code WasmObjectFile::getSectionContents(DataRefImpl Sec,
952 StringRef &Res) const {
953 const WasmSection &S = Sections[Sec.d.a];
954 // This will never fail since wasm sections can never be empty (user-sections
955 // must have a name and non-user sections each have a defined structure).
956 Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
958 return std::error_code();
961 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
965 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
969 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
970 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
973 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
974 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
977 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
979 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
981 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
983 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
984 DataRefImpl RelocRef;
985 RelocRef.d.a = Ref.d.a;
987 return relocation_iterator(RelocationRef(RelocRef, this));
990 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
991 const WasmSection &Sec = getWasmSection(Ref);
992 DataRefImpl RelocRef;
993 RelocRef.d.a = Ref.d.a;
994 RelocRef.d.b = Sec.Relocations.size();
995 return relocation_iterator(RelocationRef(RelocRef, this));
998 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1002 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1003 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1007 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1008 llvm_unreachable("not yet implemented");
1010 return symbol_iterator(Ref);
1013 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1014 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1018 void WasmObjectFile::getRelocationTypeName(
1019 DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1020 const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
1021 StringRef Res = "Unknown";
1023 #define WASM_RELOC(name, value) \
1029 #include "llvm/BinaryFormat/WasmRelocs/WebAssembly.def"
1034 Result.append(Res.begin(), Res.end());
1037 section_iterator WasmObjectFile::section_begin() const {
1040 return section_iterator(SectionRef(Ref, this));
1043 section_iterator WasmObjectFile::section_end() const {
1045 Ref.d.a = Sections.size();
1046 return section_iterator(SectionRef(Ref, this));
1049 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1051 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1053 Triple::ArchType WasmObjectFile::getArch() const { return Triple::wasm32; }
1055 SubtargetFeatures WasmObjectFile::getFeatures() const {
1056 return SubtargetFeatures();
1059 bool WasmObjectFile::isRelocatableObject() const {
1060 return HasLinkingSection;
1063 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1064 assert(Ref.d.a < Sections.size());
1065 return Sections[Ref.d.a];
1069 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1070 return getWasmSection(Section.getRawDataRefImpl());
1073 const wasm::WasmRelocation &
1074 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1075 return getWasmRelocation(Ref.getRawDataRefImpl());
1078 const wasm::WasmRelocation &
1079 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1080 assert(Ref.d.a < Sections.size());
1081 const WasmSection& Sec = Sections[Ref.d.a];
1082 assert(Ref.d.b < Sec.Relocations.size());
1083 return Sec.Relocations[Ref.d.b];