Path: blob/main/contrib/llvm-project/llvm/lib/Object/WasmObjectFile.cpp
35232 views
//===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/ADT/ArrayRef.h"9#include "llvm/ADT/DenseSet.h"10#include "llvm/ADT/SmallSet.h"11#include "llvm/ADT/StringRef.h"12#include "llvm/ADT/StringSet.h"13#include "llvm/ADT/StringSwitch.h"14#include "llvm/BinaryFormat/Wasm.h"15#include "llvm/Object/Binary.h"16#include "llvm/Object/Error.h"17#include "llvm/Object/ObjectFile.h"18#include "llvm/Object/SymbolicFile.h"19#include "llvm/Object/Wasm.h"20#include "llvm/Support/Endian.h"21#include "llvm/Support/Error.h"22#include "llvm/Support/ErrorHandling.h"23#include "llvm/Support/Format.h"24#include "llvm/Support/LEB128.h"25#include "llvm/Support/ScopedPrinter.h"26#include "llvm/TargetParser/SubtargetFeature.h"27#include "llvm/TargetParser/Triple.h"28#include <algorithm>29#include <cassert>30#include <cstdint>31#include <cstring>32#include <limits>3334#define DEBUG_TYPE "wasm-object"3536using namespace llvm;37using namespace object;3839void WasmSymbol::print(raw_ostream &Out) const {40Out << "Name=" << Info.Name41<< ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind)) << ", Flags=0x"42<< Twine::utohexstr(Info.Flags) << " [";43switch (getBinding()) {44case wasm::WASM_SYMBOL_BINDING_GLOBAL: Out << "global"; break;45case wasm::WASM_SYMBOL_BINDING_LOCAL: Out << "local"; break;46case wasm::WASM_SYMBOL_BINDING_WEAK: Out << "weak"; break;47}48if (isHidden()) {49Out << ", hidden";50} else {51Out << ", default";52}53Out << "]";54if (!isTypeData()) {55Out << ", ElemIndex=" << Info.ElementIndex;56} else if (isDefined()) {57Out << ", Segment=" << Info.DataRef.Segment;58Out << ", Offset=" << Info.DataRef.Offset;59Out << ", Size=" << Info.DataRef.Size;60}61}6263#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)64LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); }65#endif6667Expected<std::unique_ptr<WasmObjectFile>>68ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {69Error Err = Error::success();70auto ObjectFile = std::make_unique<WasmObjectFile>(Buffer, Err);71if (Err)72return std::move(Err);7374return std::move(ObjectFile);75}7677#define VARINT7_MAX ((1 << 7) - 1)78#define VARINT7_MIN (-(1 << 7))79#define VARUINT7_MAX (1 << 7)80#define VARUINT1_MAX (1)8182static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) {83if (Ctx.Ptr == Ctx.End)84report_fatal_error("EOF while reading uint8");85return *Ctx.Ptr++;86}8788static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) {89if (Ctx.Ptr + 4 > Ctx.End)90report_fatal_error("EOF while reading uint32");91uint32_t Result = support::endian::read32le(Ctx.Ptr);92Ctx.Ptr += 4;93return Result;94}9596static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) {97if (Ctx.Ptr + 4 > Ctx.End)98report_fatal_error("EOF while reading float64");99int32_t Result = 0;100memcpy(&Result, Ctx.Ptr, sizeof(Result));101Ctx.Ptr += sizeof(Result);102return Result;103}104105static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) {106if (Ctx.Ptr + 8 > Ctx.End)107report_fatal_error("EOF while reading float64");108int64_t Result = 0;109memcpy(&Result, Ctx.Ptr, sizeof(Result));110Ctx.Ptr += sizeof(Result);111return Result;112}113114static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) {115unsigned Count;116const char *Error = nullptr;117uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error);118if (Error)119report_fatal_error(Error);120Ctx.Ptr += Count;121return Result;122}123124static StringRef readString(WasmObjectFile::ReadContext &Ctx) {125uint32_t StringLen = readULEB128(Ctx);126if (Ctx.Ptr + StringLen > Ctx.End)127report_fatal_error("EOF while reading string");128StringRef Return =129StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen);130Ctx.Ptr += StringLen;131return Return;132}133134static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) {135unsigned Count;136const char *Error = nullptr;137uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error);138if (Error)139report_fatal_error(Error);140Ctx.Ptr += Count;141return Result;142}143144static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) {145int64_t Result = readLEB128(Ctx);146if (Result > VARUINT1_MAX || Result < 0)147report_fatal_error("LEB is outside Varuint1 range");148return Result;149}150151static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) {152int64_t Result = readLEB128(Ctx);153if (Result > INT32_MAX || Result < INT32_MIN)154report_fatal_error("LEB is outside Varint32 range");155return Result;156}157158static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) {159uint64_t Result = readULEB128(Ctx);160if (Result > UINT32_MAX)161report_fatal_error("LEB is outside Varuint32 range");162return Result;163}164165static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) {166return readLEB128(Ctx);167}168169static uint64_t readVaruint64(WasmObjectFile::ReadContext &Ctx) {170return readULEB128(Ctx);171}172173static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) {174return readUint8(Ctx);175}176177static wasm::ValType parseValType(WasmObjectFile::ReadContext &Ctx,178uint32_t Code) {179// only directly encoded FUNCREF/EXTERNREF/EXNREF are supported180// (not ref null func, ref null extern, or ref null exn)181switch (Code) {182case wasm::WASM_TYPE_I32:183case wasm::WASM_TYPE_I64:184case wasm::WASM_TYPE_F32:185case wasm::WASM_TYPE_F64:186case wasm::WASM_TYPE_V128:187case wasm::WASM_TYPE_FUNCREF:188case wasm::WASM_TYPE_EXTERNREF:189case wasm::WASM_TYPE_EXNREF:190return wasm::ValType(Code);191}192if (Code == wasm::WASM_TYPE_NULLABLE || Code == wasm::WASM_TYPE_NONNULLABLE) {193/* Discard HeapType */ readVarint64(Ctx);194}195return wasm::ValType(wasm::ValType::OTHERREF);196}197198static Error readInitExpr(wasm::WasmInitExpr &Expr,199WasmObjectFile::ReadContext &Ctx) {200auto Start = Ctx.Ptr;201202Expr.Extended = false;203Expr.Inst.Opcode = readOpcode(Ctx);204switch (Expr.Inst.Opcode) {205case wasm::WASM_OPCODE_I32_CONST:206Expr.Inst.Value.Int32 = readVarint32(Ctx);207break;208case wasm::WASM_OPCODE_I64_CONST:209Expr.Inst.Value.Int64 = readVarint64(Ctx);210break;211case wasm::WASM_OPCODE_F32_CONST:212Expr.Inst.Value.Float32 = readFloat32(Ctx);213break;214case wasm::WASM_OPCODE_F64_CONST:215Expr.Inst.Value.Float64 = readFloat64(Ctx);216break;217case wasm::WASM_OPCODE_GLOBAL_GET:218Expr.Inst.Value.Global = readULEB128(Ctx);219break;220case wasm::WASM_OPCODE_REF_NULL: {221/* Discard type */ parseValType(Ctx, readVaruint32(Ctx));222break;223}224default:225Expr.Extended = true;226}227228if (!Expr.Extended) {229uint8_t EndOpcode = readOpcode(Ctx);230if (EndOpcode != wasm::WASM_OPCODE_END)231Expr.Extended = true;232}233234if (Expr.Extended) {235Ctx.Ptr = Start;236while (true) {237uint8_t Opcode = readOpcode(Ctx);238switch (Opcode) {239case wasm::WASM_OPCODE_I32_CONST:240case wasm::WASM_OPCODE_GLOBAL_GET:241case wasm::WASM_OPCODE_REF_NULL:242case wasm::WASM_OPCODE_REF_FUNC:243case wasm::WASM_OPCODE_I64_CONST:244readULEB128(Ctx);245break;246case wasm::WASM_OPCODE_F32_CONST:247readFloat32(Ctx);248break;249case wasm::WASM_OPCODE_F64_CONST:250readFloat64(Ctx);251break;252case wasm::WASM_OPCODE_I32_ADD:253case wasm::WASM_OPCODE_I32_SUB:254case wasm::WASM_OPCODE_I32_MUL:255case wasm::WASM_OPCODE_I64_ADD:256case wasm::WASM_OPCODE_I64_SUB:257case wasm::WASM_OPCODE_I64_MUL:258break;259case wasm::WASM_OPCODE_GC_PREFIX:260break;261// The GC opcodes are in a separate (prefixed space). This flat switch262// structure works as long as there is no overlap between the GC and263// general opcodes used in init exprs.264case wasm::WASM_OPCODE_STRUCT_NEW:265case wasm::WASM_OPCODE_STRUCT_NEW_DEFAULT:266case wasm::WASM_OPCODE_ARRAY_NEW:267case wasm::WASM_OPCODE_ARRAY_NEW_DEFAULT:268readULEB128(Ctx); // heap type index269break;270case wasm::WASM_OPCODE_ARRAY_NEW_FIXED:271readULEB128(Ctx); // heap type index272readULEB128(Ctx); // array size273break;274case wasm::WASM_OPCODE_REF_I31:275break;276case wasm::WASM_OPCODE_END:277Expr.Body = ArrayRef<uint8_t>(Start, Ctx.Ptr - Start);278return Error::success();279default:280return make_error<GenericBinaryError>(281Twine("invalid opcode in init_expr: ") + Twine(unsigned(Opcode)),282object_error::parse_failed);283}284}285}286287return Error::success();288}289290static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) {291wasm::WasmLimits Result;292Result.Flags = readVaruint32(Ctx);293Result.Minimum = readVaruint64(Ctx);294if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)295Result.Maximum = readVaruint64(Ctx);296return Result;297}298299static wasm::WasmTableType readTableType(WasmObjectFile::ReadContext &Ctx) {300wasm::WasmTableType TableType;301auto ElemType = parseValType(Ctx, readVaruint32(Ctx));302TableType.ElemType = ElemType;303TableType.Limits = readLimits(Ctx);304return TableType;305}306307static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx,308WasmSectionOrderChecker &Checker) {309Section.Type = readUint8(Ctx);310LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");311// When reading the section's size, store the size of the LEB used to encode312// it. This allows objcopy/strip to reproduce the binary identically.313const uint8_t *PreSizePtr = Ctx.Ptr;314uint32_t Size = readVaruint32(Ctx);315Section.HeaderSecSizeEncodingLen = Ctx.Ptr - PreSizePtr;316Section.Offset = Ctx.Ptr - Ctx.Start;317if (Size == 0)318return make_error<StringError>("zero length section",319object_error::parse_failed);320if (Ctx.Ptr + Size > Ctx.End)321return make_error<StringError>("section too large",322object_error::parse_failed);323if (Section.Type == wasm::WASM_SEC_CUSTOM) {324WasmObjectFile::ReadContext SectionCtx;325SectionCtx.Start = Ctx.Ptr;326SectionCtx.Ptr = Ctx.Ptr;327SectionCtx.End = Ctx.Ptr + Size;328329Section.Name = readString(SectionCtx);330331uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start;332Ctx.Ptr += SectionNameSize;333Size -= SectionNameSize;334}335336if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) {337return make_error<StringError>("out of order section type: " +338llvm::to_string(Section.Type),339object_error::parse_failed);340}341342Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);343Ctx.Ptr += Size;344return Error::success();345}346347WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)348: ObjectFile(Binary::ID_Wasm, Buffer) {349ErrorAsOutParameter ErrAsOutParam(&Err);350Header.Magic = getData().substr(0, 4);351if (Header.Magic != StringRef("\0asm", 4)) {352Err = make_error<StringError>("invalid magic number",353object_error::parse_failed);354return;355}356357ReadContext Ctx;358Ctx.Start = getData().bytes_begin();359Ctx.Ptr = Ctx.Start + 4;360Ctx.End = Ctx.Start + getData().size();361362if (Ctx.Ptr + 4 > Ctx.End) {363Err = make_error<StringError>("missing version number",364object_error::parse_failed);365return;366}367368Header.Version = readUint32(Ctx);369if (Header.Version != wasm::WasmVersion) {370Err = make_error<StringError>("invalid version number: " +371Twine(Header.Version),372object_error::parse_failed);373return;374}375376WasmSectionOrderChecker Checker;377while (Ctx.Ptr < Ctx.End) {378WasmSection Sec;379if ((Err = readSection(Sec, Ctx, Checker)))380return;381if ((Err = parseSection(Sec)))382return;383384Sections.push_back(Sec);385}386}387388Error WasmObjectFile::parseSection(WasmSection &Sec) {389ReadContext Ctx;390Ctx.Start = Sec.Content.data();391Ctx.End = Ctx.Start + Sec.Content.size();392Ctx.Ptr = Ctx.Start;393switch (Sec.Type) {394case wasm::WASM_SEC_CUSTOM:395return parseCustomSection(Sec, Ctx);396case wasm::WASM_SEC_TYPE:397return parseTypeSection(Ctx);398case wasm::WASM_SEC_IMPORT:399return parseImportSection(Ctx);400case wasm::WASM_SEC_FUNCTION:401return parseFunctionSection(Ctx);402case wasm::WASM_SEC_TABLE:403return parseTableSection(Ctx);404case wasm::WASM_SEC_MEMORY:405return parseMemorySection(Ctx);406case wasm::WASM_SEC_TAG:407return parseTagSection(Ctx);408case wasm::WASM_SEC_GLOBAL:409return parseGlobalSection(Ctx);410case wasm::WASM_SEC_EXPORT:411return parseExportSection(Ctx);412case wasm::WASM_SEC_START:413return parseStartSection(Ctx);414case wasm::WASM_SEC_ELEM:415return parseElemSection(Ctx);416case wasm::WASM_SEC_CODE:417return parseCodeSection(Ctx);418case wasm::WASM_SEC_DATA:419return parseDataSection(Ctx);420case wasm::WASM_SEC_DATACOUNT:421return parseDataCountSection(Ctx);422default:423return make_error<GenericBinaryError>(424"invalid section type: " + Twine(Sec.Type), object_error::parse_failed);425}426}427428Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) {429// Legacy "dylink" section support.430// See parseDylink0Section for the current "dylink.0" section parsing.431HasDylinkSection = true;432DylinkInfo.MemorySize = readVaruint32(Ctx);433DylinkInfo.MemoryAlignment = readVaruint32(Ctx);434DylinkInfo.TableSize = readVaruint32(Ctx);435DylinkInfo.TableAlignment = readVaruint32(Ctx);436uint32_t Count = readVaruint32(Ctx);437while (Count--) {438DylinkInfo.Needed.push_back(readString(Ctx));439}440441if (Ctx.Ptr != Ctx.End)442return make_error<GenericBinaryError>("dylink section ended prematurely",443object_error::parse_failed);444return Error::success();445}446447Error WasmObjectFile::parseDylink0Section(ReadContext &Ctx) {448// See449// https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md450HasDylinkSection = true;451452const uint8_t *OrigEnd = Ctx.End;453while (Ctx.Ptr < OrigEnd) {454Ctx.End = OrigEnd;455uint8_t Type = readUint8(Ctx);456uint32_t Size = readVaruint32(Ctx);457LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size458<< "\n");459Ctx.End = Ctx.Ptr + Size;460uint32_t Count;461switch (Type) {462case wasm::WASM_DYLINK_MEM_INFO:463DylinkInfo.MemorySize = readVaruint32(Ctx);464DylinkInfo.MemoryAlignment = readVaruint32(Ctx);465DylinkInfo.TableSize = readVaruint32(Ctx);466DylinkInfo.TableAlignment = readVaruint32(Ctx);467break;468case wasm::WASM_DYLINK_NEEDED:469Count = readVaruint32(Ctx);470while (Count--) {471DylinkInfo.Needed.push_back(readString(Ctx));472}473break;474case wasm::WASM_DYLINK_EXPORT_INFO: {475uint32_t Count = readVaruint32(Ctx);476while (Count--) {477DylinkInfo.ExportInfo.push_back({readString(Ctx), readVaruint32(Ctx)});478}479break;480}481case wasm::WASM_DYLINK_IMPORT_INFO: {482uint32_t Count = readVaruint32(Ctx);483while (Count--) {484DylinkInfo.ImportInfo.push_back(485{readString(Ctx), readString(Ctx), readVaruint32(Ctx)});486}487break;488}489default:490LLVM_DEBUG(dbgs() << "unknown dylink.0 sub-section: " << Type << "\n");491Ctx.Ptr += Size;492break;493}494if (Ctx.Ptr != Ctx.End) {495return make_error<GenericBinaryError>(496"dylink.0 sub-section ended prematurely", object_error::parse_failed);497}498}499500if (Ctx.Ptr != Ctx.End)501return make_error<GenericBinaryError>("dylink.0 section ended prematurely",502object_error::parse_failed);503return Error::success();504}505506Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {507llvm::DenseSet<uint64_t> SeenFunctions;508llvm::DenseSet<uint64_t> SeenGlobals;509llvm::DenseSet<uint64_t> SeenSegments;510511// If we have linking section (symbol table) or if we are parsing a DSO512// then we don't use the name section for symbol information.513bool PopulateSymbolTable = !HasLinkingSection && !HasDylinkSection;514515// If we are using the name section for symbol information then it will516// supersede any symbols created by the export section.517if (PopulateSymbolTable)518Symbols.clear();519520while (Ctx.Ptr < Ctx.End) {521uint8_t Type = readUint8(Ctx);522uint32_t Size = readVaruint32(Ctx);523const uint8_t *SubSectionEnd = Ctx.Ptr + Size;524525switch (Type) {526case wasm::WASM_NAMES_FUNCTION:527case wasm::WASM_NAMES_GLOBAL:528case wasm::WASM_NAMES_DATA_SEGMENT: {529uint32_t Count = readVaruint32(Ctx);530while (Count--) {531uint32_t Index = readVaruint32(Ctx);532StringRef Name = readString(Ctx);533wasm::NameType nameType = wasm::NameType::FUNCTION;534wasm::WasmSymbolInfo Info{Name,535/*Kind */ wasm::WASM_SYMBOL_TYPE_FUNCTION,536/* Flags */ 0,537/* ImportModule */ std::nullopt,538/* ImportName */ std::nullopt,539/* ExportName */ std::nullopt,540{/* ElementIndex */ Index}};541const wasm::WasmSignature *Signature = nullptr;542const wasm::WasmGlobalType *GlobalType = nullptr;543const wasm::WasmTableType *TableType = nullptr;544if (Type == wasm::WASM_NAMES_FUNCTION) {545if (!SeenFunctions.insert(Index).second)546return make_error<GenericBinaryError>(547"function named more than once", object_error::parse_failed);548if (!isValidFunctionIndex(Index) || Name.empty())549return make_error<GenericBinaryError>("invalid function name entry",550object_error::parse_failed);551552if (isDefinedFunctionIndex(Index)) {553wasm::WasmFunction &F = getDefinedFunction(Index);554F.DebugName = Name;555Signature = &Signatures[F.SigIndex];556if (F.ExportName) {557Info.ExportName = F.ExportName;558Info.Flags |= wasm::WASM_SYMBOL_BINDING_GLOBAL;559} else {560Info.Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;561}562} else {563Info.Flags |= wasm::WASM_SYMBOL_UNDEFINED;564}565} else if (Type == wasm::WASM_NAMES_GLOBAL) {566if (!SeenGlobals.insert(Index).second)567return make_error<GenericBinaryError>("global named more than once",568object_error::parse_failed);569if (!isValidGlobalIndex(Index) || Name.empty())570return make_error<GenericBinaryError>("invalid global name entry",571object_error::parse_failed);572nameType = wasm::NameType::GLOBAL;573Info.Kind = wasm::WASM_SYMBOL_TYPE_GLOBAL;574if (isDefinedGlobalIndex(Index)) {575GlobalType = &getDefinedGlobal(Index).Type;576} else {577Info.Flags |= wasm::WASM_SYMBOL_UNDEFINED;578}579} else {580if (!SeenSegments.insert(Index).second)581return make_error<GenericBinaryError>(582"segment named more than once", object_error::parse_failed);583if (Index > DataSegments.size())584return make_error<GenericBinaryError>("invalid data segment name entry",585object_error::parse_failed);586nameType = wasm::NameType::DATA_SEGMENT;587Info.Kind = wasm::WASM_SYMBOL_TYPE_DATA;588Info.Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;589assert(Index < DataSegments.size());590Info.DataRef = wasm::WasmDataReference{591Index, 0, DataSegments[Index].Data.Content.size()};592}593DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name});594if (PopulateSymbolTable)595Symbols.emplace_back(Info, GlobalType, TableType, Signature);596}597break;598}599// Ignore local names for now600case wasm::WASM_NAMES_LOCAL:601default:602Ctx.Ptr += Size;603break;604}605if (Ctx.Ptr != SubSectionEnd)606return make_error<GenericBinaryError>(607"name sub-section ended prematurely", object_error::parse_failed);608}609610if (Ctx.Ptr != Ctx.End)611return make_error<GenericBinaryError>("name section ended prematurely",612object_error::parse_failed);613return Error::success();614}615616Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {617HasLinkingSection = true;618619LinkingData.Version = readVaruint32(Ctx);620if (LinkingData.Version != wasm::WasmMetadataVersion) {621return make_error<GenericBinaryError>(622"unexpected metadata version: " + Twine(LinkingData.Version) +623" (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",624object_error::parse_failed);625}626627const uint8_t *OrigEnd = Ctx.End;628while (Ctx.Ptr < OrigEnd) {629Ctx.End = OrigEnd;630uint8_t Type = readUint8(Ctx);631uint32_t Size = readVaruint32(Ctx);632LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size633<< "\n");634Ctx.End = Ctx.Ptr + Size;635switch (Type) {636case wasm::WASM_SYMBOL_TABLE:637if (Error Err = parseLinkingSectionSymtab(Ctx))638return Err;639break;640case wasm::WASM_SEGMENT_INFO: {641uint32_t Count = readVaruint32(Ctx);642if (Count > DataSegments.size())643return make_error<GenericBinaryError>("too many segment names",644object_error::parse_failed);645for (uint32_t I = 0; I < Count; I++) {646DataSegments[I].Data.Name = readString(Ctx);647DataSegments[I].Data.Alignment = readVaruint32(Ctx);648DataSegments[I].Data.LinkingFlags = readVaruint32(Ctx);649}650break;651}652case wasm::WASM_INIT_FUNCS: {653uint32_t Count = readVaruint32(Ctx);654LinkingData.InitFunctions.reserve(Count);655for (uint32_t I = 0; I < Count; I++) {656wasm::WasmInitFunc Init;657Init.Priority = readVaruint32(Ctx);658Init.Symbol = readVaruint32(Ctx);659if (!isValidFunctionSymbol(Init.Symbol))660return make_error<GenericBinaryError>("invalid function symbol: " +661Twine(Init.Symbol),662object_error::parse_failed);663LinkingData.InitFunctions.emplace_back(Init);664}665break;666}667case wasm::WASM_COMDAT_INFO:668if (Error Err = parseLinkingSectionComdat(Ctx))669return Err;670break;671default:672Ctx.Ptr += Size;673break;674}675if (Ctx.Ptr != Ctx.End)676return make_error<GenericBinaryError>(677"linking sub-section ended prematurely", object_error::parse_failed);678}679if (Ctx.Ptr != OrigEnd)680return make_error<GenericBinaryError>("linking section ended prematurely",681object_error::parse_failed);682return Error::success();683}684685Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {686uint32_t Count = readVaruint32(Ctx);687// Clear out any symbol information that was derived from the exports688// section.689Symbols.clear();690Symbols.reserve(Count);691StringSet<> SymbolNames;692693std::vector<wasm::WasmImport *> ImportedGlobals;694std::vector<wasm::WasmImport *> ImportedFunctions;695std::vector<wasm::WasmImport *> ImportedTags;696std::vector<wasm::WasmImport *> ImportedTables;697ImportedGlobals.reserve(Imports.size());698ImportedFunctions.reserve(Imports.size());699ImportedTags.reserve(Imports.size());700ImportedTables.reserve(Imports.size());701for (auto &I : Imports) {702if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)703ImportedFunctions.emplace_back(&I);704else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)705ImportedGlobals.emplace_back(&I);706else if (I.Kind == wasm::WASM_EXTERNAL_TAG)707ImportedTags.emplace_back(&I);708else if (I.Kind == wasm::WASM_EXTERNAL_TABLE)709ImportedTables.emplace_back(&I);710}711712while (Count--) {713wasm::WasmSymbolInfo Info;714const wasm::WasmSignature *Signature = nullptr;715const wasm::WasmGlobalType *GlobalType = nullptr;716const wasm::WasmTableType *TableType = nullptr;717718Info.Kind = readUint8(Ctx);719Info.Flags = readVaruint32(Ctx);720bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;721722switch (Info.Kind) {723case wasm::WASM_SYMBOL_TYPE_FUNCTION:724Info.ElementIndex = readVaruint32(Ctx);725if (!isValidFunctionIndex(Info.ElementIndex) ||726IsDefined != isDefinedFunctionIndex(Info.ElementIndex))727return make_error<GenericBinaryError>("invalid function symbol index",728object_error::parse_failed);729if (IsDefined) {730Info.Name = readString(Ctx);731unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;732wasm::WasmFunction &Function = Functions[FuncIndex];733Signature = &Signatures[Function.SigIndex];734if (Function.SymbolName.empty())735Function.SymbolName = Info.Name;736} else {737wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];738if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {739Info.Name = readString(Ctx);740Info.ImportName = Import.Field;741} else {742Info.Name = Import.Field;743}744Signature = &Signatures[Import.SigIndex];745Info.ImportModule = Import.Module;746}747break;748749case wasm::WASM_SYMBOL_TYPE_GLOBAL:750Info.ElementIndex = readVaruint32(Ctx);751if (!isValidGlobalIndex(Info.ElementIndex) ||752IsDefined != isDefinedGlobalIndex(Info.ElementIndex))753return make_error<GenericBinaryError>("invalid global symbol index",754object_error::parse_failed);755if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==756wasm::WASM_SYMBOL_BINDING_WEAK)757return make_error<GenericBinaryError>("undefined weak global symbol",758object_error::parse_failed);759if (IsDefined) {760Info.Name = readString(Ctx);761unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;762wasm::WasmGlobal &Global = Globals[GlobalIndex];763GlobalType = &Global.Type;764if (Global.SymbolName.empty())765Global.SymbolName = Info.Name;766} else {767wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];768if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {769Info.Name = readString(Ctx);770Info.ImportName = Import.Field;771} else {772Info.Name = Import.Field;773}774GlobalType = &Import.Global;775Info.ImportModule = Import.Module;776}777break;778779case wasm::WASM_SYMBOL_TYPE_TABLE:780Info.ElementIndex = readVaruint32(Ctx);781if (!isValidTableNumber(Info.ElementIndex) ||782IsDefined != isDefinedTableNumber(Info.ElementIndex))783return make_error<GenericBinaryError>("invalid table symbol index",784object_error::parse_failed);785if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==786wasm::WASM_SYMBOL_BINDING_WEAK)787return make_error<GenericBinaryError>("undefined weak table symbol",788object_error::parse_failed);789if (IsDefined) {790Info.Name = readString(Ctx);791unsigned TableNumber = Info.ElementIndex - NumImportedTables;792wasm::WasmTable &Table = Tables[TableNumber];793TableType = &Table.Type;794if (Table.SymbolName.empty())795Table.SymbolName = Info.Name;796} else {797wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex];798if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {799Info.Name = readString(Ctx);800Info.ImportName = Import.Field;801} else {802Info.Name = Import.Field;803}804TableType = &Import.Table;805Info.ImportModule = Import.Module;806}807break;808809case wasm::WASM_SYMBOL_TYPE_DATA:810Info.Name = readString(Ctx);811if (IsDefined) {812auto Index = readVaruint32(Ctx);813auto Offset = readVaruint64(Ctx);814auto Size = readVaruint64(Ctx);815if (!(Info.Flags & wasm::WASM_SYMBOL_ABSOLUTE)) {816if (static_cast<size_t>(Index) >= DataSegments.size())817return make_error<GenericBinaryError>(818"invalid data segment index: " + Twine(Index),819object_error::parse_failed);820size_t SegmentSize = DataSegments[Index].Data.Content.size();821if (Offset > SegmentSize)822return make_error<GenericBinaryError>(823"invalid data symbol offset: `" + Info.Name +824"` (offset: " + Twine(Offset) +825" segment size: " + Twine(SegmentSize) + ")",826object_error::parse_failed);827}828Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};829}830break;831832case wasm::WASM_SYMBOL_TYPE_SECTION: {833if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=834wasm::WASM_SYMBOL_BINDING_LOCAL)835return make_error<GenericBinaryError>(836"section symbols must have local binding",837object_error::parse_failed);838Info.ElementIndex = readVaruint32(Ctx);839// Use somewhat unique section name as symbol name.840StringRef SectionName = Sections[Info.ElementIndex].Name;841Info.Name = SectionName;842break;843}844845case wasm::WASM_SYMBOL_TYPE_TAG: {846Info.ElementIndex = readVaruint32(Ctx);847if (!isValidTagIndex(Info.ElementIndex) ||848IsDefined != isDefinedTagIndex(Info.ElementIndex))849return make_error<GenericBinaryError>("invalid tag symbol index",850object_error::parse_failed);851if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==852wasm::WASM_SYMBOL_BINDING_WEAK)853return make_error<GenericBinaryError>("undefined weak global symbol",854object_error::parse_failed);855if (IsDefined) {856Info.Name = readString(Ctx);857unsigned TagIndex = Info.ElementIndex - NumImportedTags;858wasm::WasmTag &Tag = Tags[TagIndex];859Signature = &Signatures[Tag.SigIndex];860if (Tag.SymbolName.empty())861Tag.SymbolName = Info.Name;862863} else {864wasm::WasmImport &Import = *ImportedTags[Info.ElementIndex];865if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {866Info.Name = readString(Ctx);867Info.ImportName = Import.Field;868} else {869Info.Name = Import.Field;870}871Signature = &Signatures[Import.SigIndex];872Info.ImportModule = Import.Module;873}874break;875}876877default:878return make_error<GenericBinaryError>("invalid symbol type: " +879Twine(unsigned(Info.Kind)),880object_error::parse_failed);881}882883if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=884wasm::WASM_SYMBOL_BINDING_LOCAL &&885!SymbolNames.insert(Info.Name).second)886return make_error<GenericBinaryError>("duplicate symbol name " +887Twine(Info.Name),888object_error::parse_failed);889Symbols.emplace_back(Info, GlobalType, TableType, Signature);890LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");891}892893return Error::success();894}895896Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {897uint32_t ComdatCount = readVaruint32(Ctx);898StringSet<> ComdatSet;899for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {900StringRef Name = readString(Ctx);901if (Name.empty() || !ComdatSet.insert(Name).second)902return make_error<GenericBinaryError>("bad/duplicate COMDAT name " +903Twine(Name),904object_error::parse_failed);905LinkingData.Comdats.emplace_back(Name);906uint32_t Flags = readVaruint32(Ctx);907if (Flags != 0)908return make_error<GenericBinaryError>("unsupported COMDAT flags",909object_error::parse_failed);910911uint32_t EntryCount = readVaruint32(Ctx);912while (EntryCount--) {913unsigned Kind = readVaruint32(Ctx);914unsigned Index = readVaruint32(Ctx);915switch (Kind) {916default:917return make_error<GenericBinaryError>("invalid COMDAT entry type",918object_error::parse_failed);919case wasm::WASM_COMDAT_DATA:920if (Index >= DataSegments.size())921return make_error<GenericBinaryError>(922"COMDAT data index out of range", object_error::parse_failed);923if (DataSegments[Index].Data.Comdat != UINT32_MAX)924return make_error<GenericBinaryError>("data segment in two COMDATs",925object_error::parse_failed);926DataSegments[Index].Data.Comdat = ComdatIndex;927break;928case wasm::WASM_COMDAT_FUNCTION:929if (!isDefinedFunctionIndex(Index))930return make_error<GenericBinaryError>(931"COMDAT function index out of range", object_error::parse_failed);932if (getDefinedFunction(Index).Comdat != UINT32_MAX)933return make_error<GenericBinaryError>("function in two COMDATs",934object_error::parse_failed);935getDefinedFunction(Index).Comdat = ComdatIndex;936break;937case wasm::WASM_COMDAT_SECTION:938if (Index >= Sections.size())939return make_error<GenericBinaryError>(940"COMDAT section index out of range", object_error::parse_failed);941if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM)942return make_error<GenericBinaryError>(943"non-custom section in a COMDAT", object_error::parse_failed);944Sections[Index].Comdat = ComdatIndex;945break;946}947}948}949return Error::success();950}951952Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) {953llvm::SmallSet<StringRef, 3> FieldsSeen;954uint32_t Fields = readVaruint32(Ctx);955for (size_t I = 0; I < Fields; ++I) {956StringRef FieldName = readString(Ctx);957if (!FieldsSeen.insert(FieldName).second)958return make_error<GenericBinaryError>(959"producers section does not have unique fields",960object_error::parse_failed);961std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr;962if (FieldName == "language") {963ProducerVec = &ProducerInfo.Languages;964} else if (FieldName == "processed-by") {965ProducerVec = &ProducerInfo.Tools;966} else if (FieldName == "sdk") {967ProducerVec = &ProducerInfo.SDKs;968} else {969return make_error<GenericBinaryError>(970"producers section field is not named one of language, processed-by, "971"or sdk",972object_error::parse_failed);973}974uint32_t ValueCount = readVaruint32(Ctx);975llvm::SmallSet<StringRef, 8> ProducersSeen;976for (size_t J = 0; J < ValueCount; ++J) {977StringRef Name = readString(Ctx);978StringRef Version = readString(Ctx);979if (!ProducersSeen.insert(Name).second) {980return make_error<GenericBinaryError>(981"producers section contains repeated producer",982object_error::parse_failed);983}984ProducerVec->emplace_back(std::string(Name), std::string(Version));985}986}987if (Ctx.Ptr != Ctx.End)988return make_error<GenericBinaryError>("producers section ended prematurely",989object_error::parse_failed);990return Error::success();991}992993Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) {994llvm::SmallSet<std::string, 8> FeaturesSeen;995uint32_t FeatureCount = readVaruint32(Ctx);996for (size_t I = 0; I < FeatureCount; ++I) {997wasm::WasmFeatureEntry Feature;998Feature.Prefix = readUint8(Ctx);999switch (Feature.Prefix) {1000case wasm::WASM_FEATURE_PREFIX_USED:1001case wasm::WASM_FEATURE_PREFIX_REQUIRED:1002case wasm::WASM_FEATURE_PREFIX_DISALLOWED:1003break;1004default:1005return make_error<GenericBinaryError>("unknown feature policy prefix",1006object_error::parse_failed);1007}1008Feature.Name = std::string(readString(Ctx));1009if (!FeaturesSeen.insert(Feature.Name).second)1010return make_error<GenericBinaryError>(1011"target features section contains repeated feature \"" +1012Feature.Name + "\"",1013object_error::parse_failed);1014TargetFeatures.push_back(Feature);1015}1016if (Ctx.Ptr != Ctx.End)1017return make_error<GenericBinaryError>(1018"target features section ended prematurely",1019object_error::parse_failed);1020return Error::success();1021}10221023Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {1024uint32_t SectionIndex = readVaruint32(Ctx);1025if (SectionIndex >= Sections.size())1026return make_error<GenericBinaryError>("invalid section index",1027object_error::parse_failed);1028WasmSection &Section = Sections[SectionIndex];1029uint32_t RelocCount = readVaruint32(Ctx);1030uint32_t EndOffset = Section.Content.size();1031uint32_t PreviousOffset = 0;1032while (RelocCount--) {1033wasm::WasmRelocation Reloc = {};1034uint32_t type = readVaruint32(Ctx);1035Reloc.Type = type;1036Reloc.Offset = readVaruint32(Ctx);1037if (Reloc.Offset < PreviousOffset)1038return make_error<GenericBinaryError>("relocations not in offset order",1039object_error::parse_failed);10401041auto badReloc = [&](StringRef msg) {1042return make_error<GenericBinaryError>(1043msg + ": " + Twine(Symbols[Reloc.Index].Info.Name),1044object_error::parse_failed);1045};10461047PreviousOffset = Reloc.Offset;1048Reloc.Index = readVaruint32(Ctx);1049switch (type) {1050case wasm::R_WASM_FUNCTION_INDEX_LEB:1051case wasm::R_WASM_FUNCTION_INDEX_I32:1052case wasm::R_WASM_TABLE_INDEX_SLEB:1053case wasm::R_WASM_TABLE_INDEX_SLEB64:1054case wasm::R_WASM_TABLE_INDEX_I32:1055case wasm::R_WASM_TABLE_INDEX_I64:1056case wasm::R_WASM_TABLE_INDEX_REL_SLEB:1057case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:1058if (!isValidFunctionSymbol(Reloc.Index))1059return badReloc("invalid function relocation");1060break;1061case wasm::R_WASM_TABLE_NUMBER_LEB:1062if (!isValidTableSymbol(Reloc.Index))1063return badReloc("invalid table relocation");1064break;1065case wasm::R_WASM_TYPE_INDEX_LEB:1066if (Reloc.Index >= Signatures.size())1067return badReloc("invalid relocation type index");1068break;1069case wasm::R_WASM_GLOBAL_INDEX_LEB:1070// R_WASM_GLOBAL_INDEX_LEB are can be used against function and data1071// symbols to refer to their GOT entries.1072if (!isValidGlobalSymbol(Reloc.Index) &&1073!isValidDataSymbol(Reloc.Index) &&1074!isValidFunctionSymbol(Reloc.Index))1075return badReloc("invalid global relocation");1076break;1077case wasm::R_WASM_GLOBAL_INDEX_I32:1078if (!isValidGlobalSymbol(Reloc.Index))1079return badReloc("invalid global relocation");1080break;1081case wasm::R_WASM_TAG_INDEX_LEB:1082if (!isValidTagSymbol(Reloc.Index))1083return badReloc("invalid tag relocation");1084break;1085case wasm::R_WASM_MEMORY_ADDR_LEB:1086case wasm::R_WASM_MEMORY_ADDR_SLEB:1087case wasm::R_WASM_MEMORY_ADDR_I32:1088case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:1089case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:1090case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:1091if (!isValidDataSymbol(Reloc.Index))1092return badReloc("invalid data relocation");1093Reloc.Addend = readVarint32(Ctx);1094break;1095case wasm::R_WASM_MEMORY_ADDR_LEB64:1096case wasm::R_WASM_MEMORY_ADDR_SLEB64:1097case wasm::R_WASM_MEMORY_ADDR_I64:1098case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:1099case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:1100if (!isValidDataSymbol(Reloc.Index))1101return badReloc("invalid data relocation");1102Reloc.Addend = readVarint64(Ctx);1103break;1104case wasm::R_WASM_FUNCTION_OFFSET_I32:1105if (!isValidFunctionSymbol(Reloc.Index))1106return badReloc("invalid function relocation");1107Reloc.Addend = readVarint32(Ctx);1108break;1109case wasm::R_WASM_FUNCTION_OFFSET_I64:1110if (!isValidFunctionSymbol(Reloc.Index))1111return badReloc("invalid function relocation");1112Reloc.Addend = readVarint64(Ctx);1113break;1114case wasm::R_WASM_SECTION_OFFSET_I32:1115if (!isValidSectionSymbol(Reloc.Index))1116return badReloc("invalid section relocation");1117Reloc.Addend = readVarint32(Ctx);1118break;1119default:1120return make_error<GenericBinaryError>("invalid relocation type: " +1121Twine(type),1122object_error::parse_failed);1123}11241125// Relocations must fit inside the section, and must appear in order. They1126// also shouldn't overlap a function/element boundary, but we don't bother1127// to check that.1128uint64_t Size = 5;1129if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 ||1130Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 ||1131Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64)1132Size = 10;1133if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 ||1134Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 ||1135Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LOCREL_I32 ||1136Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 ||1137Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||1138Reloc.Type == wasm::R_WASM_FUNCTION_INDEX_I32 ||1139Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32)1140Size = 4;1141if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 ||1142Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 ||1143Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64)1144Size = 8;1145if (Reloc.Offset + Size > EndOffset)1146return make_error<GenericBinaryError>("invalid relocation offset",1147object_error::parse_failed);11481149Section.Relocations.push_back(Reloc);1150}1151if (Ctx.Ptr != Ctx.End)1152return make_error<GenericBinaryError>("reloc section ended prematurely",1153object_error::parse_failed);1154return Error::success();1155}11561157Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {1158if (Sec.Name == "dylink") {1159if (Error Err = parseDylinkSection(Ctx))1160return Err;1161} else if (Sec.Name == "dylink.0") {1162if (Error Err = parseDylink0Section(Ctx))1163return Err;1164} else if (Sec.Name == "name") {1165if (Error Err = parseNameSection(Ctx))1166return Err;1167} else if (Sec.Name == "linking") {1168if (Error Err = parseLinkingSection(Ctx))1169return Err;1170} else if (Sec.Name == "producers") {1171if (Error Err = parseProducersSection(Ctx))1172return Err;1173} else if (Sec.Name == "target_features") {1174if (Error Err = parseTargetFeaturesSection(Ctx))1175return Err;1176} else if (Sec.Name.starts_with("reloc.")) {1177if (Error Err = parseRelocSection(Sec.Name, Ctx))1178return Err;1179}1180return Error::success();1181}11821183Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {1184auto parseFieldDef = [&]() {1185uint32_t TypeCode = readVaruint32((Ctx));1186/* Discard StorageType */ parseValType(Ctx, TypeCode);1187/* Discard Mutability */ readVaruint32(Ctx);1188};11891190uint32_t Count = readVaruint32(Ctx);1191Signatures.reserve(Count);1192while (Count--) {1193wasm::WasmSignature Sig;1194uint8_t Form = readUint8(Ctx);1195if (Form == wasm::WASM_TYPE_REC) {1196// Rec groups expand the type index space (beyond what was declared at1197// the top of the section, and also consume one element in that space.1198uint32_t RecSize = readVaruint32(Ctx);1199if (RecSize == 0)1200return make_error<GenericBinaryError>("Rec group size cannot be 0",1201object_error::parse_failed);1202Signatures.reserve(Signatures.size() + RecSize);1203Count += RecSize;1204Sig.Kind = wasm::WasmSignature::Placeholder;1205Signatures.push_back(std::move(Sig));1206HasUnmodeledTypes = true;1207continue;1208}1209if (Form != wasm::WASM_TYPE_FUNC) {1210// Currently LLVM only models function types, and not other composite1211// types. Here we parse the type declarations just enough to skip past1212// them in the binary.1213if (Form == wasm::WASM_TYPE_SUB || Form == wasm::WASM_TYPE_SUB_FINAL) {1214uint32_t Supers = readVaruint32(Ctx);1215if (Supers > 0) {1216if (Supers != 1)1217return make_error<GenericBinaryError>(1218"Invalid number of supertypes", object_error::parse_failed);1219/* Discard SuperIndex */ readVaruint32(Ctx);1220}1221Form = readVaruint32(Ctx);1222}1223if (Form == wasm::WASM_TYPE_STRUCT) {1224uint32_t FieldCount = readVaruint32(Ctx);1225while (FieldCount--) {1226parseFieldDef();1227}1228} else if (Form == wasm::WASM_TYPE_ARRAY) {1229parseFieldDef();1230} else {1231return make_error<GenericBinaryError>("bad form",1232object_error::parse_failed);1233}1234Sig.Kind = wasm::WasmSignature::Placeholder;1235Signatures.push_back(std::move(Sig));1236HasUnmodeledTypes = true;1237continue;1238}12391240uint32_t ParamCount = readVaruint32(Ctx);1241Sig.Params.reserve(ParamCount);1242while (ParamCount--) {1243uint32_t ParamType = readUint8(Ctx);1244Sig.Params.push_back(parseValType(Ctx, ParamType));1245continue;1246}1247uint32_t ReturnCount = readVaruint32(Ctx);1248while (ReturnCount--) {1249uint32_t ReturnType = readUint8(Ctx);1250Sig.Returns.push_back(parseValType(Ctx, ReturnType));1251}12521253Signatures.push_back(std::move(Sig));1254}1255if (Ctx.Ptr != Ctx.End)1256return make_error<GenericBinaryError>("type section ended prematurely",1257object_error::parse_failed);1258return Error::success();1259}12601261Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {1262uint32_t Count = readVaruint32(Ctx);1263uint32_t NumTypes = Signatures.size();1264Imports.reserve(Count);1265for (uint32_t I = 0; I < Count; I++) {1266wasm::WasmImport Im;1267Im.Module = readString(Ctx);1268Im.Field = readString(Ctx);1269Im.Kind = readUint8(Ctx);1270switch (Im.Kind) {1271case wasm::WASM_EXTERNAL_FUNCTION:1272NumImportedFunctions++;1273Im.SigIndex = readVaruint32(Ctx);1274if (Im.SigIndex >= NumTypes)1275return make_error<GenericBinaryError>("invalid function type",1276object_error::parse_failed);1277break;1278case wasm::WASM_EXTERNAL_GLOBAL:1279NumImportedGlobals++;1280Im.Global.Type = readUint8(Ctx);1281Im.Global.Mutable = readVaruint1(Ctx);1282break;1283case wasm::WASM_EXTERNAL_MEMORY:1284Im.Memory = readLimits(Ctx);1285if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)1286HasMemory64 = true;1287break;1288case wasm::WASM_EXTERNAL_TABLE: {1289Im.Table = readTableType(Ctx);1290NumImportedTables++;1291auto ElemType = Im.Table.ElemType;1292if (ElemType != wasm::ValType::FUNCREF &&1293ElemType != wasm::ValType::EXTERNREF &&1294ElemType != wasm::ValType::EXNREF &&1295ElemType != wasm::ValType::OTHERREF)1296return make_error<GenericBinaryError>("invalid table element type",1297object_error::parse_failed);1298break;1299}1300case wasm::WASM_EXTERNAL_TAG:1301NumImportedTags++;1302if (readUint8(Ctx) != 0) // Reserved 'attribute' field1303return make_error<GenericBinaryError>("invalid attribute",1304object_error::parse_failed);1305Im.SigIndex = readVaruint32(Ctx);1306if (Im.SigIndex >= NumTypes)1307return make_error<GenericBinaryError>("invalid tag type",1308object_error::parse_failed);1309break;1310default:1311return make_error<GenericBinaryError>("unexpected import kind",1312object_error::parse_failed);1313}1314Imports.push_back(Im);1315}1316if (Ctx.Ptr != Ctx.End)1317return make_error<GenericBinaryError>("import section ended prematurely",1318object_error::parse_failed);1319return Error::success();1320}13211322Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {1323uint32_t Count = readVaruint32(Ctx);1324Functions.reserve(Count);1325uint32_t NumTypes = Signatures.size();1326while (Count--) {1327uint32_t Type = readVaruint32(Ctx);1328if (Type >= NumTypes)1329return make_error<GenericBinaryError>("invalid function type",1330object_error::parse_failed);1331wasm::WasmFunction F;1332F.SigIndex = Type;1333Functions.push_back(F);1334}1335if (Ctx.Ptr != Ctx.End)1336return make_error<GenericBinaryError>("function section ended prematurely",1337object_error::parse_failed);1338return Error::success();1339}13401341Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {1342TableSection = Sections.size();1343uint32_t Count = readVaruint32(Ctx);1344Tables.reserve(Count);1345while (Count--) {1346wasm::WasmTable T;1347T.Type = readTableType(Ctx);1348T.Index = NumImportedTables + Tables.size();1349Tables.push_back(T);1350auto ElemType = Tables.back().Type.ElemType;1351if (ElemType != wasm::ValType::FUNCREF &&1352ElemType != wasm::ValType::EXTERNREF &&1353ElemType != wasm::ValType::EXNREF &&1354ElemType != wasm::ValType::OTHERREF) {1355return make_error<GenericBinaryError>("invalid table element type",1356object_error::parse_failed);1357}1358}1359if (Ctx.Ptr != Ctx.End)1360return make_error<GenericBinaryError>("table section ended prematurely",1361object_error::parse_failed);1362return Error::success();1363}13641365Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {1366uint32_t Count = readVaruint32(Ctx);1367Memories.reserve(Count);1368while (Count--) {1369auto Limits = readLimits(Ctx);1370if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)1371HasMemory64 = true;1372Memories.push_back(Limits);1373}1374if (Ctx.Ptr != Ctx.End)1375return make_error<GenericBinaryError>("memory section ended prematurely",1376object_error::parse_failed);1377return Error::success();1378}13791380Error WasmObjectFile::parseTagSection(ReadContext &Ctx) {1381TagSection = Sections.size();1382uint32_t Count = readVaruint32(Ctx);1383Tags.reserve(Count);1384uint32_t NumTypes = Signatures.size();1385while (Count--) {1386if (readUint8(Ctx) != 0) // Reserved 'attribute' field1387return make_error<GenericBinaryError>("invalid attribute",1388object_error::parse_failed);1389uint32_t Type = readVaruint32(Ctx);1390if (Type >= NumTypes)1391return make_error<GenericBinaryError>("invalid tag type",1392object_error::parse_failed);1393wasm::WasmTag Tag;1394Tag.Index = NumImportedTags + Tags.size();1395Tag.SigIndex = Type;1396Signatures[Type].Kind = wasm::WasmSignature::Tag;1397Tags.push_back(Tag);1398}13991400if (Ctx.Ptr != Ctx.End)1401return make_error<GenericBinaryError>("tag section ended prematurely",1402object_error::parse_failed);1403return Error::success();1404}14051406Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {1407GlobalSection = Sections.size();1408const uint8_t *SectionStart = Ctx.Ptr;1409uint32_t Count = readVaruint32(Ctx);1410Globals.reserve(Count);1411while (Count--) {1412wasm::WasmGlobal Global;1413Global.Index = NumImportedGlobals + Globals.size();1414const uint8_t *GlobalStart = Ctx.Ptr;1415Global.Offset = static_cast<uint32_t>(GlobalStart - SectionStart);1416auto GlobalOpcode = readVaruint32(Ctx);1417Global.Type.Type = (uint8_t)parseValType(Ctx, GlobalOpcode);1418Global.Type.Mutable = readVaruint1(Ctx);1419if (Error Err = readInitExpr(Global.InitExpr, Ctx))1420return Err;1421Global.Size = static_cast<uint32_t>(Ctx.Ptr - GlobalStart);1422Globals.push_back(Global);1423}1424if (Ctx.Ptr != Ctx.End)1425return make_error<GenericBinaryError>("global section ended prematurely",1426object_error::parse_failed);1427return Error::success();1428}14291430Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {1431uint32_t Count = readVaruint32(Ctx);1432Exports.reserve(Count);1433Symbols.reserve(Count);1434for (uint32_t I = 0; I < Count; I++) {1435wasm::WasmExport Ex;1436Ex.Name = readString(Ctx);1437Ex.Kind = readUint8(Ctx);1438Ex.Index = readVaruint32(Ctx);1439const wasm::WasmSignature *Signature = nullptr;1440const wasm::WasmGlobalType *GlobalType = nullptr;1441const wasm::WasmTableType *TableType = nullptr;1442wasm::WasmSymbolInfo Info;1443Info.Name = Ex.Name;1444Info.Flags = 0;1445switch (Ex.Kind) {1446case wasm::WASM_EXTERNAL_FUNCTION: {1447if (!isDefinedFunctionIndex(Ex.Index))1448return make_error<GenericBinaryError>("invalid function export",1449object_error::parse_failed);1450getDefinedFunction(Ex.Index).ExportName = Ex.Name;1451Info.Kind = wasm::WASM_SYMBOL_TYPE_FUNCTION;1452Info.ElementIndex = Ex.Index;1453unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;1454wasm::WasmFunction &Function = Functions[FuncIndex];1455Signature = &Signatures[Function.SigIndex];1456break;1457}1458case wasm::WASM_EXTERNAL_GLOBAL: {1459if (!isValidGlobalIndex(Ex.Index))1460return make_error<GenericBinaryError>("invalid global export",1461object_error::parse_failed);1462Info.Kind = wasm::WASM_SYMBOL_TYPE_DATA;1463uint64_t Offset = 0;1464if (isDefinedGlobalIndex(Ex.Index)) {1465auto Global = getDefinedGlobal(Ex.Index);1466if (!Global.InitExpr.Extended) {1467auto Inst = Global.InitExpr.Inst;1468if (Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) {1469Offset = Inst.Value.Int32;1470} else if (Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) {1471Offset = Inst.Value.Int64;1472}1473}1474}1475Info.DataRef = wasm::WasmDataReference{0, Offset, 0};1476break;1477}1478case wasm::WASM_EXTERNAL_TAG:1479if (!isValidTagIndex(Ex.Index))1480return make_error<GenericBinaryError>("invalid tag export",1481object_error::parse_failed);1482Info.Kind = wasm::WASM_SYMBOL_TYPE_TAG;1483Info.ElementIndex = Ex.Index;1484break;1485case wasm::WASM_EXTERNAL_MEMORY:1486break;1487case wasm::WASM_EXTERNAL_TABLE:1488Info.Kind = wasm::WASM_SYMBOL_TYPE_TABLE;1489Info.ElementIndex = Ex.Index;1490break;1491default:1492return make_error<GenericBinaryError>("unexpected export kind",1493object_error::parse_failed);1494}1495Exports.push_back(Ex);1496if (Ex.Kind != wasm::WASM_EXTERNAL_MEMORY) {1497Symbols.emplace_back(Info, GlobalType, TableType, Signature);1498LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");1499}1500}1501if (Ctx.Ptr != Ctx.End)1502return make_error<GenericBinaryError>("export section ended prematurely",1503object_error::parse_failed);1504return Error::success();1505}15061507bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {1508return Index < NumImportedFunctions + Functions.size();1509}15101511bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {1512return Index >= NumImportedFunctions && isValidFunctionIndex(Index);1513}15141515bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {1516return Index < NumImportedGlobals + Globals.size();1517}15181519bool WasmObjectFile::isValidTableNumber(uint32_t Index) const {1520return Index < NumImportedTables + Tables.size();1521}15221523bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {1524return Index >= NumImportedGlobals && isValidGlobalIndex(Index);1525}15261527bool WasmObjectFile::isDefinedTableNumber(uint32_t Index) const {1528return Index >= NumImportedTables && isValidTableNumber(Index);1529}15301531bool WasmObjectFile::isValidTagIndex(uint32_t Index) const {1532return Index < NumImportedTags + Tags.size();1533}15341535bool WasmObjectFile::isDefinedTagIndex(uint32_t Index) const {1536return Index >= NumImportedTags && isValidTagIndex(Index);1537}15381539bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {1540return Index < Symbols.size() && Symbols[Index].isTypeFunction();1541}15421543bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const {1544return Index < Symbols.size() && Symbols[Index].isTypeTable();1545}15461547bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {1548return Index < Symbols.size() && Symbols[Index].isTypeGlobal();1549}15501551bool WasmObjectFile::isValidTagSymbol(uint32_t Index) const {1552return Index < Symbols.size() && Symbols[Index].isTypeTag();1553}15541555bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {1556return Index < Symbols.size() && Symbols[Index].isTypeData();1557}15581559bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {1560return Index < Symbols.size() && Symbols[Index].isTypeSection();1561}15621563wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {1564assert(isDefinedFunctionIndex(Index));1565return Functions[Index - NumImportedFunctions];1566}15671568const wasm::WasmFunction &1569WasmObjectFile::getDefinedFunction(uint32_t Index) const {1570assert(isDefinedFunctionIndex(Index));1571return Functions[Index - NumImportedFunctions];1572}15731574const wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) const {1575assert(isDefinedGlobalIndex(Index));1576return Globals[Index - NumImportedGlobals];1577}15781579wasm::WasmTag &WasmObjectFile::getDefinedTag(uint32_t Index) {1580assert(isDefinedTagIndex(Index));1581return Tags[Index - NumImportedTags];1582}15831584Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {1585StartFunction = readVaruint32(Ctx);1586if (!isValidFunctionIndex(StartFunction))1587return make_error<GenericBinaryError>("invalid start function",1588object_error::parse_failed);1589return Error::success();1590}15911592Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {1593CodeSection = Sections.size();1594uint32_t FunctionCount = readVaruint32(Ctx);1595if (FunctionCount != Functions.size()) {1596return make_error<GenericBinaryError>("invalid function count",1597object_error::parse_failed);1598}15991600for (uint32_t i = 0; i < FunctionCount; i++) {1601wasm::WasmFunction& Function = Functions[i];1602const uint8_t *FunctionStart = Ctx.Ptr;1603uint32_t Size = readVaruint32(Ctx);1604const uint8_t *FunctionEnd = Ctx.Ptr + Size;16051606Function.CodeOffset = Ctx.Ptr - FunctionStart;1607Function.Index = NumImportedFunctions + i;1608Function.CodeSectionOffset = FunctionStart - Ctx.Start;1609Function.Size = FunctionEnd - FunctionStart;16101611uint32_t NumLocalDecls = readVaruint32(Ctx);1612Function.Locals.reserve(NumLocalDecls);1613while (NumLocalDecls--) {1614wasm::WasmLocalDecl Decl;1615Decl.Count = readVaruint32(Ctx);1616Decl.Type = readUint8(Ctx);1617Function.Locals.push_back(Decl);1618}16191620uint32_t BodySize = FunctionEnd - Ctx.Ptr;1621// Ensure that Function is within Ctx's buffer.1622if (Ctx.Ptr + BodySize > Ctx.End) {1623return make_error<GenericBinaryError>("Function extends beyond buffer",1624object_error::parse_failed);1625}1626Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);1627// This will be set later when reading in the linking metadata section.1628Function.Comdat = UINT32_MAX;1629Ctx.Ptr += BodySize;1630assert(Ctx.Ptr == FunctionEnd);1631}1632if (Ctx.Ptr != Ctx.End)1633return make_error<GenericBinaryError>("code section ended prematurely",1634object_error::parse_failed);1635return Error::success();1636}16371638Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {1639uint32_t Count = readVaruint32(Ctx);1640ElemSegments.reserve(Count);1641while (Count--) {1642wasm::WasmElemSegment Segment;1643Segment.Flags = readVaruint32(Ctx);16441645uint32_t SupportedFlags = wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER |1646wasm::WASM_ELEM_SEGMENT_IS_PASSIVE |1647wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS;1648if (Segment.Flags & ~SupportedFlags)1649return make_error<GenericBinaryError>(1650"Unsupported flags for element segment", object_error::parse_failed);16511652bool IsPassive = (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_PASSIVE) != 0;1653bool IsDeclarative =1654IsPassive && (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_DECLARATIVE);1655bool HasTableNumber =1656!IsPassive &&1657(Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER);1658bool HasInitExprs =1659(Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS);1660bool HasElemKind =1661(Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) &&1662!HasInitExprs;16631664if (HasTableNumber)1665Segment.TableNumber = readVaruint32(Ctx);1666else1667Segment.TableNumber = 0;16681669if (!isValidTableNumber(Segment.TableNumber))1670return make_error<GenericBinaryError>("invalid TableNumber",1671object_error::parse_failed);16721673if (IsPassive || IsDeclarative) {1674Segment.Offset.Extended = false;1675Segment.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;1676Segment.Offset.Inst.Value.Int32 = 0;1677} else {1678if (Error Err = readInitExpr(Segment.Offset, Ctx))1679return Err;1680}16811682if (HasElemKind) {1683auto ElemKind = readVaruint32(Ctx);1684if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) {1685Segment.ElemKind = parseValType(Ctx, ElemKind);1686if (Segment.ElemKind != wasm::ValType::FUNCREF &&1687Segment.ElemKind != wasm::ValType::EXTERNREF &&1688Segment.ElemKind != wasm::ValType::EXNREF &&1689Segment.ElemKind != wasm::ValType::OTHERREF) {1690return make_error<GenericBinaryError>("invalid elem type",1691object_error::parse_failed);1692}1693} else {1694if (ElemKind != 0)1695return make_error<GenericBinaryError>("invalid elem type",1696object_error::parse_failed);1697Segment.ElemKind = wasm::ValType::FUNCREF;1698}1699} else if (HasInitExprs) {1700auto ElemType = parseValType(Ctx, readVaruint32(Ctx));1701Segment.ElemKind = ElemType;1702} else {1703Segment.ElemKind = wasm::ValType::FUNCREF;1704}17051706uint32_t NumElems = readVaruint32(Ctx);17071708if (HasInitExprs) {1709while (NumElems--) {1710wasm::WasmInitExpr Expr;1711if (Error Err = readInitExpr(Expr, Ctx))1712return Err;1713}1714} else {1715while (NumElems--) {1716Segment.Functions.push_back(readVaruint32(Ctx));1717}1718}1719ElemSegments.push_back(Segment);1720}1721if (Ctx.Ptr != Ctx.End)1722return make_error<GenericBinaryError>("elem section ended prematurely",1723object_error::parse_failed);1724return Error::success();1725}17261727Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {1728DataSection = Sections.size();1729uint32_t Count = readVaruint32(Ctx);1730if (DataCount && Count != *DataCount)1731return make_error<GenericBinaryError>(1732"number of data segments does not match DataCount section");1733DataSegments.reserve(Count);1734while (Count--) {1735WasmSegment Segment;1736Segment.Data.InitFlags = readVaruint32(Ctx);1737Segment.Data.MemoryIndex =1738(Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)1739? readVaruint32(Ctx)1740: 0;1741if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {1742if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))1743return Err;1744} else {1745Segment.Data.Offset.Extended = false;1746Segment.Data.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;1747Segment.Data.Offset.Inst.Value.Int32 = 0;1748}1749uint32_t Size = readVaruint32(Ctx);1750if (Size > (size_t)(Ctx.End - Ctx.Ptr))1751return make_error<GenericBinaryError>("invalid segment size",1752object_error::parse_failed);1753Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);1754// The rest of these Data fields are set later, when reading in the linking1755// metadata section.1756Segment.Data.Alignment = 0;1757Segment.Data.LinkingFlags = 0;1758Segment.Data.Comdat = UINT32_MAX;1759Segment.SectionOffset = Ctx.Ptr - Ctx.Start;1760Ctx.Ptr += Size;1761DataSegments.push_back(Segment);1762}1763if (Ctx.Ptr != Ctx.End)1764return make_error<GenericBinaryError>("data section ended prematurely",1765object_error::parse_failed);1766return Error::success();1767}17681769Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {1770DataCount = readVaruint32(Ctx);1771return Error::success();1772}17731774const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {1775return Header;1776}17771778void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }17791780Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {1781uint32_t Result = SymbolRef::SF_None;1782const WasmSymbol &Sym = getWasmSymbol(Symb);17831784LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");1785if (Sym.isBindingWeak())1786Result |= SymbolRef::SF_Weak;1787if (!Sym.isBindingLocal())1788Result |= SymbolRef::SF_Global;1789if (Sym.isHidden())1790Result |= SymbolRef::SF_Hidden;1791if (!Sym.isDefined())1792Result |= SymbolRef::SF_Undefined;1793if (Sym.isTypeFunction())1794Result |= SymbolRef::SF_Executable;1795return Result;1796}17971798basic_symbol_iterator WasmObjectFile::symbol_begin() const {1799DataRefImpl Ref;1800Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null1801Ref.d.b = 0; // Symbol index1802return BasicSymbolRef(Ref, this);1803}18041805basic_symbol_iterator WasmObjectFile::symbol_end() const {1806DataRefImpl Ref;1807Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null1808Ref.d.b = Symbols.size(); // Symbol index1809return BasicSymbolRef(Ref, this);1810}18111812const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {1813return Symbols[Symb.d.b];1814}18151816const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {1817return getWasmSymbol(Symb.getRawDataRefImpl());1818}18191820Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {1821return getWasmSymbol(Symb).Info.Name;1822}18231824Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {1825auto &Sym = getWasmSymbol(Symb);1826if (!Sym.isDefined())1827return 0;1828Expected<section_iterator> Sec = getSymbolSection(Symb);1829if (!Sec)1830return Sec.takeError();1831uint32_t SectionAddress = getSectionAddress(Sec.get()->getRawDataRefImpl());1832if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&1833isDefinedFunctionIndex(Sym.Info.ElementIndex)) {1834return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset +1835SectionAddress;1836}1837if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_GLOBAL &&1838isDefinedGlobalIndex(Sym.Info.ElementIndex)) {1839return getDefinedGlobal(Sym.Info.ElementIndex).Offset + SectionAddress;1840}18411842return getSymbolValue(Symb);1843}18441845uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {1846switch (Sym.Info.Kind) {1847case wasm::WASM_SYMBOL_TYPE_FUNCTION:1848case wasm::WASM_SYMBOL_TYPE_GLOBAL:1849case wasm::WASM_SYMBOL_TYPE_TAG:1850case wasm::WASM_SYMBOL_TYPE_TABLE:1851return Sym.Info.ElementIndex;1852case wasm::WASM_SYMBOL_TYPE_DATA: {1853// The value of a data symbol is the segment offset, plus the symbol1854// offset within the segment.1855uint32_t SegmentIndex = Sym.Info.DataRef.Segment;1856const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;1857if (Segment.Offset.Extended) {1858llvm_unreachable("extended init exprs not supported");1859} else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) {1860return Segment.Offset.Inst.Value.Int32 + Sym.Info.DataRef.Offset;1861} else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) {1862return Segment.Offset.Inst.Value.Int64 + Sym.Info.DataRef.Offset;1863} else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_GLOBAL_GET) {1864return Sym.Info.DataRef.Offset;1865} else {1866llvm_unreachable("unknown init expr opcode");1867}1868}1869case wasm::WASM_SYMBOL_TYPE_SECTION:1870return 0;1871}1872llvm_unreachable("invalid symbol type");1873}18741875uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {1876return getWasmSymbolValue(getWasmSymbol(Symb));1877}18781879uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {1880llvm_unreachable("not yet implemented");1881return 0;1882}18831884uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {1885llvm_unreachable("not yet implemented");1886return 0;1887}18881889Expected<SymbolRef::Type>1890WasmObjectFile::getSymbolType(DataRefImpl Symb) const {1891const WasmSymbol &Sym = getWasmSymbol(Symb);18921893switch (Sym.Info.Kind) {1894case wasm::WASM_SYMBOL_TYPE_FUNCTION:1895return SymbolRef::ST_Function;1896case wasm::WASM_SYMBOL_TYPE_GLOBAL:1897return SymbolRef::ST_Other;1898case wasm::WASM_SYMBOL_TYPE_DATA:1899return SymbolRef::ST_Data;1900case wasm::WASM_SYMBOL_TYPE_SECTION:1901return SymbolRef::ST_Debug;1902case wasm::WASM_SYMBOL_TYPE_TAG:1903return SymbolRef::ST_Other;1904case wasm::WASM_SYMBOL_TYPE_TABLE:1905return SymbolRef::ST_Other;1906}19071908llvm_unreachable("unknown WasmSymbol::SymbolType");1909return SymbolRef::ST_Other;1910}19111912Expected<section_iterator>1913WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {1914const WasmSymbol &Sym = getWasmSymbol(Symb);1915if (Sym.isUndefined())1916return section_end();19171918DataRefImpl Ref;1919Ref.d.a = getSymbolSectionIdImpl(Sym);1920return section_iterator(SectionRef(Ref, this));1921}19221923uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {1924const WasmSymbol &Sym = getWasmSymbol(Symb);1925return getSymbolSectionIdImpl(Sym);1926}19271928uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {1929switch (Sym.Info.Kind) {1930case wasm::WASM_SYMBOL_TYPE_FUNCTION:1931return CodeSection;1932case wasm::WASM_SYMBOL_TYPE_GLOBAL:1933return GlobalSection;1934case wasm::WASM_SYMBOL_TYPE_DATA:1935return DataSection;1936case wasm::WASM_SYMBOL_TYPE_SECTION:1937return Sym.Info.ElementIndex;1938case wasm::WASM_SYMBOL_TYPE_TAG:1939return TagSection;1940case wasm::WASM_SYMBOL_TYPE_TABLE:1941return TableSection;1942default:1943llvm_unreachable("unknown WasmSymbol::SymbolType");1944}1945}19461947uint32_t WasmObjectFile::getSymbolSize(SymbolRef Symb) const {1948const WasmSymbol &Sym = getWasmSymbol(Symb);1949if (!Sym.isDefined())1950return 0;1951if (Sym.isTypeGlobal())1952return getDefinedGlobal(Sym.Info.ElementIndex).Size;1953if (Sym.isTypeData())1954return Sym.Info.DataRef.Size;1955if (Sym.isTypeFunction())1956return functions()[Sym.Info.ElementIndex - getNumImportedFunctions()].Size;1957// Currently symbol size is only tracked for data segments and functions. In1958// principle we could also track size (e.g. binary size) for tables, globals1959// and element segments etc too.1960return 0;1961}19621963void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }19641965Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {1966const WasmSection &S = Sections[Sec.d.a];1967if (S.Type == wasm::WASM_SEC_CUSTOM)1968return S.Name;1969if (S.Type > wasm::WASM_SEC_LAST_KNOWN)1970return createStringError(object_error::invalid_section_index, "");1971return wasm::sectionTypeToString(S.Type);1972}19731974uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const {1975// For object files, use 0 for section addresses, and section offsets for1976// symbol addresses. For linked files, use file offsets.1977// See also getSymbolAddress.1978return isRelocatableObject() || isSharedObject() ? 01979: Sections[Sec.d.a].Offset;1980}19811982uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {1983return Sec.d.a;1984}19851986uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {1987const WasmSection &S = Sections[Sec.d.a];1988return S.Content.size();1989}19901991Expected<ArrayRef<uint8_t>>1992WasmObjectFile::getSectionContents(DataRefImpl Sec) const {1993const WasmSection &S = Sections[Sec.d.a];1994// This will never fail since wasm sections can never be empty (user-sections1995// must have a name and non-user sections each have a defined structure).1996return S.Content;1997}19981999uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {2000return 1;2001}20022003bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {2004return false;2005}20062007bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {2008return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;2009}20102011bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {2012return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;2013}20142015bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }20162017bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }20182019relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {2020DataRefImpl RelocRef;2021RelocRef.d.a = Ref.d.a;2022RelocRef.d.b = 0;2023return relocation_iterator(RelocationRef(RelocRef, this));2024}20252026relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {2027const WasmSection &Sec = getWasmSection(Ref);2028DataRefImpl RelocRef;2029RelocRef.d.a = Ref.d.a;2030RelocRef.d.b = Sec.Relocations.size();2031return relocation_iterator(RelocationRef(RelocRef, this));2032}20332034void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }20352036uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {2037const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2038return Rel.Offset;2039}20402041symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {2042const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2043if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)2044return symbol_end();2045DataRefImpl Sym;2046Sym.d.a = 1;2047Sym.d.b = Rel.Index;2048return symbol_iterator(SymbolRef(Sym, this));2049}20502051uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {2052const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2053return Rel.Type;2054}20552056void WasmObjectFile::getRelocationTypeName(2057DataRefImpl Ref, SmallVectorImpl<char> &Result) const {2058const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2059StringRef Res = "Unknown";20602061#define WASM_RELOC(name, value) \2062case wasm::name: \2063Res = #name; \2064break;20652066switch (Rel.Type) {2067#include "llvm/BinaryFormat/WasmRelocs.def"2068}20692070#undef WASM_RELOC20712072Result.append(Res.begin(), Res.end());2073}20742075section_iterator WasmObjectFile::section_begin() const {2076DataRefImpl Ref;2077Ref.d.a = 0;2078return section_iterator(SectionRef(Ref, this));2079}20802081section_iterator WasmObjectFile::section_end() const {2082DataRefImpl Ref;2083Ref.d.a = Sections.size();2084return section_iterator(SectionRef(Ref, this));2085}20862087uint8_t WasmObjectFile::getBytesInAddress() const {2088return HasMemory64 ? 8 : 4;2089}20902091StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }20922093Triple::ArchType WasmObjectFile::getArch() const {2094return HasMemory64 ? Triple::wasm64 : Triple::wasm32;2095}20962097Expected<SubtargetFeatures> WasmObjectFile::getFeatures() const {2098return SubtargetFeatures();2099}21002101bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }21022103bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }21042105const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {2106assert(Ref.d.a < Sections.size());2107return Sections[Ref.d.a];2108}21092110const WasmSection &2111WasmObjectFile::getWasmSection(const SectionRef &Section) const {2112return getWasmSection(Section.getRawDataRefImpl());2113}21142115const wasm::WasmRelocation &2116WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {2117return getWasmRelocation(Ref.getRawDataRefImpl());2118}21192120const wasm::WasmRelocation &2121WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {2122assert(Ref.d.a < Sections.size());2123const WasmSection &Sec = Sections[Ref.d.a];2124assert(Ref.d.b < Sec.Relocations.size());2125return Sec.Relocations[Ref.d.b];2126}21272128int WasmSectionOrderChecker::getSectionOrder(unsigned ID,2129StringRef CustomSectionName) {2130switch (ID) {2131case wasm::WASM_SEC_CUSTOM:2132return StringSwitch<unsigned>(CustomSectionName)2133.Case("dylink", WASM_SEC_ORDER_DYLINK)2134.Case("dylink.0", WASM_SEC_ORDER_DYLINK)2135.Case("linking", WASM_SEC_ORDER_LINKING)2136.StartsWith("reloc.", WASM_SEC_ORDER_RELOC)2137.Case("name", WASM_SEC_ORDER_NAME)2138.Case("producers", WASM_SEC_ORDER_PRODUCERS)2139.Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)2140.Default(WASM_SEC_ORDER_NONE);2141case wasm::WASM_SEC_TYPE:2142return WASM_SEC_ORDER_TYPE;2143case wasm::WASM_SEC_IMPORT:2144return WASM_SEC_ORDER_IMPORT;2145case wasm::WASM_SEC_FUNCTION:2146return WASM_SEC_ORDER_FUNCTION;2147case wasm::WASM_SEC_TABLE:2148return WASM_SEC_ORDER_TABLE;2149case wasm::WASM_SEC_MEMORY:2150return WASM_SEC_ORDER_MEMORY;2151case wasm::WASM_SEC_GLOBAL:2152return WASM_SEC_ORDER_GLOBAL;2153case wasm::WASM_SEC_EXPORT:2154return WASM_SEC_ORDER_EXPORT;2155case wasm::WASM_SEC_START:2156return WASM_SEC_ORDER_START;2157case wasm::WASM_SEC_ELEM:2158return WASM_SEC_ORDER_ELEM;2159case wasm::WASM_SEC_CODE:2160return WASM_SEC_ORDER_CODE;2161case wasm::WASM_SEC_DATA:2162return WASM_SEC_ORDER_DATA;2163case wasm::WASM_SEC_DATACOUNT:2164return WASM_SEC_ORDER_DATACOUNT;2165case wasm::WASM_SEC_TAG:2166return WASM_SEC_ORDER_TAG;2167default:2168return WASM_SEC_ORDER_NONE;2169}2170}21712172// Represents the edges in a directed graph where any node B reachable from node2173// A is not allowed to appear before A in the section ordering, but may appear2174// afterward.2175int WasmSectionOrderChecker::DisallowedPredecessors2176[WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {2177// WASM_SEC_ORDER_NONE2178{},2179// WASM_SEC_ORDER_TYPE2180{WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},2181// WASM_SEC_ORDER_IMPORT2182{WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},2183// WASM_SEC_ORDER_FUNCTION2184{WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},2185// WASM_SEC_ORDER_TABLE2186{WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},2187// WASM_SEC_ORDER_MEMORY2188{WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_TAG},2189// WASM_SEC_ORDER_TAG2190{WASM_SEC_ORDER_TAG, WASM_SEC_ORDER_GLOBAL},2191// WASM_SEC_ORDER_GLOBAL2192{WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},2193// WASM_SEC_ORDER_EXPORT2194{WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},2195// WASM_SEC_ORDER_START2196{WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},2197// WASM_SEC_ORDER_ELEM2198{WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},2199// WASM_SEC_ORDER_DATACOUNT2200{WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},2201// WASM_SEC_ORDER_CODE2202{WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},2203// WASM_SEC_ORDER_DATA2204{WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},22052206// Custom Sections2207// WASM_SEC_ORDER_DYLINK2208{WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},2209// WASM_SEC_ORDER_LINKING2210{WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},2211// WASM_SEC_ORDER_RELOC (can be repeated)2212{},2213// WASM_SEC_ORDER_NAME2214{WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},2215// WASM_SEC_ORDER_PRODUCERS2216{WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},2217// WASM_SEC_ORDER_TARGET_FEATURES2218{WASM_SEC_ORDER_TARGET_FEATURES}};22192220bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,2221StringRef CustomSectionName) {2222int Order = getSectionOrder(ID, CustomSectionName);2223if (Order == WASM_SEC_ORDER_NONE)2224return true;22252226// Disallowed predecessors we need to check for2227SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;22282229// Keep track of completed checks to avoid repeating work2230bool Checked[WASM_NUM_SEC_ORDERS] = {};22312232int Curr = Order;2233while (true) {2234// Add new disallowed predecessors to work list2235for (size_t I = 0;; ++I) {2236int Next = DisallowedPredecessors[Curr][I];2237if (Next == WASM_SEC_ORDER_NONE)2238break;2239if (Checked[Next])2240continue;2241WorkList.push_back(Next);2242Checked[Next] = true;2243}22442245if (WorkList.empty())2246break;22472248// Consider next disallowed predecessor2249Curr = WorkList.pop_back_val();2250if (Seen[Curr])2251return false;2252}22532254// Have not seen any disallowed predecessors2255Seen[Order] = true;2256return true;2257}225822592260