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/DenseSet.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/StringSet.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/BinaryFormat/Wasm.h"
17 #include "llvm/MC/SubtargetFeature.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/Object/Error.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Object/SymbolicFile.h"
22 #include "llvm/Object/Wasm.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/LEB128.h"
31 #include <system_error>
33 #define DEBUG_TYPE "wasm-object"
36 using namespace object;
38 void WasmSymbol::print(raw_ostream &Out) const {
39 Out << "Name=" << Info.Name
40 << ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind))
41 << ", Flags=" << Info.Flags;
43 Out << ", ElemIndex=" << Info.ElementIndex;
44 } else if (isDefined()) {
45 Out << ", Segment=" << Info.DataRef.Segment;
46 Out << ", Offset=" << Info.DataRef.Offset;
47 Out << ", Size=" << Info.DataRef.Size;
51 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52 LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); }
55 Expected<std::unique_ptr<WasmObjectFile>>
56 ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {
57 Error Err = Error::success();
58 auto ObjectFile = llvm::make_unique<WasmObjectFile>(Buffer, Err);
60 return std::move(Err);
62 return std::move(ObjectFile);
65 #define VARINT7_MAX ((1<<7)-1)
66 #define VARINT7_MIN (-(1<<7))
67 #define VARUINT7_MAX (1<<7)
68 #define VARUINT1_MAX (1)
70 static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) {
71 if (Ctx.Ptr == Ctx.End)
72 report_fatal_error("EOF while reading uint8");
76 static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) {
77 if (Ctx.Ptr + 4 > Ctx.End)
78 report_fatal_error("EOF while reading uint32");
79 uint32_t Result = support::endian::read32le(Ctx.Ptr);
84 static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) {
86 memcpy(&Result, Ctx.Ptr, sizeof(Result));
87 Ctx.Ptr += sizeof(Result);
91 static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) {
93 memcpy(&Result, Ctx.Ptr, sizeof(Result));
94 Ctx.Ptr += sizeof(Result);
98 static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) {
100 const char* Error = nullptr;
101 uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
103 report_fatal_error(Error);
108 static StringRef readString(WasmObjectFile::ReadContext &Ctx) {
109 uint32_t StringLen = readULEB128(Ctx);
110 if (Ctx.Ptr + StringLen > Ctx.End)
111 report_fatal_error("EOF while reading string");
113 StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen);
114 Ctx.Ptr += StringLen;
118 static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) {
120 const char* Error = nullptr;
121 uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error);
123 report_fatal_error(Error);
128 static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) {
129 int64_t result = readLEB128(Ctx);
130 if (result > VARUINT1_MAX || result < 0)
131 report_fatal_error("LEB is outside Varuint1 range");
135 static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) {
136 int64_t result = readLEB128(Ctx);
137 if (result > INT32_MAX || result < INT32_MIN)
138 report_fatal_error("LEB is outside Varint32 range");
142 static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) {
143 uint64_t result = readULEB128(Ctx);
144 if (result > UINT32_MAX)
145 report_fatal_error("LEB is outside Varuint32 range");
149 static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) {
150 return readLEB128(Ctx);
153 static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) {
154 return readUint8(Ctx);
157 static Error readInitExpr(wasm::WasmInitExpr &Expr,
158 WasmObjectFile::ReadContext &Ctx) {
159 Expr.Opcode = readOpcode(Ctx);
161 switch (Expr.Opcode) {
162 case wasm::WASM_OPCODE_I32_CONST:
163 Expr.Value.Int32 = readVarint32(Ctx);
165 case wasm::WASM_OPCODE_I64_CONST:
166 Expr.Value.Int64 = readVarint64(Ctx);
168 case wasm::WASM_OPCODE_F32_CONST:
169 Expr.Value.Float32 = readFloat32(Ctx);
171 case wasm::WASM_OPCODE_F64_CONST:
172 Expr.Value.Float64 = readFloat64(Ctx);
174 case wasm::WASM_OPCODE_GET_GLOBAL:
175 Expr.Value.Global = readULEB128(Ctx);
178 return make_error<GenericBinaryError>("Invalid opcode in init_expr",
179 object_error::parse_failed);
182 uint8_t EndOpcode = readOpcode(Ctx);
183 if (EndOpcode != wasm::WASM_OPCODE_END) {
184 return make_error<GenericBinaryError>("Invalid init_expr",
185 object_error::parse_failed);
187 return Error::success();
190 static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) {
191 wasm::WasmLimits Result;
192 Result.Flags = readVaruint1(Ctx);
193 Result.Initial = readVaruint32(Ctx);
194 if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
195 Result.Maximum = readVaruint32(Ctx);
199 static wasm::WasmTable readTable(WasmObjectFile::ReadContext &Ctx) {
200 wasm::WasmTable Table;
201 Table.ElemType = readUint8(Ctx);
202 Table.Limits = readLimits(Ctx);
206 static Error readSection(WasmSection &Section,
207 WasmObjectFile::ReadContext &Ctx) {
208 Section.Offset = Ctx.Ptr - Ctx.Start;
209 Section.Type = readUint8(Ctx);
210 DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");
211 uint32_t Size = readVaruint32(Ctx);
213 return make_error<StringError>("Zero length section",
214 object_error::parse_failed);
215 if (Ctx.Ptr + Size > Ctx.End)
216 return make_error<StringError>("Section too large",
217 object_error::parse_failed);
218 if (Section.Type == wasm::WASM_SEC_CUSTOM) {
219 const uint8_t *NameStart = Ctx.Ptr;
220 Section.Name = readString(Ctx);
221 Size -= Ctx.Ptr - NameStart;
223 Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
225 return Error::success();
228 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)
229 : ObjectFile(Binary::ID_Wasm, Buffer) {
230 ErrorAsOutParameter ErrAsOutParam(&Err);
231 Header.Magic = getData().substr(0, 4);
232 if (Header.Magic != StringRef("\0asm", 4)) {
233 Err = make_error<StringError>("Bad magic number",
234 object_error::parse_failed);
239 Ctx.Start = getPtr(0);
240 Ctx.Ptr = Ctx.Start + 4;
241 Ctx.End = Ctx.Start + getData().size();
243 if (Ctx.Ptr + 4 > Ctx.End) {
244 Err = make_error<StringError>("Missing version number",
245 object_error::parse_failed);
249 Header.Version = readUint32(Ctx);
250 if (Header.Version != wasm::WasmVersion) {
251 Err = make_error<StringError>("Bad version number",
252 object_error::parse_failed);
257 while (Ctx.Ptr < Ctx.End) {
258 if ((Err = readSection(Sec, Ctx)))
260 if ((Err = parseSection(Sec)))
263 Sections.push_back(Sec);
267 Error WasmObjectFile::parseSection(WasmSection &Sec) {
269 Ctx.Start = Sec.Content.data();
270 Ctx.End = Ctx.Start + Sec.Content.size();
273 case wasm::WASM_SEC_CUSTOM:
274 return parseCustomSection(Sec, Ctx);
275 case wasm::WASM_SEC_TYPE:
276 return parseTypeSection(Ctx);
277 case wasm::WASM_SEC_IMPORT:
278 return parseImportSection(Ctx);
279 case wasm::WASM_SEC_FUNCTION:
280 return parseFunctionSection(Ctx);
281 case wasm::WASM_SEC_TABLE:
282 return parseTableSection(Ctx);
283 case wasm::WASM_SEC_MEMORY:
284 return parseMemorySection(Ctx);
285 case wasm::WASM_SEC_GLOBAL:
286 return parseGlobalSection(Ctx);
287 case wasm::WASM_SEC_EXPORT:
288 return parseExportSection(Ctx);
289 case wasm::WASM_SEC_START:
290 return parseStartSection(Ctx);
291 case wasm::WASM_SEC_ELEM:
292 return parseElemSection(Ctx);
293 case wasm::WASM_SEC_CODE:
294 return parseCodeSection(Ctx);
295 case wasm::WASM_SEC_DATA:
296 return parseDataSection(Ctx);
298 return make_error<GenericBinaryError>("Bad section type",
299 object_error::parse_failed);
303 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {
304 llvm::DenseSet<uint64_t> Seen;
305 if (Functions.size() != FunctionTypes.size()) {
306 return make_error<GenericBinaryError>("Names must come after code section",
307 object_error::parse_failed);
310 while (Ctx.Ptr < Ctx.End) {
311 uint8_t Type = readUint8(Ctx);
312 uint32_t Size = readVaruint32(Ctx);
313 const uint8_t *SubSectionEnd = Ctx.Ptr + Size;
315 case wasm::WASM_NAMES_FUNCTION: {
316 uint32_t Count = readVaruint32(Ctx);
318 uint32_t Index = readVaruint32(Ctx);
319 if (!Seen.insert(Index).second)
320 return make_error<GenericBinaryError>("Function named more than once",
321 object_error::parse_failed);
322 StringRef Name = readString(Ctx);
323 if (!isValidFunctionIndex(Index) || Name.empty())
324 return make_error<GenericBinaryError>("Invalid name entry",
325 object_error::parse_failed);
326 DebugNames.push_back(wasm::WasmFunctionName{Index, Name});
327 if (isDefinedFunctionIndex(Index))
328 getDefinedFunction(Index).DebugName = Name;
332 // Ignore local names for now
333 case wasm::WASM_NAMES_LOCAL:
338 if (Ctx.Ptr != SubSectionEnd)
339 return make_error<GenericBinaryError>("Name sub-section ended prematurely",
340 object_error::parse_failed);
343 if (Ctx.Ptr != Ctx.End)
344 return make_error<GenericBinaryError>("Name section ended prematurely",
345 object_error::parse_failed);
346 return Error::success();
349 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {
350 HasLinkingSection = true;
351 if (Functions.size() != FunctionTypes.size()) {
352 return make_error<GenericBinaryError>(
353 "Linking data must come after code section", object_error::parse_failed);
356 LinkingData.Version = readVaruint32(Ctx);
357 if (LinkingData.Version != wasm::WasmMetadataVersion) {
358 return make_error<GenericBinaryError>(
359 "Unexpected metadata version: " + Twine(LinkingData.Version) +
360 " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",
361 object_error::parse_failed);
364 const uint8_t *OrigEnd = Ctx.End;
365 while (Ctx.Ptr < OrigEnd) {
367 uint8_t Type = readUint8(Ctx);
368 uint32_t Size = readVaruint32(Ctx);
369 DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size << "\n");
370 Ctx.End = Ctx.Ptr + Size;
372 case wasm::WASM_SYMBOL_TABLE:
373 if (Error Err = parseLinkingSectionSymtab(Ctx))
376 case wasm::WASM_SEGMENT_INFO: {
377 uint32_t Count = readVaruint32(Ctx);
378 if (Count > DataSegments.size())
379 return make_error<GenericBinaryError>("Too many segment names",
380 object_error::parse_failed);
381 for (uint32_t i = 0; i < Count; i++) {
382 DataSegments[i].Data.Name = readString(Ctx);
383 DataSegments[i].Data.Alignment = readVaruint32(Ctx);
384 DataSegments[i].Data.Flags = readVaruint32(Ctx);
388 case wasm::WASM_INIT_FUNCS: {
389 uint32_t Count = readVaruint32(Ctx);
390 LinkingData.InitFunctions.reserve(Count);
391 for (uint32_t i = 0; i < Count; i++) {
392 wasm::WasmInitFunc Init;
393 Init.Priority = readVaruint32(Ctx);
394 Init.Symbol = readVaruint32(Ctx);
395 if (!isValidFunctionSymbol(Init.Symbol))
396 return make_error<GenericBinaryError>("Invalid function symbol: " +
398 object_error::parse_failed);
399 LinkingData.InitFunctions.emplace_back(Init);
403 case wasm::WASM_COMDAT_INFO:
404 if (Error Err = parseLinkingSectionComdat(Ctx))
411 if (Ctx.Ptr != Ctx.End)
412 return make_error<GenericBinaryError>(
413 "Linking sub-section ended prematurely", object_error::parse_failed);
415 if (Ctx.Ptr != OrigEnd)
416 return make_error<GenericBinaryError>("Linking section ended prematurely",
417 object_error::parse_failed);
418 return Error::success();
421 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {
422 uint32_t Count = readVaruint32(Ctx);
423 LinkingData.SymbolTable.reserve(Count);
424 Symbols.reserve(Count);
425 StringSet<> SymbolNames;
427 std::vector<wasm::WasmImport *> ImportedGlobals;
428 std::vector<wasm::WasmImport *> ImportedFunctions;
429 ImportedGlobals.reserve(Imports.size());
430 ImportedFunctions.reserve(Imports.size());
431 for (auto &I : Imports) {
432 if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)
433 ImportedFunctions.emplace_back(&I);
434 else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)
435 ImportedGlobals.emplace_back(&I);
439 wasm::WasmSymbolInfo Info;
440 const wasm::WasmSignature *FunctionType = nullptr;
441 const wasm::WasmGlobalType *GlobalType = nullptr;
443 Info.Kind = readUint8(Ctx);
444 Info.Flags = readVaruint32(Ctx);
445 bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;
448 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
449 Info.ElementIndex = readVaruint32(Ctx);
450 if (!isValidFunctionIndex(Info.ElementIndex) ||
451 IsDefined != isDefinedFunctionIndex(Info.ElementIndex))
452 return make_error<GenericBinaryError>("invalid function symbol index",
453 object_error::parse_failed);
455 Info.Name = readString(Ctx);
456 unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
457 FunctionType = &Signatures[FunctionTypes[FuncIndex]];
458 wasm::WasmFunction &Function = Functions[FuncIndex];
459 if (Function.SymbolName.empty())
460 Function.SymbolName = Info.Name;
462 wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];
463 FunctionType = &Signatures[Import.SigIndex];
464 Info.Name = Import.Field;
465 Info.Module = Import.Module;
469 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
470 Info.ElementIndex = readVaruint32(Ctx);
471 if (!isValidGlobalIndex(Info.ElementIndex) ||
472 IsDefined != isDefinedGlobalIndex(Info.ElementIndex))
473 return make_error<GenericBinaryError>("invalid global symbol index",
474 object_error::parse_failed);
476 (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
477 wasm::WASM_SYMBOL_BINDING_WEAK)
478 return make_error<GenericBinaryError>("undefined weak global symbol",
479 object_error::parse_failed);
481 Info.Name = readString(Ctx);
482 unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;
483 wasm::WasmGlobal &Global = Globals[GlobalIndex];
484 GlobalType = &Global.Type;
485 if (Global.SymbolName.empty())
486 Global.SymbolName = Info.Name;
488 wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];
489 Info.Name = Import.Field;
490 GlobalType = &Import.Global;
494 case wasm::WASM_SYMBOL_TYPE_DATA:
495 Info.Name = readString(Ctx);
497 uint32_t Index = readVaruint32(Ctx);
498 if (Index >= DataSegments.size())
499 return make_error<GenericBinaryError>("invalid data symbol index",
500 object_error::parse_failed);
501 uint32_t Offset = readVaruint32(Ctx);
502 uint32_t Size = readVaruint32(Ctx);
503 if (Offset + Size > DataSegments[Index].Data.Content.size())
504 return make_error<GenericBinaryError>("invalid data symbol offset",
505 object_error::parse_failed);
506 Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
510 case wasm::WASM_SYMBOL_TYPE_SECTION: {
511 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
512 wasm::WASM_SYMBOL_BINDING_LOCAL)
513 return make_error<GenericBinaryError>(
514 "Section symbols must have local binding",
515 object_error::parse_failed);
516 Info.ElementIndex = readVaruint32(Ctx);
517 // Use somewhat unique section name as symbol name.
518 StringRef SectionName = Sections[Info.ElementIndex].Name;
519 Info.Name = SectionName;
524 return make_error<GenericBinaryError>("Invalid symbol type",
525 object_error::parse_failed);
528 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
529 wasm::WASM_SYMBOL_BINDING_LOCAL &&
530 !SymbolNames.insert(Info.Name).second)
531 return make_error<GenericBinaryError>("Duplicate symbol name " +
533 object_error::parse_failed);
534 LinkingData.SymbolTable.emplace_back(Info);
535 Symbols.emplace_back(LinkingData.SymbolTable.back(), FunctionType,
537 LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
540 return Error::success();
543 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {
544 uint32_t ComdatCount = readVaruint32(Ctx);
545 StringSet<> ComdatSet;
546 for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {
547 StringRef Name = readString(Ctx);
548 if (Name.empty() || !ComdatSet.insert(Name).second)
549 return make_error<GenericBinaryError>("Bad/duplicate COMDAT name " + Twine(Name),
550 object_error::parse_failed);
551 LinkingData.Comdats.emplace_back(Name);
552 uint32_t Flags = readVaruint32(Ctx);
554 return make_error<GenericBinaryError>("Unsupported COMDAT flags",
555 object_error::parse_failed);
557 uint32_t EntryCount = readVaruint32(Ctx);
558 while (EntryCount--) {
559 unsigned Kind = readVaruint32(Ctx);
560 unsigned Index = readVaruint32(Ctx);
563 return make_error<GenericBinaryError>("Invalid COMDAT entry type",
564 object_error::parse_failed);
565 case wasm::WASM_COMDAT_DATA:
566 if (Index >= DataSegments.size())
567 return make_error<GenericBinaryError>("COMDAT data index out of range",
568 object_error::parse_failed);
569 if (DataSegments[Index].Data.Comdat != UINT32_MAX)
570 return make_error<GenericBinaryError>("Data segment in two COMDATs",
571 object_error::parse_failed);
572 DataSegments[Index].Data.Comdat = ComdatIndex;
574 case wasm::WASM_COMDAT_FUNCTION:
575 if (!isDefinedFunctionIndex(Index))
576 return make_error<GenericBinaryError>("COMDAT function index out of range",
577 object_error::parse_failed);
578 if (getDefinedFunction(Index).Comdat != UINT32_MAX)
579 return make_error<GenericBinaryError>("Function in two COMDATs",
580 object_error::parse_failed);
581 getDefinedFunction(Index).Comdat = ComdatIndex;
586 return Error::success();
589 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {
590 uint32_t SectionIndex = readVaruint32(Ctx);
591 if (SectionIndex >= Sections.size())
592 return make_error<GenericBinaryError>("Invalid section index",
593 object_error::parse_failed);
594 WasmSection& Section = Sections[SectionIndex];
595 uint32_t RelocCount = readVaruint32(Ctx);
596 uint32_t EndOffset = Section.Content.size();
597 while (RelocCount--) {
598 wasm::WasmRelocation Reloc = {};
599 Reloc.Type = readVaruint32(Ctx);
600 Reloc.Offset = readVaruint32(Ctx);
601 Reloc.Index = readVaruint32(Ctx);
602 switch (Reloc.Type) {
603 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
604 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
605 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
606 if (!isValidFunctionSymbol(Reloc.Index))
607 return make_error<GenericBinaryError>("Bad relocation function index",
608 object_error::parse_failed);
610 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
611 if (Reloc.Index >= Signatures.size())
612 return make_error<GenericBinaryError>("Bad relocation type index",
613 object_error::parse_failed);
615 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
616 if (!isValidGlobalSymbol(Reloc.Index))
617 return make_error<GenericBinaryError>("Bad relocation global index",
618 object_error::parse_failed);
620 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
621 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
622 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
623 if (!isValidDataSymbol(Reloc.Index))
624 return make_error<GenericBinaryError>("Bad relocation data index",
625 object_error::parse_failed);
626 Reloc.Addend = readVarint32(Ctx);
628 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
629 if (!isValidFunctionSymbol(Reloc.Index))
630 return make_error<GenericBinaryError>("Bad relocation function index",
631 object_error::parse_failed);
632 Reloc.Addend = readVarint32(Ctx);
634 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
635 if (!isValidSectionSymbol(Reloc.Index))
636 return make_error<GenericBinaryError>("Bad relocation section index",
637 object_error::parse_failed);
638 Reloc.Addend = readVarint32(Ctx);
641 return make_error<GenericBinaryError>("Bad relocation type: " +
643 object_error::parse_failed);
646 // Relocations must fit inside the section, and must appear in order. They
647 // also shouldn't overlap a function/element boundary, but we don't bother
650 if (Reloc.Type == wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 ||
651 Reloc.Type == wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32 ||
652 Reloc.Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32 ||
653 Reloc.Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32)
655 if (Reloc.Offset + Size > EndOffset)
656 return make_error<GenericBinaryError>("Bad relocation offset",
657 object_error::parse_failed);
659 Section.Relocations.push_back(Reloc);
661 if (Ctx.Ptr != Ctx.End)
662 return make_error<GenericBinaryError>("Reloc section ended prematurely",
663 object_error::parse_failed);
664 return Error::success();
667 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {
668 if (Sec.Name == "name") {
669 if (Error Err = parseNameSection(Ctx))
671 } else if (Sec.Name == "linking") {
672 if (Error Err = parseLinkingSection(Ctx))
674 } else if (Sec.Name.startswith("reloc.")) {
675 if (Error Err = parseRelocSection(Sec.Name, Ctx))
678 return Error::success();
681 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {
682 uint32_t Count = readVaruint32(Ctx);
683 Signatures.reserve(Count);
685 wasm::WasmSignature Sig;
686 Sig.ReturnType = wasm::WASM_TYPE_NORESULT;
687 uint8_t Form = readUint8(Ctx);
688 if (Form != wasm::WASM_TYPE_FUNC) {
689 return make_error<GenericBinaryError>("Invalid signature type",
690 object_error::parse_failed);
692 uint32_t ParamCount = readVaruint32(Ctx);
693 Sig.ParamTypes.reserve(ParamCount);
694 while (ParamCount--) {
695 uint32_t ParamType = readUint8(Ctx);
696 Sig.ParamTypes.push_back(ParamType);
698 uint32_t ReturnCount = readVaruint32(Ctx);
700 if (ReturnCount != 1) {
701 return make_error<GenericBinaryError>(
702 "Multiple return types not supported", object_error::parse_failed);
704 Sig.ReturnType = readUint8(Ctx);
706 Signatures.push_back(Sig);
708 if (Ctx.Ptr != Ctx.End)
709 return make_error<GenericBinaryError>("Type section ended prematurely",
710 object_error::parse_failed);
711 return Error::success();
714 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {
715 uint32_t Count = readVaruint32(Ctx);
716 Imports.reserve(Count);
717 for (uint32_t i = 0; i < Count; i++) {
719 Im.Module = readString(Ctx);
720 Im.Field = readString(Ctx);
721 Im.Kind = readUint8(Ctx);
723 case wasm::WASM_EXTERNAL_FUNCTION:
724 NumImportedFunctions++;
725 Im.SigIndex = readVaruint32(Ctx);
727 case wasm::WASM_EXTERNAL_GLOBAL:
728 NumImportedGlobals++;
729 Im.Global.Type = readUint8(Ctx);
730 Im.Global.Mutable = readVaruint1(Ctx);
732 case wasm::WASM_EXTERNAL_MEMORY:
733 Im.Memory = readLimits(Ctx);
735 case wasm::WASM_EXTERNAL_TABLE:
736 Im.Table = readTable(Ctx);
737 if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC)
738 return make_error<GenericBinaryError>("Invalid table element type",
739 object_error::parse_failed);
742 return make_error<GenericBinaryError>(
743 "Unexpected import kind", object_error::parse_failed);
745 Imports.push_back(Im);
747 if (Ctx.Ptr != Ctx.End)
748 return make_error<GenericBinaryError>("Import section ended prematurely",
749 object_error::parse_failed);
750 return Error::success();
753 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {
754 uint32_t Count = readVaruint32(Ctx);
755 FunctionTypes.reserve(Count);
756 uint32_t NumTypes = Signatures.size();
758 uint32_t Type = readVaruint32(Ctx);
759 if (Type >= NumTypes)
760 return make_error<GenericBinaryError>("Invalid function type",
761 object_error::parse_failed);
762 FunctionTypes.push_back(Type);
764 if (Ctx.Ptr != Ctx.End)
765 return make_error<GenericBinaryError>("Function section ended prematurely",
766 object_error::parse_failed);
767 return Error::success();
770 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {
771 uint32_t Count = readVaruint32(Ctx);
772 Tables.reserve(Count);
774 Tables.push_back(readTable(Ctx));
775 if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) {
776 return make_error<GenericBinaryError>("Invalid table element type",
777 object_error::parse_failed);
780 if (Ctx.Ptr != Ctx.End)
781 return make_error<GenericBinaryError>("Table section ended prematurely",
782 object_error::parse_failed);
783 return Error::success();
786 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {
787 uint32_t Count = readVaruint32(Ctx);
788 Memories.reserve(Count);
790 Memories.push_back(readLimits(Ctx));
792 if (Ctx.Ptr != Ctx.End)
793 return make_error<GenericBinaryError>("Memory section ended prematurely",
794 object_error::parse_failed);
795 return Error::success();
798 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {
799 GlobalSection = Sections.size();
800 uint32_t Count = readVaruint32(Ctx);
801 Globals.reserve(Count);
803 wasm::WasmGlobal Global;
804 Global.Index = NumImportedGlobals + Globals.size();
805 Global.Type.Type = readUint8(Ctx);
806 Global.Type.Mutable = readVaruint1(Ctx);
807 if (Error Err = readInitExpr(Global.InitExpr, Ctx))
809 Globals.push_back(Global);
811 if (Ctx.Ptr != Ctx.End)
812 return make_error<GenericBinaryError>("Global section ended prematurely",
813 object_error::parse_failed);
814 return Error::success();
817 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {
818 uint32_t Count = readVaruint32(Ctx);
819 Exports.reserve(Count);
820 for (uint32_t i = 0; i < Count; i++) {
822 Ex.Name = readString(Ctx);
823 Ex.Kind = readUint8(Ctx);
824 Ex.Index = readVaruint32(Ctx);
826 case wasm::WASM_EXTERNAL_FUNCTION:
827 if (!isValidFunctionIndex(Ex.Index))
828 return make_error<GenericBinaryError>("Invalid function export",
829 object_error::parse_failed);
831 case wasm::WASM_EXTERNAL_GLOBAL:
832 if (!isValidGlobalIndex(Ex.Index))
833 return make_error<GenericBinaryError>("Invalid global export",
834 object_error::parse_failed);
836 case wasm::WASM_EXTERNAL_MEMORY:
837 case wasm::WASM_EXTERNAL_TABLE:
840 return make_error<GenericBinaryError>(
841 "Unexpected export kind", object_error::parse_failed);
843 Exports.push_back(Ex);
845 if (Ctx.Ptr != Ctx.End)
846 return make_error<GenericBinaryError>("Export section ended prematurely",
847 object_error::parse_failed);
848 return Error::success();
851 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
852 return Index < NumImportedFunctions + FunctionTypes.size();
855 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {
856 return Index >= NumImportedFunctions && isValidFunctionIndex(Index);
859 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {
860 return Index < NumImportedGlobals + Globals.size();
863 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {
864 return Index >= NumImportedGlobals && isValidGlobalIndex(Index);
867 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {
868 return Index < Symbols.size() && Symbols[Index].isTypeFunction();
871 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {
872 return Index < Symbols.size() && Symbols[Index].isTypeGlobal();
875 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {
876 return Index < Symbols.size() && Symbols[Index].isTypeData();
879 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {
880 return Index < Symbols.size() && Symbols[Index].isTypeSection();
883 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {
884 assert(isDefinedFunctionIndex(Index));
885 return Functions[Index - NumImportedFunctions];
888 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) {
889 assert(isDefinedGlobalIndex(Index));
890 return Globals[Index - NumImportedGlobals];
893 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {
894 StartFunction = readVaruint32(Ctx);
895 if (!isValidFunctionIndex(StartFunction))
896 return make_error<GenericBinaryError>("Invalid start function",
897 object_error::parse_failed);
898 return Error::success();
901 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {
902 CodeSection = Sections.size();
903 uint32_t FunctionCount = readVaruint32(Ctx);
904 if (FunctionCount != FunctionTypes.size()) {
905 return make_error<GenericBinaryError>("Invalid function count",
906 object_error::parse_failed);
909 while (FunctionCount--) {
910 wasm::WasmFunction Function;
911 const uint8_t *FunctionStart = Ctx.Ptr;
912 uint32_t Size = readVaruint32(Ctx);
913 const uint8_t *FunctionEnd = Ctx.Ptr + Size;
915 Function.CodeOffset = Ctx.Ptr - FunctionStart;
916 Function.Index = NumImportedFunctions + Functions.size();
917 Function.CodeSectionOffset = FunctionStart - Ctx.Start;
918 Function.Size = FunctionEnd - FunctionStart;
920 uint32_t NumLocalDecls = readVaruint32(Ctx);
921 Function.Locals.reserve(NumLocalDecls);
922 while (NumLocalDecls--) {
923 wasm::WasmLocalDecl Decl;
924 Decl.Count = readVaruint32(Ctx);
925 Decl.Type = readUint8(Ctx);
926 Function.Locals.push_back(Decl);
929 uint32_t BodySize = FunctionEnd - Ctx.Ptr;
930 Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);
931 // This will be set later when reading in the linking metadata section.
932 Function.Comdat = UINT32_MAX;
934 assert(Ctx.Ptr == FunctionEnd);
935 Functions.push_back(Function);
937 if (Ctx.Ptr != Ctx.End)
938 return make_error<GenericBinaryError>("Code section ended prematurely",
939 object_error::parse_failed);
940 return Error::success();
943 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {
944 uint32_t Count = readVaruint32(Ctx);
945 ElemSegments.reserve(Count);
947 wasm::WasmElemSegment Segment;
948 Segment.TableIndex = readVaruint32(Ctx);
949 if (Segment.TableIndex != 0) {
950 return make_error<GenericBinaryError>("Invalid TableIndex",
951 object_error::parse_failed);
953 if (Error Err = readInitExpr(Segment.Offset, Ctx))
955 uint32_t NumElems = readVaruint32(Ctx);
957 Segment.Functions.push_back(readVaruint32(Ctx));
959 ElemSegments.push_back(Segment);
961 if (Ctx.Ptr != Ctx.End)
962 return make_error<GenericBinaryError>("Elem section ended prematurely",
963 object_error::parse_failed);
964 return Error::success();
967 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {
968 DataSection = Sections.size();
969 uint32_t Count = readVaruint32(Ctx);
970 DataSegments.reserve(Count);
973 Segment.Data.MemoryIndex = readVaruint32(Ctx);
974 if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
976 uint32_t Size = readVaruint32(Ctx);
977 if (Size > Ctx.End - Ctx.Ptr)
978 return make_error<GenericBinaryError>("Invalid segment size",
979 object_error::parse_failed);
980 Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
981 // The rest of these Data fields are set later, when reading in the linking
983 Segment.Data.Alignment = 0;
984 Segment.Data.Flags = 0;
985 Segment.Data.Comdat = UINT32_MAX;
986 Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
988 DataSegments.push_back(Segment);
990 if (Ctx.Ptr != Ctx.End)
991 return make_error<GenericBinaryError>("Data section ended prematurely",
992 object_error::parse_failed);
993 return Error::success();
996 const uint8_t *WasmObjectFile::getPtr(size_t Offset) const {
997 return reinterpret_cast<const uint8_t *>(getData().substr(Offset, 1).data());
1000 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
1004 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.a++; }
1006 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
1007 uint32_t Result = SymbolRef::SF_None;
1008 const WasmSymbol &Sym = getWasmSymbol(Symb);
1010 LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
1011 if (Sym.isBindingWeak())
1012 Result |= SymbolRef::SF_Weak;
1013 if (!Sym.isBindingLocal())
1014 Result |= SymbolRef::SF_Global;
1016 Result |= SymbolRef::SF_Hidden;
1017 if (!Sym.isDefined())
1018 Result |= SymbolRef::SF_Undefined;
1019 if (Sym.isTypeFunction())
1020 Result |= SymbolRef::SF_Executable;
1024 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
1027 return BasicSymbolRef(Ref, this);
1030 basic_symbol_iterator WasmObjectFile::symbol_end() const {
1032 Ref.d.a = Symbols.size();
1033 return BasicSymbolRef(Ref, this);
1036 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
1037 return Symbols[Symb.d.a];
1040 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
1041 return getWasmSymbol(Symb.getRawDataRefImpl());
1044 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
1045 return getWasmSymbol(Symb).Info.Name;
1048 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
1049 return getSymbolValue(Symb);
1052 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol& Sym) const {
1053 switch (Sym.Info.Kind) {
1054 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1055 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1056 return Sym.Info.ElementIndex;
1057 case wasm::WASM_SYMBOL_TYPE_DATA: {
1058 // The value of a data symbol is the segment offset, plus the symbol
1059 // offset within the segment.
1060 uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
1061 const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
1062 assert(Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST);
1063 return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset;
1065 case wasm::WASM_SYMBOL_TYPE_SECTION:
1068 llvm_unreachable("invalid symbol type");
1071 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
1072 return getWasmSymbolValue(getWasmSymbol(Symb));
1075 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
1076 llvm_unreachable("not yet implemented");
1080 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
1081 llvm_unreachable("not yet implemented");
1085 Expected<SymbolRef::Type>
1086 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
1087 const WasmSymbol &Sym = getWasmSymbol(Symb);
1089 switch (Sym.Info.Kind) {
1090 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1091 return SymbolRef::ST_Function;
1092 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1093 return SymbolRef::ST_Other;
1094 case wasm::WASM_SYMBOL_TYPE_DATA:
1095 return SymbolRef::ST_Data;
1096 case wasm::WASM_SYMBOL_TYPE_SECTION:
1097 return SymbolRef::ST_Debug;
1100 llvm_unreachable("Unknown WasmSymbol::SymbolType");
1101 return SymbolRef::ST_Other;
1104 Expected<section_iterator>
1105 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
1106 const WasmSymbol& Sym = getWasmSymbol(Symb);
1107 if (Sym.isUndefined())
1108 return section_end();
1111 switch (Sym.Info.Kind) {
1112 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1113 Ref.d.a = CodeSection;
1115 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1116 Ref.d.a = GlobalSection;
1118 case wasm::WASM_SYMBOL_TYPE_DATA:
1119 Ref.d.a = DataSection;
1121 case wasm::WASM_SYMBOL_TYPE_SECTION: {
1122 Ref.d.a = Sym.Info.ElementIndex;
1126 llvm_unreachable("Unknown WasmSymbol::SymbolType");
1128 return section_iterator(SectionRef(Ref, this));
1131 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
1133 std::error_code WasmObjectFile::getSectionName(DataRefImpl Sec,
1134 StringRef &Res) const {
1135 const WasmSection &S = Sections[Sec.d.a];
1137 case wasm::WASM_SEC_##X: \
1152 case wasm::WASM_SEC_CUSTOM:
1156 return object_error::invalid_section_index;
1159 return std::error_code();
1162 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
1164 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
1168 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
1169 const WasmSection &S = Sections[Sec.d.a];
1170 return S.Content.size();
1173 std::error_code WasmObjectFile::getSectionContents(DataRefImpl Sec,
1174 StringRef &Res) const {
1175 const WasmSection &S = Sections[Sec.d.a];
1176 // This will never fail since wasm sections can never be empty (user-sections
1177 // must have a name and non-user sections each have a defined structure).
1178 Res = StringRef(reinterpret_cast<const char *>(S.Content.data()),
1180 return std::error_code();
1183 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1187 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1191 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
1192 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
1195 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
1196 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
1199 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
1201 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
1203 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec) const { return false; }
1205 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
1206 DataRefImpl RelocRef;
1207 RelocRef.d.a = Ref.d.a;
1209 return relocation_iterator(RelocationRef(RelocRef, this));
1212 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
1213 const WasmSection &Sec = getWasmSection(Ref);
1214 DataRefImpl RelocRef;
1215 RelocRef.d.a = Ref.d.a;
1216 RelocRef.d.b = Sec.Relocations.size();
1217 return relocation_iterator(RelocationRef(RelocRef, this));
1220 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1224 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1225 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1229 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
1230 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1231 if (Rel.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1232 return symbol_end();
1234 Sym.d.a = Rel.Index;
1236 return symbol_iterator(SymbolRef(Sym, this));
1239 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1240 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1244 void WasmObjectFile::getRelocationTypeName(
1245 DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1246 const wasm::WasmRelocation& Rel = getWasmRelocation(Ref);
1247 StringRef Res = "Unknown";
1249 #define WASM_RELOC(name, value) \
1255 #include "llvm/BinaryFormat/WasmRelocs.def"
1260 Result.append(Res.begin(), Res.end());
1263 section_iterator WasmObjectFile::section_begin() const {
1266 return section_iterator(SectionRef(Ref, this));
1269 section_iterator WasmObjectFile::section_end() const {
1271 Ref.d.a = Sections.size();
1272 return section_iterator(SectionRef(Ref, this));
1275 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1277 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
1279 Triple::ArchType WasmObjectFile::getArch() const { return Triple::wasm32; }
1281 SubtargetFeatures WasmObjectFile::getFeatures() const {
1282 return SubtargetFeatures();
1285 bool WasmObjectFile::isRelocatableObject() const {
1286 return HasLinkingSection;
1289 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
1290 assert(Ref.d.a < Sections.size());
1291 return Sections[Ref.d.a];
1295 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
1296 return getWasmSection(Section.getRawDataRefImpl());
1299 const wasm::WasmRelocation &
1300 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
1301 return getWasmRelocation(Ref.getRawDataRefImpl());
1304 const wasm::WasmRelocation &
1305 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
1306 assert(Ref.d.a < Sections.size());
1307 const WasmSection& Sec = Sections[Ref.d.a];
1308 assert(Ref.d.b < Sec.Relocations.size());
1309 return Sec.Relocations[Ref.d.b];