llvm-project
2255 строк · 79.8 Кб
1//===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ADT/ArrayRef.h"10#include "llvm/ADT/DenseSet.h"11#include "llvm/ADT/SmallSet.h"12#include "llvm/ADT/StringRef.h"13#include "llvm/ADT/StringSet.h"14#include "llvm/ADT/StringSwitch.h"15#include "llvm/BinaryFormat/Wasm.h"16#include "llvm/Object/Binary.h"17#include "llvm/Object/Error.h"18#include "llvm/Object/ObjectFile.h"19#include "llvm/Object/SymbolicFile.h"20#include "llvm/Object/Wasm.h"21#include "llvm/Support/Endian.h"22#include "llvm/Support/Error.h"23#include "llvm/Support/ErrorHandling.h"24#include "llvm/Support/Format.h"25#include "llvm/Support/LEB128.h"26#include "llvm/Support/ScopedPrinter.h"27#include "llvm/TargetParser/SubtargetFeature.h"28#include "llvm/TargetParser/Triple.h"29#include <algorithm>30#include <cassert>31#include <cstdint>32#include <cstring>33#include <limits>34
35#define DEBUG_TYPE "wasm-object"36
37using namespace llvm;38using namespace object;39
40void WasmSymbol::print(raw_ostream &Out) const {41Out << "Name=" << Info.Name42<< ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind)) << ", Flags=0x"43<< Twine::utohexstr(Info.Flags) << " [";44switch (getBinding()) {45case wasm::WASM_SYMBOL_BINDING_GLOBAL: Out << "global"; break;46case wasm::WASM_SYMBOL_BINDING_LOCAL: Out << "local"; break;47case wasm::WASM_SYMBOL_BINDING_WEAK: Out << "weak"; break;48}49if (isHidden()) {50Out << ", hidden";51} else {52Out << ", default";53}54Out << "]";55if (!isTypeData()) {56Out << ", ElemIndex=" << Info.ElementIndex;57} else if (isDefined()) {58Out << ", Segment=" << Info.DataRef.Segment;59Out << ", Offset=" << Info.DataRef.Offset;60Out << ", Size=" << Info.DataRef.Size;61}62}
63
64#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)65LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); }66#endif67
68Expected<std::unique_ptr<WasmObjectFile>>69ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) {70Error Err = Error::success();71auto ObjectFile = std::make_unique<WasmObjectFile>(Buffer, Err);72if (Err)73return std::move(Err);74
75return std::move(ObjectFile);76}
77
78#define VARINT7_MAX ((1 << 7) - 1)79#define VARINT7_MIN (-(1 << 7))80#define VARUINT7_MAX (1 << 7)81#define VARUINT1_MAX (1)82
83static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) {84if (Ctx.Ptr == Ctx.End)85report_fatal_error("EOF while reading uint8");86return *Ctx.Ptr++;87}
88
89static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) {90if (Ctx.Ptr + 4 > Ctx.End)91report_fatal_error("EOF while reading uint32");92uint32_t Result = support::endian::read32le(Ctx.Ptr);93Ctx.Ptr += 4;94return Result;95}
96
97static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) {98if (Ctx.Ptr + 4 > Ctx.End)99report_fatal_error("EOF while reading float64");100int32_t Result = 0;101memcpy(&Result, Ctx.Ptr, sizeof(Result));102Ctx.Ptr += sizeof(Result);103return Result;104}
105
106static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) {107if (Ctx.Ptr + 8 > Ctx.End)108report_fatal_error("EOF while reading float64");109int64_t Result = 0;110memcpy(&Result, Ctx.Ptr, sizeof(Result));111Ctx.Ptr += sizeof(Result);112return Result;113}
114
115static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) {116unsigned Count;117const char *Error = nullptr;118uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error);119if (Error)120report_fatal_error(Error);121Ctx.Ptr += Count;122return Result;123}
124
125static StringRef readString(WasmObjectFile::ReadContext &Ctx) {126uint32_t StringLen = readULEB128(Ctx);127if (Ctx.Ptr + StringLen > Ctx.End)128report_fatal_error("EOF while reading string");129StringRef Return =130StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen);131Ctx.Ptr += StringLen;132return Return;133}
134
135static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) {136unsigned Count;137const char *Error = nullptr;138uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error);139if (Error)140report_fatal_error(Error);141Ctx.Ptr += Count;142return Result;143}
144
145static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) {146int64_t Result = readLEB128(Ctx);147if (Result > VARUINT1_MAX || Result < 0)148report_fatal_error("LEB is outside Varuint1 range");149return Result;150}
151
152static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) {153int64_t Result = readLEB128(Ctx);154if (Result > INT32_MAX || Result < INT32_MIN)155report_fatal_error("LEB is outside Varint32 range");156return Result;157}
158
159static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) {160uint64_t Result = readULEB128(Ctx);161if (Result > UINT32_MAX)162report_fatal_error("LEB is outside Varuint32 range");163return Result;164}
165
166static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) {167return readLEB128(Ctx);168}
169
170static uint64_t readVaruint64(WasmObjectFile::ReadContext &Ctx) {171return readULEB128(Ctx);172}
173
174static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) {175return readUint8(Ctx);176}
177
178static wasm::ValType parseValType(WasmObjectFile::ReadContext &Ctx,179uint32_t Code) {180// only directly encoded FUNCREF/EXTERNREF/EXNREF are supported181// (not ref null func, ref null extern, or ref null exn)182switch (Code) {183case wasm::WASM_TYPE_I32:184case wasm::WASM_TYPE_I64:185case wasm::WASM_TYPE_F32:186case wasm::WASM_TYPE_F64:187case wasm::WASM_TYPE_V128:188case wasm::WASM_TYPE_FUNCREF:189case wasm::WASM_TYPE_EXTERNREF:190case wasm::WASM_TYPE_EXNREF:191return wasm::ValType(Code);192}193if (Code == wasm::WASM_TYPE_NULLABLE || Code == wasm::WASM_TYPE_NONNULLABLE) {194/* Discard HeapType */ readVarint64(Ctx);195}196return wasm::ValType(wasm::ValType::OTHERREF);197}
198
199static Error readInitExpr(wasm::WasmInitExpr &Expr,200WasmObjectFile::ReadContext &Ctx) {201auto Start = Ctx.Ptr;202
203Expr.Extended = false;204Expr.Inst.Opcode = readOpcode(Ctx);205switch (Expr.Inst.Opcode) {206case wasm::WASM_OPCODE_I32_CONST:207Expr.Inst.Value.Int32 = readVarint32(Ctx);208break;209case wasm::WASM_OPCODE_I64_CONST:210Expr.Inst.Value.Int64 = readVarint64(Ctx);211break;212case wasm::WASM_OPCODE_F32_CONST:213Expr.Inst.Value.Float32 = readFloat32(Ctx);214break;215case wasm::WASM_OPCODE_F64_CONST:216Expr.Inst.Value.Float64 = readFloat64(Ctx);217break;218case wasm::WASM_OPCODE_GLOBAL_GET:219Expr.Inst.Value.Global = readULEB128(Ctx);220break;221case wasm::WASM_OPCODE_REF_NULL: {222/* Discard type */ parseValType(Ctx, readVaruint32(Ctx));223break;224}225default:226Expr.Extended = true;227}228
229if (!Expr.Extended) {230uint8_t EndOpcode = readOpcode(Ctx);231if (EndOpcode != wasm::WASM_OPCODE_END)232Expr.Extended = true;233}234
235if (Expr.Extended) {236Ctx.Ptr = Start;237while (true) {238uint8_t Opcode = readOpcode(Ctx);239switch (Opcode) {240case wasm::WASM_OPCODE_I32_CONST:241case wasm::WASM_OPCODE_GLOBAL_GET:242case wasm::WASM_OPCODE_REF_NULL:243case wasm::WASM_OPCODE_REF_FUNC:244case wasm::WASM_OPCODE_I64_CONST:245readULEB128(Ctx);246break;247case wasm::WASM_OPCODE_F32_CONST:248readFloat32(Ctx);249break;250case wasm::WASM_OPCODE_F64_CONST:251readFloat64(Ctx);252break;253case wasm::WASM_OPCODE_I32_ADD:254case wasm::WASM_OPCODE_I32_SUB:255case wasm::WASM_OPCODE_I32_MUL:256case wasm::WASM_OPCODE_I64_ADD:257case wasm::WASM_OPCODE_I64_SUB:258case wasm::WASM_OPCODE_I64_MUL:259break;260case wasm::WASM_OPCODE_GC_PREFIX:261break;262// The GC opcodes are in a separate (prefixed space). This flat switch263// structure works as long as there is no overlap between the GC and264// general opcodes used in init exprs.265case wasm::WASM_OPCODE_STRUCT_NEW:266case wasm::WASM_OPCODE_STRUCT_NEW_DEFAULT:267case wasm::WASM_OPCODE_ARRAY_NEW:268case wasm::WASM_OPCODE_ARRAY_NEW_DEFAULT:269readULEB128(Ctx); // heap type index270break;271case wasm::WASM_OPCODE_ARRAY_NEW_FIXED:272readULEB128(Ctx); // heap type index273readULEB128(Ctx); // array size274break;275case wasm::WASM_OPCODE_REF_I31:276break;277case wasm::WASM_OPCODE_END:278Expr.Body = ArrayRef<uint8_t>(Start, Ctx.Ptr - Start);279return Error::success();280default:281return make_error<GenericBinaryError>(282Twine("invalid opcode in init_expr: ") + Twine(unsigned(Opcode)),283object_error::parse_failed);284}285}286}287
288return Error::success();289}
290
291static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) {292wasm::WasmLimits Result;293Result.Flags = readVaruint32(Ctx);294Result.Minimum = readVaruint64(Ctx);295if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)296Result.Maximum = readVaruint64(Ctx);297return Result;298}
299
300static wasm::WasmTableType readTableType(WasmObjectFile::ReadContext &Ctx) {301wasm::WasmTableType TableType;302auto ElemType = parseValType(Ctx, readVaruint32(Ctx));303TableType.ElemType = ElemType;304TableType.Limits = readLimits(Ctx);305return TableType;306}
307
308static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx,309WasmSectionOrderChecker &Checker) {310Section.Type = readUint8(Ctx);311LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n");312// When reading the section's size, store the size of the LEB used to encode313// it. This allows objcopy/strip to reproduce the binary identically.314const uint8_t *PreSizePtr = Ctx.Ptr;315uint32_t Size = readVaruint32(Ctx);316Section.HeaderSecSizeEncodingLen = Ctx.Ptr - PreSizePtr;317Section.Offset = Ctx.Ptr - Ctx.Start;318if (Size == 0)319return make_error<StringError>("zero length section",320object_error::parse_failed);321if (Ctx.Ptr + Size > Ctx.End)322return make_error<StringError>("section too large",323object_error::parse_failed);324if (Section.Type == wasm::WASM_SEC_CUSTOM) {325WasmObjectFile::ReadContext SectionCtx;326SectionCtx.Start = Ctx.Ptr;327SectionCtx.Ptr = Ctx.Ptr;328SectionCtx.End = Ctx.Ptr + Size;329
330Section.Name = readString(SectionCtx);331
332uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start;333Ctx.Ptr += SectionNameSize;334Size -= SectionNameSize;335}336
337if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) {338return make_error<StringError>("out of order section type: " +339llvm::to_string(Section.Type),340object_error::parse_failed);341}342
343Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);344Ctx.Ptr += Size;345return Error::success();346}
347
348WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err)349: ObjectFile(Binary::ID_Wasm, Buffer) {350ErrorAsOutParameter ErrAsOutParam(&Err);351Header.Magic = getData().substr(0, 4);352if (Header.Magic != StringRef("\0asm", 4)) {353Err = make_error<StringError>("invalid magic number",354object_error::parse_failed);355return;356}357
358ReadContext Ctx;359Ctx.Start = getData().bytes_begin();360Ctx.Ptr = Ctx.Start + 4;361Ctx.End = Ctx.Start + getData().size();362
363if (Ctx.Ptr + 4 > Ctx.End) {364Err = make_error<StringError>("missing version number",365object_error::parse_failed);366return;367}368
369Header.Version = readUint32(Ctx);370if (Header.Version != wasm::WasmVersion) {371Err = make_error<StringError>("invalid version number: " +372Twine(Header.Version),373object_error::parse_failed);374return;375}376
377WasmSectionOrderChecker Checker;378while (Ctx.Ptr < Ctx.End) {379WasmSection Sec;380if ((Err = readSection(Sec, Ctx, Checker)))381return;382if ((Err = parseSection(Sec)))383return;384
385Sections.push_back(Sec);386}387}
388
389Error WasmObjectFile::parseSection(WasmSection &Sec) {390ReadContext Ctx;391Ctx.Start = Sec.Content.data();392Ctx.End = Ctx.Start + Sec.Content.size();393Ctx.Ptr = Ctx.Start;394switch (Sec.Type) {395case wasm::WASM_SEC_CUSTOM:396return parseCustomSection(Sec, Ctx);397case wasm::WASM_SEC_TYPE:398return parseTypeSection(Ctx);399case wasm::WASM_SEC_IMPORT:400return parseImportSection(Ctx);401case wasm::WASM_SEC_FUNCTION:402return parseFunctionSection(Ctx);403case wasm::WASM_SEC_TABLE:404return parseTableSection(Ctx);405case wasm::WASM_SEC_MEMORY:406return parseMemorySection(Ctx);407case wasm::WASM_SEC_TAG:408return parseTagSection(Ctx);409case wasm::WASM_SEC_GLOBAL:410return parseGlobalSection(Ctx);411case wasm::WASM_SEC_EXPORT:412return parseExportSection(Ctx);413case wasm::WASM_SEC_START:414return parseStartSection(Ctx);415case wasm::WASM_SEC_ELEM:416return parseElemSection(Ctx);417case wasm::WASM_SEC_CODE:418return parseCodeSection(Ctx);419case wasm::WASM_SEC_DATA:420return parseDataSection(Ctx);421case wasm::WASM_SEC_DATACOUNT:422return parseDataCountSection(Ctx);423default:424return make_error<GenericBinaryError>(425"invalid section type: " + Twine(Sec.Type), object_error::parse_failed);426}427}
428
429Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) {430// Legacy "dylink" section support.431// See parseDylink0Section for the current "dylink.0" section parsing.432HasDylinkSection = true;433DylinkInfo.MemorySize = readVaruint32(Ctx);434DylinkInfo.MemoryAlignment = readVaruint32(Ctx);435DylinkInfo.TableSize = readVaruint32(Ctx);436DylinkInfo.TableAlignment = readVaruint32(Ctx);437uint32_t Count = readVaruint32(Ctx);438while (Count--) {439DylinkInfo.Needed.push_back(readString(Ctx));440}441
442if (Ctx.Ptr != Ctx.End)443return make_error<GenericBinaryError>("dylink section ended prematurely",444object_error::parse_failed);445return Error::success();446}
447
448Error WasmObjectFile::parseDylink0Section(ReadContext &Ctx) {449// See450// https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md451HasDylinkSection = true;452
453const uint8_t *OrigEnd = Ctx.End;454while (Ctx.Ptr < OrigEnd) {455Ctx.End = OrigEnd;456uint8_t Type = readUint8(Ctx);457uint32_t Size = readVaruint32(Ctx);458LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size459<< "\n");460Ctx.End = Ctx.Ptr + Size;461uint32_t Count;462switch (Type) {463case wasm::WASM_DYLINK_MEM_INFO:464DylinkInfo.MemorySize = readVaruint32(Ctx);465DylinkInfo.MemoryAlignment = readVaruint32(Ctx);466DylinkInfo.TableSize = readVaruint32(Ctx);467DylinkInfo.TableAlignment = readVaruint32(Ctx);468break;469case wasm::WASM_DYLINK_NEEDED:470Count = readVaruint32(Ctx);471while (Count--) {472DylinkInfo.Needed.push_back(readString(Ctx));473}474break;475case wasm::WASM_DYLINK_EXPORT_INFO: {476uint32_t Count = readVaruint32(Ctx);477while (Count--) {478DylinkInfo.ExportInfo.push_back({readString(Ctx), readVaruint32(Ctx)});479}480break;481}482case wasm::WASM_DYLINK_IMPORT_INFO: {483uint32_t Count = readVaruint32(Ctx);484while (Count--) {485DylinkInfo.ImportInfo.push_back(486{readString(Ctx), readString(Ctx), readVaruint32(Ctx)});487}488break;489}490default:491LLVM_DEBUG(dbgs() << "unknown dylink.0 sub-section: " << Type << "\n");492Ctx.Ptr += Size;493break;494}495if (Ctx.Ptr != Ctx.End) {496return make_error<GenericBinaryError>(497"dylink.0 sub-section ended prematurely", object_error::parse_failed);498}499}500
501if (Ctx.Ptr != Ctx.End)502return make_error<GenericBinaryError>("dylink.0 section ended prematurely",503object_error::parse_failed);504return Error::success();505}
506
507Error WasmObjectFile::parseNameSection(ReadContext &Ctx) {508llvm::DenseSet<uint64_t> SeenFunctions;509llvm::DenseSet<uint64_t> SeenGlobals;510llvm::DenseSet<uint64_t> SeenSegments;511
512// If there is symbol info from the export section, this info will supersede513// it, but not info from a linking section514if (!HasLinkingSection) {515Symbols.clear();516}517
518while (Ctx.Ptr < Ctx.End) {519uint8_t Type = readUint8(Ctx);520uint32_t Size = readVaruint32(Ctx);521const uint8_t *SubSectionEnd = Ctx.Ptr + Size;522
523switch (Type) {524case wasm::WASM_NAMES_FUNCTION:525case wasm::WASM_NAMES_GLOBAL:526case wasm::WASM_NAMES_DATA_SEGMENT: {527uint32_t Count = readVaruint32(Ctx);528while (Count--) {529uint32_t Index = readVaruint32(Ctx);530StringRef Name = readString(Ctx);531wasm::NameType nameType = wasm::NameType::FUNCTION;532wasm::WasmSymbolInfo Info{Name,533/*Kind */ wasm::WASM_SYMBOL_TYPE_FUNCTION,534/* Flags */ 0,535/* ImportModule */ std::nullopt,536/* ImportName */ std::nullopt,537/* ExportName */ std::nullopt,538{/* ElementIndex */ Index}};539const wasm::WasmSignature *Signature = nullptr;540const wasm::WasmGlobalType *GlobalType = nullptr;541const wasm::WasmTableType *TableType = nullptr;542if (Type == wasm::WASM_NAMES_FUNCTION) {543if (!SeenFunctions.insert(Index).second)544return make_error<GenericBinaryError>(545"function named more than once", object_error::parse_failed);546if (!isValidFunctionIndex(Index) || Name.empty())547return make_error<GenericBinaryError>("invalid function name entry",548object_error::parse_failed);549
550if (isDefinedFunctionIndex(Index)) {551wasm::WasmFunction &F = getDefinedFunction(Index);552F.DebugName = Name;553Signature = &Signatures[F.SigIndex];554if (F.ExportName) {555Info.ExportName = F.ExportName;556Info.Flags |= wasm::WASM_SYMBOL_BINDING_GLOBAL;557} else {558Info.Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;559}560} else {561Info.Flags |= wasm::WASM_SYMBOL_UNDEFINED;562}563} else if (Type == wasm::WASM_NAMES_GLOBAL) {564if (!SeenGlobals.insert(Index).second)565return make_error<GenericBinaryError>("global named more than once",566object_error::parse_failed);567if (!isValidGlobalIndex(Index) || Name.empty())568return make_error<GenericBinaryError>("invalid global name entry",569object_error::parse_failed);570nameType = wasm::NameType::GLOBAL;571Info.Kind = wasm::WASM_SYMBOL_TYPE_GLOBAL;572if (isDefinedGlobalIndex(Index)) {573GlobalType = &getDefinedGlobal(Index).Type;574} else {575Info.Flags |= wasm::WASM_SYMBOL_UNDEFINED;576}577} else {578if (!SeenSegments.insert(Index).second)579return make_error<GenericBinaryError>(580"segment named more than once", object_error::parse_failed);581if (Index > DataSegments.size())582return make_error<GenericBinaryError>("invalid data segment name entry",583object_error::parse_failed);584nameType = wasm::NameType::DATA_SEGMENT;585Info.Kind = wasm::WASM_SYMBOL_TYPE_DATA;586Info.Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;587assert(Index < DataSegments.size());588Info.DataRef = wasm::WasmDataReference{589Index, 0, DataSegments[Index].Data.Content.size()};590}591DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name});592if (!HasLinkingSection)593Symbols.emplace_back(Info, GlobalType, TableType, Signature);594}595break;596}597// Ignore local names for now598case wasm::WASM_NAMES_LOCAL:599default:600Ctx.Ptr += Size;601break;602}603if (Ctx.Ptr != SubSectionEnd)604return make_error<GenericBinaryError>(605"name sub-section ended prematurely", object_error::parse_failed);606}607
608if (Ctx.Ptr != Ctx.End)609return make_error<GenericBinaryError>("name section ended prematurely",610object_error::parse_failed);611return Error::success();612}
613
614Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {615HasLinkingSection = true;616
617LinkingData.Version = readVaruint32(Ctx);618if (LinkingData.Version != wasm::WasmMetadataVersion) {619return make_error<GenericBinaryError>(620"unexpected metadata version: " + Twine(LinkingData.Version) +621" (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",622object_error::parse_failed);623}624
625const uint8_t *OrigEnd = Ctx.End;626while (Ctx.Ptr < OrigEnd) {627Ctx.End = OrigEnd;628uint8_t Type = readUint8(Ctx);629uint32_t Size = readVaruint32(Ctx);630LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size631<< "\n");632Ctx.End = Ctx.Ptr + Size;633switch (Type) {634case wasm::WASM_SYMBOL_TABLE:635if (Error Err = parseLinkingSectionSymtab(Ctx))636return Err;637break;638case wasm::WASM_SEGMENT_INFO: {639uint32_t Count = readVaruint32(Ctx);640if (Count > DataSegments.size())641return make_error<GenericBinaryError>("too many segment names",642object_error::parse_failed);643for (uint32_t I = 0; I < Count; I++) {644DataSegments[I].Data.Name = readString(Ctx);645DataSegments[I].Data.Alignment = readVaruint32(Ctx);646DataSegments[I].Data.LinkingFlags = readVaruint32(Ctx);647}648break;649}650case wasm::WASM_INIT_FUNCS: {651uint32_t Count = readVaruint32(Ctx);652LinkingData.InitFunctions.reserve(Count);653for (uint32_t I = 0; I < Count; I++) {654wasm::WasmInitFunc Init;655Init.Priority = readVaruint32(Ctx);656Init.Symbol = readVaruint32(Ctx);657if (!isValidFunctionSymbol(Init.Symbol))658return make_error<GenericBinaryError>("invalid function symbol: " +659Twine(Init.Symbol),660object_error::parse_failed);661LinkingData.InitFunctions.emplace_back(Init);662}663break;664}665case wasm::WASM_COMDAT_INFO:666if (Error Err = parseLinkingSectionComdat(Ctx))667return Err;668break;669default:670Ctx.Ptr += Size;671break;672}673if (Ctx.Ptr != Ctx.End)674return make_error<GenericBinaryError>(675"linking sub-section ended prematurely", object_error::parse_failed);676}677if (Ctx.Ptr != OrigEnd)678return make_error<GenericBinaryError>("linking section ended prematurely",679object_error::parse_failed);680return Error::success();681}
682
683Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {684uint32_t Count = readVaruint32(Ctx);685// Clear out any symbol information that was derived from the exports686// section.687Symbols.clear();688Symbols.reserve(Count);689StringSet<> SymbolNames;690
691std::vector<wasm::WasmImport *> ImportedGlobals;692std::vector<wasm::WasmImport *> ImportedFunctions;693std::vector<wasm::WasmImport *> ImportedTags;694std::vector<wasm::WasmImport *> ImportedTables;695ImportedGlobals.reserve(Imports.size());696ImportedFunctions.reserve(Imports.size());697ImportedTags.reserve(Imports.size());698ImportedTables.reserve(Imports.size());699for (auto &I : Imports) {700if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)701ImportedFunctions.emplace_back(&I);702else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)703ImportedGlobals.emplace_back(&I);704else if (I.Kind == wasm::WASM_EXTERNAL_TAG)705ImportedTags.emplace_back(&I);706else if (I.Kind == wasm::WASM_EXTERNAL_TABLE)707ImportedTables.emplace_back(&I);708}709
710while (Count--) {711wasm::WasmSymbolInfo Info;712const wasm::WasmSignature *Signature = nullptr;713const wasm::WasmGlobalType *GlobalType = nullptr;714const wasm::WasmTableType *TableType = nullptr;715
716Info.Kind = readUint8(Ctx);717Info.Flags = readVaruint32(Ctx);718bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;719
720switch (Info.Kind) {721case wasm::WASM_SYMBOL_TYPE_FUNCTION:722Info.ElementIndex = readVaruint32(Ctx);723if (!isValidFunctionIndex(Info.ElementIndex) ||724IsDefined != isDefinedFunctionIndex(Info.ElementIndex))725return make_error<GenericBinaryError>("invalid function symbol index",726object_error::parse_failed);727if (IsDefined) {728Info.Name = readString(Ctx);729unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;730wasm::WasmFunction &Function = Functions[FuncIndex];731Signature = &Signatures[Function.SigIndex];732if (Function.SymbolName.empty())733Function.SymbolName = Info.Name;734} else {735wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];736if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {737Info.Name = readString(Ctx);738Info.ImportName = Import.Field;739} else {740Info.Name = Import.Field;741}742Signature = &Signatures[Import.SigIndex];743Info.ImportModule = Import.Module;744}745break;746
747case wasm::WASM_SYMBOL_TYPE_GLOBAL:748Info.ElementIndex = readVaruint32(Ctx);749if (!isValidGlobalIndex(Info.ElementIndex) ||750IsDefined != isDefinedGlobalIndex(Info.ElementIndex))751return make_error<GenericBinaryError>("invalid global symbol index",752object_error::parse_failed);753if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==754wasm::WASM_SYMBOL_BINDING_WEAK)755return make_error<GenericBinaryError>("undefined weak global symbol",756object_error::parse_failed);757if (IsDefined) {758Info.Name = readString(Ctx);759unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;760wasm::WasmGlobal &Global = Globals[GlobalIndex];761GlobalType = &Global.Type;762if (Global.SymbolName.empty())763Global.SymbolName = Info.Name;764} else {765wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];766if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {767Info.Name = readString(Ctx);768Info.ImportName = Import.Field;769} else {770Info.Name = Import.Field;771}772GlobalType = &Import.Global;773Info.ImportModule = Import.Module;774}775break;776
777case wasm::WASM_SYMBOL_TYPE_TABLE:778Info.ElementIndex = readVaruint32(Ctx);779if (!isValidTableNumber(Info.ElementIndex) ||780IsDefined != isDefinedTableNumber(Info.ElementIndex))781return make_error<GenericBinaryError>("invalid table symbol index",782object_error::parse_failed);783if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==784wasm::WASM_SYMBOL_BINDING_WEAK)785return make_error<GenericBinaryError>("undefined weak table symbol",786object_error::parse_failed);787if (IsDefined) {788Info.Name = readString(Ctx);789unsigned TableNumber = Info.ElementIndex - NumImportedTables;790wasm::WasmTable &Table = Tables[TableNumber];791TableType = &Table.Type;792if (Table.SymbolName.empty())793Table.SymbolName = Info.Name;794} else {795wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex];796if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {797Info.Name = readString(Ctx);798Info.ImportName = Import.Field;799} else {800Info.Name = Import.Field;801}802TableType = &Import.Table;803Info.ImportModule = Import.Module;804}805break;806
807case wasm::WASM_SYMBOL_TYPE_DATA:808Info.Name = readString(Ctx);809if (IsDefined) {810auto Index = readVaruint32(Ctx);811auto Offset = readVaruint64(Ctx);812auto Size = readVaruint64(Ctx);813if (!(Info.Flags & wasm::WASM_SYMBOL_ABSOLUTE)) {814if (static_cast<size_t>(Index) >= DataSegments.size())815return make_error<GenericBinaryError>(816"invalid data segment index: " + Twine(Index),817object_error::parse_failed);818size_t SegmentSize = DataSegments[Index].Data.Content.size();819if (Offset > SegmentSize)820return make_error<GenericBinaryError>(821"invalid data symbol offset: `" + Info.Name +822"` (offset: " + Twine(Offset) +823" segment size: " + Twine(SegmentSize) + ")",824object_error::parse_failed);825}826Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};827}828break;829
830case wasm::WASM_SYMBOL_TYPE_SECTION: {831if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=832wasm::WASM_SYMBOL_BINDING_LOCAL)833return make_error<GenericBinaryError>(834"section symbols must have local binding",835object_error::parse_failed);836Info.ElementIndex = readVaruint32(Ctx);837// Use somewhat unique section name as symbol name.838StringRef SectionName = Sections[Info.ElementIndex].Name;839Info.Name = SectionName;840break;841}842
843case wasm::WASM_SYMBOL_TYPE_TAG: {844Info.ElementIndex = readVaruint32(Ctx);845if (!isValidTagIndex(Info.ElementIndex) ||846IsDefined != isDefinedTagIndex(Info.ElementIndex))847return make_error<GenericBinaryError>("invalid tag symbol index",848object_error::parse_failed);849if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==850wasm::WASM_SYMBOL_BINDING_WEAK)851return make_error<GenericBinaryError>("undefined weak global symbol",852object_error::parse_failed);853if (IsDefined) {854Info.Name = readString(Ctx);855unsigned TagIndex = Info.ElementIndex - NumImportedTags;856wasm::WasmTag &Tag = Tags[TagIndex];857Signature = &Signatures[Tag.SigIndex];858if (Tag.SymbolName.empty())859Tag.SymbolName = Info.Name;860
861} else {862wasm::WasmImport &Import = *ImportedTags[Info.ElementIndex];863if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {864Info.Name = readString(Ctx);865Info.ImportName = Import.Field;866} else {867Info.Name = Import.Field;868}869Signature = &Signatures[Import.SigIndex];870Info.ImportModule = Import.Module;871}872break;873}874
875default:876return make_error<GenericBinaryError>("invalid symbol type: " +877Twine(unsigned(Info.Kind)),878object_error::parse_failed);879}880
881if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=882wasm::WASM_SYMBOL_BINDING_LOCAL &&883!SymbolNames.insert(Info.Name).second)884return make_error<GenericBinaryError>("duplicate symbol name " +885Twine(Info.Name),886object_error::parse_failed);887Symbols.emplace_back(Info, GlobalType, TableType, Signature);888LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");889}890
891return Error::success();892}
893
894Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {895uint32_t ComdatCount = readVaruint32(Ctx);896StringSet<> ComdatSet;897for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {898StringRef Name = readString(Ctx);899if (Name.empty() || !ComdatSet.insert(Name).second)900return make_error<GenericBinaryError>("bad/duplicate COMDAT name " +901Twine(Name),902object_error::parse_failed);903LinkingData.Comdats.emplace_back(Name);904uint32_t Flags = readVaruint32(Ctx);905if (Flags != 0)906return make_error<GenericBinaryError>("unsupported COMDAT flags",907object_error::parse_failed);908
909uint32_t EntryCount = readVaruint32(Ctx);910while (EntryCount--) {911unsigned Kind = readVaruint32(Ctx);912unsigned Index = readVaruint32(Ctx);913switch (Kind) {914default:915return make_error<GenericBinaryError>("invalid COMDAT entry type",916object_error::parse_failed);917case wasm::WASM_COMDAT_DATA:918if (Index >= DataSegments.size())919return make_error<GenericBinaryError>(920"COMDAT data index out of range", object_error::parse_failed);921if (DataSegments[Index].Data.Comdat != UINT32_MAX)922return make_error<GenericBinaryError>("data segment in two COMDATs",923object_error::parse_failed);924DataSegments[Index].Data.Comdat = ComdatIndex;925break;926case wasm::WASM_COMDAT_FUNCTION:927if (!isDefinedFunctionIndex(Index))928return make_error<GenericBinaryError>(929"COMDAT function index out of range", object_error::parse_failed);930if (getDefinedFunction(Index).Comdat != UINT32_MAX)931return make_error<GenericBinaryError>("function in two COMDATs",932object_error::parse_failed);933getDefinedFunction(Index).Comdat = ComdatIndex;934break;935case wasm::WASM_COMDAT_SECTION:936if (Index >= Sections.size())937return make_error<GenericBinaryError>(938"COMDAT section index out of range", object_error::parse_failed);939if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM)940return make_error<GenericBinaryError>(941"non-custom section in a COMDAT", object_error::parse_failed);942Sections[Index].Comdat = ComdatIndex;943break;944}945}946}947return Error::success();948}
949
950Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) {951llvm::SmallSet<StringRef, 3> FieldsSeen;952uint32_t Fields = readVaruint32(Ctx);953for (size_t I = 0; I < Fields; ++I) {954StringRef FieldName = readString(Ctx);955if (!FieldsSeen.insert(FieldName).second)956return make_error<GenericBinaryError>(957"producers section does not have unique fields",958object_error::parse_failed);959std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr;960if (FieldName == "language") {961ProducerVec = &ProducerInfo.Languages;962} else if (FieldName == "processed-by") {963ProducerVec = &ProducerInfo.Tools;964} else if (FieldName == "sdk") {965ProducerVec = &ProducerInfo.SDKs;966} else {967return make_error<GenericBinaryError>(968"producers section field is not named one of language, processed-by, "969"or sdk",970object_error::parse_failed);971}972uint32_t ValueCount = readVaruint32(Ctx);973llvm::SmallSet<StringRef, 8> ProducersSeen;974for (size_t J = 0; J < ValueCount; ++J) {975StringRef Name = readString(Ctx);976StringRef Version = readString(Ctx);977if (!ProducersSeen.insert(Name).second) {978return make_error<GenericBinaryError>(979"producers section contains repeated producer",980object_error::parse_failed);981}982ProducerVec->emplace_back(std::string(Name), std::string(Version));983}984}985if (Ctx.Ptr != Ctx.End)986return make_error<GenericBinaryError>("producers section ended prematurely",987object_error::parse_failed);988return Error::success();989}
990
991Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) {992llvm::SmallSet<std::string, 8> FeaturesSeen;993uint32_t FeatureCount = readVaruint32(Ctx);994for (size_t I = 0; I < FeatureCount; ++I) {995wasm::WasmFeatureEntry Feature;996Feature.Prefix = readUint8(Ctx);997switch (Feature.Prefix) {998case wasm::WASM_FEATURE_PREFIX_USED:999case wasm::WASM_FEATURE_PREFIX_REQUIRED:1000case wasm::WASM_FEATURE_PREFIX_DISALLOWED:1001break;1002default:1003return make_error<GenericBinaryError>("unknown feature policy prefix",1004object_error::parse_failed);1005}1006Feature.Name = std::string(readString(Ctx));1007if (!FeaturesSeen.insert(Feature.Name).second)1008return make_error<GenericBinaryError>(1009"target features section contains repeated feature \"" +1010Feature.Name + "\"",1011object_error::parse_failed);1012TargetFeatures.push_back(Feature);1013}1014if (Ctx.Ptr != Ctx.End)1015return make_error<GenericBinaryError>(1016"target features section ended prematurely",1017object_error::parse_failed);1018return Error::success();1019}
1020
1021Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {1022uint32_t SectionIndex = readVaruint32(Ctx);1023if (SectionIndex >= Sections.size())1024return make_error<GenericBinaryError>("invalid section index",1025object_error::parse_failed);1026WasmSection &Section = Sections[SectionIndex];1027uint32_t RelocCount = readVaruint32(Ctx);1028uint32_t EndOffset = Section.Content.size();1029uint32_t PreviousOffset = 0;1030while (RelocCount--) {1031wasm::WasmRelocation Reloc = {};1032uint32_t type = readVaruint32(Ctx);1033Reloc.Type = type;1034Reloc.Offset = readVaruint32(Ctx);1035if (Reloc.Offset < PreviousOffset)1036return make_error<GenericBinaryError>("relocations not in offset order",1037object_error::parse_failed);1038
1039auto badReloc = [&](StringRef msg) {1040return make_error<GenericBinaryError>(1041msg + ": " + Twine(Symbols[Reloc.Index].Info.Name),1042object_error::parse_failed);1043};1044
1045PreviousOffset = Reloc.Offset;1046Reloc.Index = readVaruint32(Ctx);1047switch (type) {1048case wasm::R_WASM_FUNCTION_INDEX_LEB:1049case wasm::R_WASM_FUNCTION_INDEX_I32:1050case wasm::R_WASM_TABLE_INDEX_SLEB:1051case wasm::R_WASM_TABLE_INDEX_SLEB64:1052case wasm::R_WASM_TABLE_INDEX_I32:1053case wasm::R_WASM_TABLE_INDEX_I64:1054case wasm::R_WASM_TABLE_INDEX_REL_SLEB:1055case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:1056if (!isValidFunctionSymbol(Reloc.Index))1057return badReloc("invalid function relocation");1058break;1059case wasm::R_WASM_TABLE_NUMBER_LEB:1060if (!isValidTableSymbol(Reloc.Index))1061return badReloc("invalid table relocation");1062break;1063case wasm::R_WASM_TYPE_INDEX_LEB:1064if (Reloc.Index >= Signatures.size())1065return badReloc("invalid relocation type index");1066break;1067case wasm::R_WASM_GLOBAL_INDEX_LEB:1068// R_WASM_GLOBAL_INDEX_LEB are can be used against function and data1069// symbols to refer to their GOT entries.1070if (!isValidGlobalSymbol(Reloc.Index) &&1071!isValidDataSymbol(Reloc.Index) &&1072!isValidFunctionSymbol(Reloc.Index))1073return badReloc("invalid global relocation");1074break;1075case wasm::R_WASM_GLOBAL_INDEX_I32:1076if (!isValidGlobalSymbol(Reloc.Index))1077return badReloc("invalid global relocation");1078break;1079case wasm::R_WASM_TAG_INDEX_LEB:1080if (!isValidTagSymbol(Reloc.Index))1081return badReloc("invalid tag relocation");1082break;1083case wasm::R_WASM_MEMORY_ADDR_LEB:1084case wasm::R_WASM_MEMORY_ADDR_SLEB:1085case wasm::R_WASM_MEMORY_ADDR_I32:1086case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:1087case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:1088case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:1089if (!isValidDataSymbol(Reloc.Index))1090return badReloc("invalid data relocation");1091Reloc.Addend = readVarint32(Ctx);1092break;1093case wasm::R_WASM_MEMORY_ADDR_LEB64:1094case wasm::R_WASM_MEMORY_ADDR_SLEB64:1095case wasm::R_WASM_MEMORY_ADDR_I64:1096case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:1097case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:1098if (!isValidDataSymbol(Reloc.Index))1099return badReloc("invalid data relocation");1100Reloc.Addend = readVarint64(Ctx);1101break;1102case wasm::R_WASM_FUNCTION_OFFSET_I32:1103if (!isValidFunctionSymbol(Reloc.Index))1104return badReloc("invalid function relocation");1105Reloc.Addend = readVarint32(Ctx);1106break;1107case wasm::R_WASM_FUNCTION_OFFSET_I64:1108if (!isValidFunctionSymbol(Reloc.Index))1109return badReloc("invalid function relocation");1110Reloc.Addend = readVarint64(Ctx);1111break;1112case wasm::R_WASM_SECTION_OFFSET_I32:1113if (!isValidSectionSymbol(Reloc.Index))1114return badReloc("invalid section relocation");1115Reloc.Addend = readVarint32(Ctx);1116break;1117default:1118return make_error<GenericBinaryError>("invalid relocation type: " +1119Twine(type),1120object_error::parse_failed);1121}1122
1123// Relocations must fit inside the section, and must appear in order. They1124// also shouldn't overlap a function/element boundary, but we don't bother1125// to check that.1126uint64_t Size = 5;1127if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 ||1128Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 ||1129Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64)1130Size = 10;1131if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 ||1132Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 ||1133Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LOCREL_I32 ||1134Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 ||1135Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||1136Reloc.Type == wasm::R_WASM_FUNCTION_INDEX_I32 ||1137Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32)1138Size = 4;1139if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 ||1140Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 ||1141Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64)1142Size = 8;1143if (Reloc.Offset + Size > EndOffset)1144return make_error<GenericBinaryError>("invalid relocation offset",1145object_error::parse_failed);1146
1147Section.Relocations.push_back(Reloc);1148}1149if (Ctx.Ptr != Ctx.End)1150return make_error<GenericBinaryError>("reloc section ended prematurely",1151object_error::parse_failed);1152return Error::success();1153}
1154
1155Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {1156if (Sec.Name == "dylink") {1157if (Error Err = parseDylinkSection(Ctx))1158return Err;1159} else if (Sec.Name == "dylink.0") {1160if (Error Err = parseDylink0Section(Ctx))1161return Err;1162} else if (Sec.Name == "name") {1163if (Error Err = parseNameSection(Ctx))1164return Err;1165} else if (Sec.Name == "linking") {1166if (Error Err = parseLinkingSection(Ctx))1167return Err;1168} else if (Sec.Name == "producers") {1169if (Error Err = parseProducersSection(Ctx))1170return Err;1171} else if (Sec.Name == "target_features") {1172if (Error Err = parseTargetFeaturesSection(Ctx))1173return Err;1174} else if (Sec.Name.starts_with("reloc.")) {1175if (Error Err = parseRelocSection(Sec.Name, Ctx))1176return Err;1177}1178return Error::success();1179}
1180
1181Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {1182auto parseFieldDef = [&]() {1183uint32_t TypeCode = readVaruint32((Ctx));1184/* Discard StorageType */ parseValType(Ctx, TypeCode);1185/* Discard Mutability */ readVaruint32(Ctx);1186};1187
1188uint32_t Count = readVaruint32(Ctx);1189Signatures.reserve(Count);1190while (Count--) {1191wasm::WasmSignature Sig;1192uint8_t Form = readUint8(Ctx);1193if (Form == wasm::WASM_TYPE_REC) {1194// Rec groups expand the type index space (beyond what was declared at1195// the top of the section, and also consume one element in that space.1196uint32_t RecSize = readVaruint32(Ctx);1197if (RecSize == 0)1198return make_error<GenericBinaryError>("Rec group size cannot be 0",1199object_error::parse_failed);1200Signatures.reserve(Signatures.size() + RecSize);1201Count += RecSize;1202Sig.Kind = wasm::WasmSignature::Placeholder;1203Signatures.push_back(std::move(Sig));1204HasUnmodeledTypes = true;1205continue;1206}1207if (Form != wasm::WASM_TYPE_FUNC) {1208// Currently LLVM only models function types, and not other composite1209// types. Here we parse the type declarations just enough to skip past1210// them in the binary.1211if (Form == wasm::WASM_TYPE_SUB || Form == wasm::WASM_TYPE_SUB_FINAL) {1212uint32_t Supers = readVaruint32(Ctx);1213if (Supers > 0) {1214if (Supers != 1)1215return make_error<GenericBinaryError>(1216"Invalid number of supertypes", object_error::parse_failed);1217/* Discard SuperIndex */ readVaruint32(Ctx);1218}1219Form = readVaruint32(Ctx);1220}1221if (Form == wasm::WASM_TYPE_STRUCT) {1222uint32_t FieldCount = readVaruint32(Ctx);1223while (FieldCount--) {1224parseFieldDef();1225}1226} else if (Form == wasm::WASM_TYPE_ARRAY) {1227parseFieldDef();1228} else {1229return make_error<GenericBinaryError>("bad form",1230object_error::parse_failed);1231}1232Sig.Kind = wasm::WasmSignature::Placeholder;1233Signatures.push_back(std::move(Sig));1234HasUnmodeledTypes = true;1235continue;1236}1237
1238uint32_t ParamCount = readVaruint32(Ctx);1239Sig.Params.reserve(ParamCount);1240while (ParamCount--) {1241uint32_t ParamType = readUint8(Ctx);1242Sig.Params.push_back(parseValType(Ctx, ParamType));1243continue;1244}1245uint32_t ReturnCount = readVaruint32(Ctx);1246while (ReturnCount--) {1247uint32_t ReturnType = readUint8(Ctx);1248Sig.Returns.push_back(parseValType(Ctx, ReturnType));1249}1250
1251Signatures.push_back(std::move(Sig));1252}1253if (Ctx.Ptr != Ctx.End)1254return make_error<GenericBinaryError>("type section ended prematurely",1255object_error::parse_failed);1256return Error::success();1257}
1258
1259Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {1260uint32_t Count = readVaruint32(Ctx);1261uint32_t NumTypes = Signatures.size();1262Imports.reserve(Count);1263for (uint32_t I = 0; I < Count; I++) {1264wasm::WasmImport Im;1265Im.Module = readString(Ctx);1266Im.Field = readString(Ctx);1267Im.Kind = readUint8(Ctx);1268switch (Im.Kind) {1269case wasm::WASM_EXTERNAL_FUNCTION:1270NumImportedFunctions++;1271Im.SigIndex = readVaruint32(Ctx);1272if (Im.SigIndex >= NumTypes)1273return make_error<GenericBinaryError>("invalid function type",1274object_error::parse_failed);1275break;1276case wasm::WASM_EXTERNAL_GLOBAL:1277NumImportedGlobals++;1278Im.Global.Type = readUint8(Ctx);1279Im.Global.Mutable = readVaruint1(Ctx);1280break;1281case wasm::WASM_EXTERNAL_MEMORY:1282Im.Memory = readLimits(Ctx);1283if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)1284HasMemory64 = true;1285break;1286case wasm::WASM_EXTERNAL_TABLE: {1287Im.Table = readTableType(Ctx);1288NumImportedTables++;1289auto ElemType = Im.Table.ElemType;1290if (ElemType != wasm::ValType::FUNCREF &&1291ElemType != wasm::ValType::EXTERNREF &&1292ElemType != wasm::ValType::EXNREF &&1293ElemType != wasm::ValType::OTHERREF)1294return make_error<GenericBinaryError>("invalid table element type",1295object_error::parse_failed);1296break;1297}1298case wasm::WASM_EXTERNAL_TAG:1299NumImportedTags++;1300if (readUint8(Ctx) != 0) // Reserved 'attribute' field1301return make_error<GenericBinaryError>("invalid attribute",1302object_error::parse_failed);1303Im.SigIndex = readVaruint32(Ctx);1304if (Im.SigIndex >= NumTypes)1305return make_error<GenericBinaryError>("invalid tag type",1306object_error::parse_failed);1307break;1308default:1309return make_error<GenericBinaryError>("unexpected import kind",1310object_error::parse_failed);1311}1312Imports.push_back(Im);1313}1314if (Ctx.Ptr != Ctx.End)1315return make_error<GenericBinaryError>("import section ended prematurely",1316object_error::parse_failed);1317return Error::success();1318}
1319
1320Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {1321uint32_t Count = readVaruint32(Ctx);1322Functions.reserve(Count);1323uint32_t NumTypes = Signatures.size();1324while (Count--) {1325uint32_t Type = readVaruint32(Ctx);1326if (Type >= NumTypes)1327return make_error<GenericBinaryError>("invalid function type",1328object_error::parse_failed);1329wasm::WasmFunction F;1330F.SigIndex = Type;1331Functions.push_back(F);1332}1333if (Ctx.Ptr != Ctx.End)1334return make_error<GenericBinaryError>("function section ended prematurely",1335object_error::parse_failed);1336return Error::success();1337}
1338
1339Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {1340TableSection = Sections.size();1341uint32_t Count = readVaruint32(Ctx);1342Tables.reserve(Count);1343while (Count--) {1344wasm::WasmTable T;1345T.Type = readTableType(Ctx);1346T.Index = NumImportedTables + Tables.size();1347Tables.push_back(T);1348auto ElemType = Tables.back().Type.ElemType;1349if (ElemType != wasm::ValType::FUNCREF &&1350ElemType != wasm::ValType::EXTERNREF &&1351ElemType != wasm::ValType::EXNREF &&1352ElemType != wasm::ValType::OTHERREF) {1353return make_error<GenericBinaryError>("invalid table element type",1354object_error::parse_failed);1355}1356}1357if (Ctx.Ptr != Ctx.End)1358return make_error<GenericBinaryError>("table section ended prematurely",1359object_error::parse_failed);1360return Error::success();1361}
1362
1363Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {1364uint32_t Count = readVaruint32(Ctx);1365Memories.reserve(Count);1366while (Count--) {1367auto Limits = readLimits(Ctx);1368if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)1369HasMemory64 = true;1370Memories.push_back(Limits);1371}1372if (Ctx.Ptr != Ctx.End)1373return make_error<GenericBinaryError>("memory section ended prematurely",1374object_error::parse_failed);1375return Error::success();1376}
1377
1378Error WasmObjectFile::parseTagSection(ReadContext &Ctx) {1379TagSection = Sections.size();1380uint32_t Count = readVaruint32(Ctx);1381Tags.reserve(Count);1382uint32_t NumTypes = Signatures.size();1383while (Count--) {1384if (readUint8(Ctx) != 0) // Reserved 'attribute' field1385return make_error<GenericBinaryError>("invalid attribute",1386object_error::parse_failed);1387uint32_t Type = readVaruint32(Ctx);1388if (Type >= NumTypes)1389return make_error<GenericBinaryError>("invalid tag type",1390object_error::parse_failed);1391wasm::WasmTag Tag;1392Tag.Index = NumImportedTags + Tags.size();1393Tag.SigIndex = Type;1394Signatures[Type].Kind = wasm::WasmSignature::Tag;1395Tags.push_back(Tag);1396}1397
1398if (Ctx.Ptr != Ctx.End)1399return make_error<GenericBinaryError>("tag section ended prematurely",1400object_error::parse_failed);1401return Error::success();1402}
1403
1404Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {1405GlobalSection = Sections.size();1406const uint8_t *SectionStart = Ctx.Ptr;1407uint32_t Count = readVaruint32(Ctx);1408Globals.reserve(Count);1409while (Count--) {1410wasm::WasmGlobal Global;1411Global.Index = NumImportedGlobals + Globals.size();1412const uint8_t *GlobalStart = Ctx.Ptr;1413Global.Offset = static_cast<uint32_t>(GlobalStart - SectionStart);1414auto GlobalOpcode = readVaruint32(Ctx);1415Global.Type.Type = (uint8_t)parseValType(Ctx, GlobalOpcode);1416Global.Type.Mutable = readVaruint1(Ctx);1417if (Error Err = readInitExpr(Global.InitExpr, Ctx))1418return Err;1419Global.Size = static_cast<uint32_t>(Ctx.Ptr - GlobalStart);1420Globals.push_back(Global);1421}1422if (Ctx.Ptr != Ctx.End)1423return make_error<GenericBinaryError>("global section ended prematurely",1424object_error::parse_failed);1425return Error::success();1426}
1427
1428Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {1429uint32_t Count = readVaruint32(Ctx);1430Exports.reserve(Count);1431Symbols.reserve(Count);1432for (uint32_t I = 0; I < Count; I++) {1433wasm::WasmExport Ex;1434Ex.Name = readString(Ctx);1435Ex.Kind = readUint8(Ctx);1436Ex.Index = readVaruint32(Ctx);1437const wasm::WasmSignature *Signature = nullptr;1438const wasm::WasmGlobalType *GlobalType = nullptr;1439const wasm::WasmTableType *TableType = nullptr;1440wasm::WasmSymbolInfo Info;1441Info.Name = Ex.Name;1442Info.Flags = 0;1443switch (Ex.Kind) {1444case wasm::WASM_EXTERNAL_FUNCTION: {1445if (!isDefinedFunctionIndex(Ex.Index))1446return make_error<GenericBinaryError>("invalid function export",1447object_error::parse_failed);1448getDefinedFunction(Ex.Index).ExportName = Ex.Name;1449Info.Kind = wasm::WASM_SYMBOL_TYPE_FUNCTION;1450Info.ElementIndex = Ex.Index;1451unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;1452wasm::WasmFunction &Function = Functions[FuncIndex];1453Signature = &Signatures[Function.SigIndex];1454break;1455}1456case wasm::WASM_EXTERNAL_GLOBAL: {1457if (!isValidGlobalIndex(Ex.Index))1458return make_error<GenericBinaryError>("invalid global export",1459object_error::parse_failed);1460Info.Kind = wasm::WASM_SYMBOL_TYPE_DATA;1461uint64_t Offset = 0;1462if (isDefinedGlobalIndex(Ex.Index)) {1463auto Global = getDefinedGlobal(Ex.Index);1464if (!Global.InitExpr.Extended) {1465auto Inst = Global.InitExpr.Inst;1466if (Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) {1467Offset = Inst.Value.Int32;1468} else if (Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) {1469Offset = Inst.Value.Int64;1470}1471}1472}1473Info.DataRef = wasm::WasmDataReference{0, Offset, 0};1474break;1475}1476case wasm::WASM_EXTERNAL_TAG:1477if (!isValidTagIndex(Ex.Index))1478return make_error<GenericBinaryError>("invalid tag export",1479object_error::parse_failed);1480Info.Kind = wasm::WASM_SYMBOL_TYPE_TAG;1481Info.ElementIndex = Ex.Index;1482break;1483case wasm::WASM_EXTERNAL_MEMORY:1484break;1485case wasm::WASM_EXTERNAL_TABLE:1486Info.Kind = wasm::WASM_SYMBOL_TYPE_TABLE;1487Info.ElementIndex = Ex.Index;1488break;1489default:1490return make_error<GenericBinaryError>("unexpected export kind",1491object_error::parse_failed);1492}1493Exports.push_back(Ex);1494if (Ex.Kind != wasm::WASM_EXTERNAL_MEMORY) {1495Symbols.emplace_back(Info, GlobalType, TableType, Signature);1496LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");1497}1498}1499if (Ctx.Ptr != Ctx.End)1500return make_error<GenericBinaryError>("export section ended prematurely",1501object_error::parse_failed);1502return Error::success();1503}
1504
1505bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {1506return Index < NumImportedFunctions + Functions.size();1507}
1508
1509bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {1510return Index >= NumImportedFunctions && isValidFunctionIndex(Index);1511}
1512
1513bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {1514return Index < NumImportedGlobals + Globals.size();1515}
1516
1517bool WasmObjectFile::isValidTableNumber(uint32_t Index) const {1518return Index < NumImportedTables + Tables.size();1519}
1520
1521bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {1522return Index >= NumImportedGlobals && isValidGlobalIndex(Index);1523}
1524
1525bool WasmObjectFile::isDefinedTableNumber(uint32_t Index) const {1526return Index >= NumImportedTables && isValidTableNumber(Index);1527}
1528
1529bool WasmObjectFile::isValidTagIndex(uint32_t Index) const {1530return Index < NumImportedTags + Tags.size();1531}
1532
1533bool WasmObjectFile::isDefinedTagIndex(uint32_t Index) const {1534return Index >= NumImportedTags && isValidTagIndex(Index);1535}
1536
1537bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {1538return Index < Symbols.size() && Symbols[Index].isTypeFunction();1539}
1540
1541bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const {1542return Index < Symbols.size() && Symbols[Index].isTypeTable();1543}
1544
1545bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {1546return Index < Symbols.size() && Symbols[Index].isTypeGlobal();1547}
1548
1549bool WasmObjectFile::isValidTagSymbol(uint32_t Index) const {1550return Index < Symbols.size() && Symbols[Index].isTypeTag();1551}
1552
1553bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {1554return Index < Symbols.size() && Symbols[Index].isTypeData();1555}
1556
1557bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {1558return Index < Symbols.size() && Symbols[Index].isTypeSection();1559}
1560
1561wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {1562assert(isDefinedFunctionIndex(Index));1563return Functions[Index - NumImportedFunctions];1564}
1565
1566const wasm::WasmFunction &1567WasmObjectFile::getDefinedFunction(uint32_t Index) const {1568assert(isDefinedFunctionIndex(Index));1569return Functions[Index - NumImportedFunctions];1570}
1571
1572const wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) const {1573assert(isDefinedGlobalIndex(Index));1574return Globals[Index - NumImportedGlobals];1575}
1576
1577wasm::WasmTag &WasmObjectFile::getDefinedTag(uint32_t Index) {1578assert(isDefinedTagIndex(Index));1579return Tags[Index - NumImportedTags];1580}
1581
1582Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {1583StartFunction = readVaruint32(Ctx);1584if (!isValidFunctionIndex(StartFunction))1585return make_error<GenericBinaryError>("invalid start function",1586object_error::parse_failed);1587return Error::success();1588}
1589
1590Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {1591CodeSection = Sections.size();1592uint32_t FunctionCount = readVaruint32(Ctx);1593if (FunctionCount != Functions.size()) {1594return make_error<GenericBinaryError>("invalid function count",1595object_error::parse_failed);1596}1597
1598for (uint32_t i = 0; i < FunctionCount; i++) {1599wasm::WasmFunction& Function = Functions[i];1600const uint8_t *FunctionStart = Ctx.Ptr;1601uint32_t Size = readVaruint32(Ctx);1602const uint8_t *FunctionEnd = Ctx.Ptr + Size;1603
1604Function.CodeOffset = Ctx.Ptr - FunctionStart;1605Function.Index = NumImportedFunctions + i;1606Function.CodeSectionOffset = FunctionStart - Ctx.Start;1607Function.Size = FunctionEnd - FunctionStart;1608
1609uint32_t NumLocalDecls = readVaruint32(Ctx);1610Function.Locals.reserve(NumLocalDecls);1611while (NumLocalDecls--) {1612wasm::WasmLocalDecl Decl;1613Decl.Count = readVaruint32(Ctx);1614Decl.Type = readUint8(Ctx);1615Function.Locals.push_back(Decl);1616}1617
1618uint32_t BodySize = FunctionEnd - Ctx.Ptr;1619// Ensure that Function is within Ctx's buffer.1620if (Ctx.Ptr + BodySize > Ctx.End) {1621return make_error<GenericBinaryError>("Function extends beyond buffer",1622object_error::parse_failed);1623}1624Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);1625// This will be set later when reading in the linking metadata section.1626Function.Comdat = UINT32_MAX;1627Ctx.Ptr += BodySize;1628assert(Ctx.Ptr == FunctionEnd);1629}1630if (Ctx.Ptr != Ctx.End)1631return make_error<GenericBinaryError>("code section ended prematurely",1632object_error::parse_failed);1633return Error::success();1634}
1635
1636Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {1637uint32_t Count = readVaruint32(Ctx);1638ElemSegments.reserve(Count);1639while (Count--) {1640wasm::WasmElemSegment Segment;1641Segment.Flags = readVaruint32(Ctx);1642
1643uint32_t SupportedFlags = wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER |1644wasm::WASM_ELEM_SEGMENT_IS_PASSIVE |1645wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS;1646if (Segment.Flags & ~SupportedFlags)1647return make_error<GenericBinaryError>(1648"Unsupported flags for element segment", object_error::parse_failed);1649
1650bool IsPassive = (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_PASSIVE) != 0;1651bool IsDeclarative =1652IsPassive && (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_DECLARATIVE);1653bool HasTableNumber =1654!IsPassive &&1655(Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER);1656bool HasInitExprs =1657(Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS);1658bool HasElemKind =1659(Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) &&1660!HasInitExprs;1661
1662if (HasTableNumber)1663Segment.TableNumber = readVaruint32(Ctx);1664else1665Segment.TableNumber = 0;1666
1667if (!isValidTableNumber(Segment.TableNumber))1668return make_error<GenericBinaryError>("invalid TableNumber",1669object_error::parse_failed);1670
1671if (IsPassive || IsDeclarative) {1672Segment.Offset.Extended = false;1673Segment.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;1674Segment.Offset.Inst.Value.Int32 = 0;1675} else {1676if (Error Err = readInitExpr(Segment.Offset, Ctx))1677return Err;1678}1679
1680if (HasElemKind) {1681auto ElemKind = readVaruint32(Ctx);1682if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) {1683Segment.ElemKind = parseValType(Ctx, ElemKind);1684if (Segment.ElemKind != wasm::ValType::FUNCREF &&1685Segment.ElemKind != wasm::ValType::EXTERNREF &&1686Segment.ElemKind != wasm::ValType::EXNREF &&1687Segment.ElemKind != wasm::ValType::OTHERREF) {1688return make_error<GenericBinaryError>("invalid elem type",1689object_error::parse_failed);1690}1691} else {1692if (ElemKind != 0)1693return make_error<GenericBinaryError>("invalid elem type",1694object_error::parse_failed);1695Segment.ElemKind = wasm::ValType::FUNCREF;1696}1697} else if (HasInitExprs) {1698auto ElemType = parseValType(Ctx, readVaruint32(Ctx));1699Segment.ElemKind = ElemType;1700} else {1701Segment.ElemKind = wasm::ValType::FUNCREF;1702}1703
1704uint32_t NumElems = readVaruint32(Ctx);1705
1706if (HasInitExprs) {1707while (NumElems--) {1708wasm::WasmInitExpr Expr;1709if (Error Err = readInitExpr(Expr, Ctx))1710return Err;1711}1712} else {1713while (NumElems--) {1714Segment.Functions.push_back(readVaruint32(Ctx));1715}1716}1717ElemSegments.push_back(Segment);1718}1719if (Ctx.Ptr != Ctx.End)1720return make_error<GenericBinaryError>("elem section ended prematurely",1721object_error::parse_failed);1722return Error::success();1723}
1724
1725Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {1726DataSection = Sections.size();1727uint32_t Count = readVaruint32(Ctx);1728if (DataCount && Count != *DataCount)1729return make_error<GenericBinaryError>(1730"number of data segments does not match DataCount section");1731DataSegments.reserve(Count);1732while (Count--) {1733WasmSegment Segment;1734Segment.Data.InitFlags = readVaruint32(Ctx);1735Segment.Data.MemoryIndex =1736(Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)1737? readVaruint32(Ctx)1738: 0;1739if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {1740if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))1741return Err;1742} else {1743Segment.Data.Offset.Extended = false;1744Segment.Data.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;1745Segment.Data.Offset.Inst.Value.Int32 = 0;1746}1747uint32_t Size = readVaruint32(Ctx);1748if (Size > (size_t)(Ctx.End - Ctx.Ptr))1749return make_error<GenericBinaryError>("invalid segment size",1750object_error::parse_failed);1751Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);1752// The rest of these Data fields are set later, when reading in the linking1753// metadata section.1754Segment.Data.Alignment = 0;1755Segment.Data.LinkingFlags = 0;1756Segment.Data.Comdat = UINT32_MAX;1757Segment.SectionOffset = Ctx.Ptr - Ctx.Start;1758Ctx.Ptr += Size;1759DataSegments.push_back(Segment);1760}1761if (Ctx.Ptr != Ctx.End)1762return make_error<GenericBinaryError>("data section ended prematurely",1763object_error::parse_failed);1764return Error::success();1765}
1766
1767Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {1768DataCount = readVaruint32(Ctx);1769return Error::success();1770}
1771
1772const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {1773return Header;1774}
1775
1776void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }1777
1778Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {1779uint32_t Result = SymbolRef::SF_None;1780const WasmSymbol &Sym = getWasmSymbol(Symb);1781
1782LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");1783if (Sym.isBindingWeak())1784Result |= SymbolRef::SF_Weak;1785if (!Sym.isBindingLocal())1786Result |= SymbolRef::SF_Global;1787if (Sym.isHidden())1788Result |= SymbolRef::SF_Hidden;1789if (!Sym.isDefined())1790Result |= SymbolRef::SF_Undefined;1791if (Sym.isTypeFunction())1792Result |= SymbolRef::SF_Executable;1793return Result;1794}
1795
1796basic_symbol_iterator WasmObjectFile::symbol_begin() const {1797DataRefImpl Ref;1798Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null1799Ref.d.b = 0; // Symbol index1800return BasicSymbolRef(Ref, this);1801}
1802
1803basic_symbol_iterator WasmObjectFile::symbol_end() const {1804DataRefImpl Ref;1805Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null1806Ref.d.b = Symbols.size(); // Symbol index1807return BasicSymbolRef(Ref, this);1808}
1809
1810const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {1811return Symbols[Symb.d.b];1812}
1813
1814const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {1815return getWasmSymbol(Symb.getRawDataRefImpl());1816}
1817
1818Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {1819return getWasmSymbol(Symb).Info.Name;1820}
1821
1822Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {1823auto &Sym = getWasmSymbol(Symb);1824if (!Sym.isDefined())1825return 0;1826Expected<section_iterator> Sec = getSymbolSection(Symb);1827if (!Sec)1828return Sec.takeError();1829uint32_t SectionAddress = getSectionAddress(Sec.get()->getRawDataRefImpl());1830if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&1831isDefinedFunctionIndex(Sym.Info.ElementIndex)) {1832return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset +1833SectionAddress;1834}1835if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_GLOBAL &&1836isDefinedGlobalIndex(Sym.Info.ElementIndex)) {1837return getDefinedGlobal(Sym.Info.ElementIndex).Offset + SectionAddress;1838}1839
1840return getSymbolValue(Symb);1841}
1842
1843uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {1844switch (Sym.Info.Kind) {1845case wasm::WASM_SYMBOL_TYPE_FUNCTION:1846case wasm::WASM_SYMBOL_TYPE_GLOBAL:1847case wasm::WASM_SYMBOL_TYPE_TAG:1848case wasm::WASM_SYMBOL_TYPE_TABLE:1849return Sym.Info.ElementIndex;1850case wasm::WASM_SYMBOL_TYPE_DATA: {1851// The value of a data symbol is the segment offset, plus the symbol1852// offset within the segment.1853uint32_t SegmentIndex = Sym.Info.DataRef.Segment;1854const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;1855if (Segment.Offset.Extended) {1856llvm_unreachable("extended init exprs not supported");1857} else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) {1858return Segment.Offset.Inst.Value.Int32 + Sym.Info.DataRef.Offset;1859} else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) {1860return Segment.Offset.Inst.Value.Int64 + Sym.Info.DataRef.Offset;1861} else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_GLOBAL_GET) {1862return Sym.Info.DataRef.Offset;1863} else {1864llvm_unreachable("unknown init expr opcode");1865}1866}1867case wasm::WASM_SYMBOL_TYPE_SECTION:1868return 0;1869}1870llvm_unreachable("invalid symbol type");1871}
1872
1873uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {1874return getWasmSymbolValue(getWasmSymbol(Symb));1875}
1876
1877uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {1878llvm_unreachable("not yet implemented");1879return 0;1880}
1881
1882uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {1883llvm_unreachable("not yet implemented");1884return 0;1885}
1886
1887Expected<SymbolRef::Type>1888WasmObjectFile::getSymbolType(DataRefImpl Symb) const {1889const WasmSymbol &Sym = getWasmSymbol(Symb);1890
1891switch (Sym.Info.Kind) {1892case wasm::WASM_SYMBOL_TYPE_FUNCTION:1893return SymbolRef::ST_Function;1894case wasm::WASM_SYMBOL_TYPE_GLOBAL:1895return SymbolRef::ST_Other;1896case wasm::WASM_SYMBOL_TYPE_DATA:1897return SymbolRef::ST_Data;1898case wasm::WASM_SYMBOL_TYPE_SECTION:1899return SymbolRef::ST_Debug;1900case wasm::WASM_SYMBOL_TYPE_TAG:1901return SymbolRef::ST_Other;1902case wasm::WASM_SYMBOL_TYPE_TABLE:1903return SymbolRef::ST_Other;1904}1905
1906llvm_unreachable("unknown WasmSymbol::SymbolType");1907return SymbolRef::ST_Other;1908}
1909
1910Expected<section_iterator>1911WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {1912const WasmSymbol &Sym = getWasmSymbol(Symb);1913if (Sym.isUndefined())1914return section_end();1915
1916DataRefImpl Ref;1917Ref.d.a = getSymbolSectionIdImpl(Sym);1918return section_iterator(SectionRef(Ref, this));1919}
1920
1921uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {1922const WasmSymbol &Sym = getWasmSymbol(Symb);1923return getSymbolSectionIdImpl(Sym);1924}
1925
1926uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {1927switch (Sym.Info.Kind) {1928case wasm::WASM_SYMBOL_TYPE_FUNCTION:1929return CodeSection;1930case wasm::WASM_SYMBOL_TYPE_GLOBAL:1931return GlobalSection;1932case wasm::WASM_SYMBOL_TYPE_DATA:1933return DataSection;1934case wasm::WASM_SYMBOL_TYPE_SECTION:1935return Sym.Info.ElementIndex;1936case wasm::WASM_SYMBOL_TYPE_TAG:1937return TagSection;1938case wasm::WASM_SYMBOL_TYPE_TABLE:1939return TableSection;1940default:1941llvm_unreachable("unknown WasmSymbol::SymbolType");1942}1943}
1944
1945uint32_t WasmObjectFile::getSymbolSize(SymbolRef Symb) const {1946const WasmSymbol &Sym = getWasmSymbol(Symb);1947if (!Sym.isDefined())1948return 0;1949if (Sym.isTypeGlobal())1950return getDefinedGlobal(Sym.Info.ElementIndex).Size;1951if (Sym.isTypeData())1952return Sym.Info.DataRef.Size;1953if (Sym.isTypeFunction())1954return functions()[Sym.Info.ElementIndex - getNumImportedFunctions()].Size;1955// Currently symbol size is only tracked for data segments and functions. In1956// principle we could also track size (e.g. binary size) for tables, globals1957// and element segments etc too.1958return 0;1959}
1960
1961void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }1962
1963Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {1964const WasmSection &S = Sections[Sec.d.a];1965if (S.Type == wasm::WASM_SEC_CUSTOM)1966return S.Name;1967if (S.Type > wasm::WASM_SEC_LAST_KNOWN)1968return createStringError(object_error::invalid_section_index, "");1969return wasm::sectionTypeToString(S.Type);1970}
1971
1972uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const {1973// For object files, use 0 for section addresses, and section offsets for1974// symbol addresses. For linked files, use file offsets.1975// See also getSymbolAddress.1976return isRelocatableObject() || isSharedObject() ? 01977: Sections[Sec.d.a].Offset;1978}
1979
1980uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {1981return Sec.d.a;1982}
1983
1984uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {1985const WasmSection &S = Sections[Sec.d.a];1986return S.Content.size();1987}
1988
1989Expected<ArrayRef<uint8_t>>1990WasmObjectFile::getSectionContents(DataRefImpl Sec) const {1991const WasmSection &S = Sections[Sec.d.a];1992// This will never fail since wasm sections can never be empty (user-sections1993// must have a name and non-user sections each have a defined structure).1994return S.Content;1995}
1996
1997uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {1998return 1;1999}
2000
2001bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {2002return false;2003}
2004
2005bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {2006return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;2007}
2008
2009bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {2010return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;2011}
2012
2013bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }2014
2015bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }2016
2017relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {2018DataRefImpl RelocRef;2019RelocRef.d.a = Ref.d.a;2020RelocRef.d.b = 0;2021return relocation_iterator(RelocationRef(RelocRef, this));2022}
2023
2024relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {2025const WasmSection &Sec = getWasmSection(Ref);2026DataRefImpl RelocRef;2027RelocRef.d.a = Ref.d.a;2028RelocRef.d.b = Sec.Relocations.size();2029return relocation_iterator(RelocationRef(RelocRef, this));2030}
2031
2032void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }2033
2034uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {2035const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2036return Rel.Offset;2037}
2038
2039symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {2040const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2041if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)2042return symbol_end();2043DataRefImpl Sym;2044Sym.d.a = 1;2045Sym.d.b = Rel.Index;2046return symbol_iterator(SymbolRef(Sym, this));2047}
2048
2049uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {2050const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2051return Rel.Type;2052}
2053
2054void WasmObjectFile::getRelocationTypeName(2055DataRefImpl Ref, SmallVectorImpl<char> &Result) const {2056const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);2057StringRef Res = "Unknown";2058
2059#define WASM_RELOC(name, value) \2060case wasm::name: \2061Res = #name; \2062break;2063
2064switch (Rel.Type) {2065#include "llvm/BinaryFormat/WasmRelocs.def"2066}2067
2068#undef WASM_RELOC2069
2070Result.append(Res.begin(), Res.end());2071}
2072
2073section_iterator WasmObjectFile::section_begin() const {2074DataRefImpl Ref;2075Ref.d.a = 0;2076return section_iterator(SectionRef(Ref, this));2077}
2078
2079section_iterator WasmObjectFile::section_end() const {2080DataRefImpl Ref;2081Ref.d.a = Sections.size();2082return section_iterator(SectionRef(Ref, this));2083}
2084
2085uint8_t WasmObjectFile::getBytesInAddress() const {2086return HasMemory64 ? 8 : 4;2087}
2088
2089StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }2090
2091Triple::ArchType WasmObjectFile::getArch() const {2092return HasMemory64 ? Triple::wasm64 : Triple::wasm32;2093}
2094
2095Expected<SubtargetFeatures> WasmObjectFile::getFeatures() const {2096return SubtargetFeatures();2097}
2098
2099bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }2100
2101bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }2102
2103const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {2104assert(Ref.d.a < Sections.size());2105return Sections[Ref.d.a];2106}
2107
2108const WasmSection &2109WasmObjectFile::getWasmSection(const SectionRef &Section) const {2110return getWasmSection(Section.getRawDataRefImpl());2111}
2112
2113const wasm::WasmRelocation &2114WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {2115return getWasmRelocation(Ref.getRawDataRefImpl());2116}
2117
2118const wasm::WasmRelocation &2119WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {2120assert(Ref.d.a < Sections.size());2121const WasmSection &Sec = Sections[Ref.d.a];2122assert(Ref.d.b < Sec.Relocations.size());2123return Sec.Relocations[Ref.d.b];2124}
2125
2126int WasmSectionOrderChecker::getSectionOrder(unsigned ID,2127StringRef CustomSectionName) {2128switch (ID) {2129case wasm::WASM_SEC_CUSTOM:2130return StringSwitch<unsigned>(CustomSectionName)2131.Case("dylink", WASM_SEC_ORDER_DYLINK)2132.Case("dylink.0", WASM_SEC_ORDER_DYLINK)2133.Case("linking", WASM_SEC_ORDER_LINKING)2134.StartsWith("reloc.", WASM_SEC_ORDER_RELOC)2135.Case("name", WASM_SEC_ORDER_NAME)2136.Case("producers", WASM_SEC_ORDER_PRODUCERS)2137.Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)2138.Default(WASM_SEC_ORDER_NONE);2139case wasm::WASM_SEC_TYPE:2140return WASM_SEC_ORDER_TYPE;2141case wasm::WASM_SEC_IMPORT:2142return WASM_SEC_ORDER_IMPORT;2143case wasm::WASM_SEC_FUNCTION:2144return WASM_SEC_ORDER_FUNCTION;2145case wasm::WASM_SEC_TABLE:2146return WASM_SEC_ORDER_TABLE;2147case wasm::WASM_SEC_MEMORY:2148return WASM_SEC_ORDER_MEMORY;2149case wasm::WASM_SEC_GLOBAL:2150return WASM_SEC_ORDER_GLOBAL;2151case wasm::WASM_SEC_EXPORT:2152return WASM_SEC_ORDER_EXPORT;2153case wasm::WASM_SEC_START:2154return WASM_SEC_ORDER_START;2155case wasm::WASM_SEC_ELEM:2156return WASM_SEC_ORDER_ELEM;2157case wasm::WASM_SEC_CODE:2158return WASM_SEC_ORDER_CODE;2159case wasm::WASM_SEC_DATA:2160return WASM_SEC_ORDER_DATA;2161case wasm::WASM_SEC_DATACOUNT:2162return WASM_SEC_ORDER_DATACOUNT;2163case wasm::WASM_SEC_TAG:2164return WASM_SEC_ORDER_TAG;2165default:2166return WASM_SEC_ORDER_NONE;2167}2168}
2169
2170// Represents the edges in a directed graph where any node B reachable from node
2171// A is not allowed to appear before A in the section ordering, but may appear
2172// afterward.
2173int WasmSectionOrderChecker::DisallowedPredecessors2174[WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {2175// WASM_SEC_ORDER_NONE2176{},2177// WASM_SEC_ORDER_TYPE2178{WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},2179// WASM_SEC_ORDER_IMPORT2180{WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},2181// WASM_SEC_ORDER_FUNCTION2182{WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},2183// WASM_SEC_ORDER_TABLE2184{WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},2185// WASM_SEC_ORDER_MEMORY2186{WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_TAG},2187// WASM_SEC_ORDER_TAG2188{WASM_SEC_ORDER_TAG, WASM_SEC_ORDER_GLOBAL},2189// WASM_SEC_ORDER_GLOBAL2190{WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},2191// WASM_SEC_ORDER_EXPORT2192{WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},2193// WASM_SEC_ORDER_START2194{WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},2195// WASM_SEC_ORDER_ELEM2196{WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},2197// WASM_SEC_ORDER_DATACOUNT2198{WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},2199// WASM_SEC_ORDER_CODE2200{WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},2201// WASM_SEC_ORDER_DATA2202{WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},2203
2204// Custom Sections2205// WASM_SEC_ORDER_DYLINK2206{WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},2207// WASM_SEC_ORDER_LINKING2208{WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},2209// WASM_SEC_ORDER_RELOC (can be repeated)2210{},2211// WASM_SEC_ORDER_NAME2212{WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},2213// WASM_SEC_ORDER_PRODUCERS2214{WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},2215// WASM_SEC_ORDER_TARGET_FEATURES2216{WASM_SEC_ORDER_TARGET_FEATURES}};2217
2218bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,2219StringRef CustomSectionName) {2220int Order = getSectionOrder(ID, CustomSectionName);2221if (Order == WASM_SEC_ORDER_NONE)2222return true;2223
2224// Disallowed predecessors we need to check for2225SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;2226
2227// Keep track of completed checks to avoid repeating work2228bool Checked[WASM_NUM_SEC_ORDERS] = {};2229
2230int Curr = Order;2231while (true) {2232// Add new disallowed predecessors to work list2233for (size_t I = 0;; ++I) {2234int Next = DisallowedPredecessors[Curr][I];2235if (Next == WASM_SEC_ORDER_NONE)2236break;2237if (Checked[Next])2238continue;2239WorkList.push_back(Next);2240Checked[Next] = true;2241}2242
2243if (WorkList.empty())2244break;2245
2246// Consider next disallowed predecessor2247Curr = WorkList.pop_back_val();2248if (Seen[Curr])2249return false;2250}2251
2252// Have not seen any disallowed predecessors2253Seen[Order] = true;2254return true;2255}
2256