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/STLExtras.h" 12 #include "llvm/ADT/SmallSet.h" 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/ADT/StringSet.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/BinaryFormat/Wasm.h" 18 #include "llvm/MC/SubtargetFeature.h" 19 #include "llvm/Object/Binary.h" 20 #include "llvm/Object/Error.h" 21 #include "llvm/Object/ObjectFile.h" 22 #include "llvm/Object/SymbolicFile.h" 23 #include "llvm/Object/Wasm.h" 24 #include "llvm/Support/Endian.h" 25 #include "llvm/Support/Error.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/LEB128.h" 28 #include "llvm/Support/ScopedPrinter.h" 29 #include <algorithm> 30 #include <cassert> 31 #include <cstdint> 32 #include <cstring> 33 #include <system_error> 34 35 #define DEBUG_TYPE "wasm-object" 36 37 using namespace llvm; 38 using namespace object; 39 40 void WasmSymbol::print(raw_ostream &Out) const { 41 Out << "Name=" << Info.Name 42 << ", Kind=" << toString(wasm::WasmSymbolType(Info.Kind)) 43 << ", Flags=" << Info.Flags; 44 if (!isTypeData()) { 45 Out << ", ElemIndex=" << Info.ElementIndex; 46 } else if (isDefined()) { 47 Out << ", Segment=" << Info.DataRef.Segment; 48 Out << ", Offset=" << Info.DataRef.Offset; 49 Out << ", Size=" << Info.DataRef.Size; 50 } 51 } 52 53 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 54 LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); } 55 #endif 56 57 Expected<std::unique_ptr<WasmObjectFile>> 58 ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) { 59 Error Err = Error::success(); 60 auto ObjectFile = std::make_unique<WasmObjectFile>(Buffer, Err); 61 if (Err) 62 return std::move(Err); 63 64 return std::move(ObjectFile); 65 } 66 67 #define VARINT7_MAX ((1 << 7) - 1) 68 #define VARINT7_MIN (-(1 << 7)) 69 #define VARUINT7_MAX (1 << 7) 70 #define VARUINT1_MAX (1) 71 72 static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) { 73 if (Ctx.Ptr == Ctx.End) 74 report_fatal_error("EOF while reading uint8"); 75 return *Ctx.Ptr++; 76 } 77 78 static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) { 79 if (Ctx.Ptr + 4 > Ctx.End) 80 report_fatal_error("EOF while reading uint32"); 81 uint32_t Result = support::endian::read32le(Ctx.Ptr); 82 Ctx.Ptr += 4; 83 return Result; 84 } 85 86 static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) { 87 if (Ctx.Ptr + 4 > Ctx.End) 88 report_fatal_error("EOF while reading float64"); 89 int32_t Result = 0; 90 memcpy(&Result, Ctx.Ptr, sizeof(Result)); 91 Ctx.Ptr += sizeof(Result); 92 return Result; 93 } 94 95 static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) { 96 if (Ctx.Ptr + 8 > Ctx.End) 97 report_fatal_error("EOF while reading float64"); 98 int64_t Result = 0; 99 memcpy(&Result, Ctx.Ptr, sizeof(Result)); 100 Ctx.Ptr += sizeof(Result); 101 return Result; 102 } 103 104 static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) { 105 unsigned Count; 106 const char *Error = nullptr; 107 uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error); 108 if (Error) 109 report_fatal_error(Error); 110 Ctx.Ptr += Count; 111 return Result; 112 } 113 114 static StringRef readString(WasmObjectFile::ReadContext &Ctx) { 115 uint32_t StringLen = readULEB128(Ctx); 116 if (Ctx.Ptr + StringLen > Ctx.End) 117 report_fatal_error("EOF while reading string"); 118 StringRef Return = 119 StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen); 120 Ctx.Ptr += StringLen; 121 return Return; 122 } 123 124 static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) { 125 unsigned Count; 126 const char *Error = nullptr; 127 uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error); 128 if (Error) 129 report_fatal_error(Error); 130 Ctx.Ptr += Count; 131 return Result; 132 } 133 134 static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) { 135 int64_t Result = readLEB128(Ctx); 136 if (Result > VARUINT1_MAX || Result < 0) 137 report_fatal_error("LEB is outside Varuint1 range"); 138 return Result; 139 } 140 141 static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) { 142 int64_t Result = readLEB128(Ctx); 143 if (Result > INT32_MAX || Result < INT32_MIN) 144 report_fatal_error("LEB is outside Varint32 range"); 145 return Result; 146 } 147 148 static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) { 149 uint64_t Result = readULEB128(Ctx); 150 if (Result > UINT32_MAX) 151 report_fatal_error("LEB is outside Varuint32 range"); 152 return Result; 153 } 154 155 static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) { 156 return readLEB128(Ctx); 157 } 158 159 static uint64_t readVaruint64(WasmObjectFile::ReadContext &Ctx) { 160 return readULEB128(Ctx); 161 } 162 163 static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) { 164 return readUint8(Ctx); 165 } 166 167 static Error readInitExpr(wasm::WasmInitExpr &Expr, 168 WasmObjectFile::ReadContext &Ctx) { 169 Expr.Opcode = readOpcode(Ctx); 170 171 switch (Expr.Opcode) { 172 case wasm::WASM_OPCODE_I32_CONST: 173 Expr.Value.Int32 = readVarint32(Ctx); 174 break; 175 case wasm::WASM_OPCODE_I64_CONST: 176 Expr.Value.Int64 = readVarint64(Ctx); 177 break; 178 case wasm::WASM_OPCODE_F32_CONST: 179 Expr.Value.Float32 = readFloat32(Ctx); 180 break; 181 case wasm::WASM_OPCODE_F64_CONST: 182 Expr.Value.Float64 = readFloat64(Ctx); 183 break; 184 case wasm::WASM_OPCODE_GLOBAL_GET: 185 Expr.Value.Global = readULEB128(Ctx); 186 break; 187 case wasm::WASM_OPCODE_REF_NULL: { 188 wasm::ValType Ty = static_cast<wasm::ValType>(readULEB128(Ctx)); 189 if (Ty != wasm::ValType::EXTERNREF) { 190 return make_error<GenericBinaryError>("Invalid type for ref.null", 191 object_error::parse_failed); 192 } 193 break; 194 } 195 default: 196 return make_error<GenericBinaryError>("Invalid opcode in init_expr", 197 object_error::parse_failed); 198 } 199 200 uint8_t EndOpcode = readOpcode(Ctx); 201 if (EndOpcode != wasm::WASM_OPCODE_END) { 202 return make_error<GenericBinaryError>("Invalid init_expr", 203 object_error::parse_failed); 204 } 205 return Error::success(); 206 } 207 208 static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) { 209 wasm::WasmLimits Result; 210 Result.Flags = readVaruint32(Ctx); 211 Result.Initial = readVaruint64(Ctx); 212 if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX) 213 Result.Maximum = readVaruint64(Ctx); 214 return Result; 215 } 216 217 static wasm::WasmTableType readTableType(WasmObjectFile::ReadContext &Ctx) { 218 wasm::WasmTableType TableType; 219 TableType.ElemType = readUint8(Ctx); 220 TableType.Limits = readLimits(Ctx); 221 return TableType; 222 } 223 224 static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx, 225 WasmSectionOrderChecker &Checker) { 226 Section.Offset = Ctx.Ptr - Ctx.Start; 227 Section.Type = readUint8(Ctx); 228 LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n"); 229 uint32_t Size = readVaruint32(Ctx); 230 if (Size == 0) 231 return make_error<StringError>("Zero length section", 232 object_error::parse_failed); 233 if (Ctx.Ptr + Size > Ctx.End) 234 return make_error<StringError>("Section too large", 235 object_error::parse_failed); 236 if (Section.Type == wasm::WASM_SEC_CUSTOM) { 237 WasmObjectFile::ReadContext SectionCtx; 238 SectionCtx.Start = Ctx.Ptr; 239 SectionCtx.Ptr = Ctx.Ptr; 240 SectionCtx.End = Ctx.Ptr + Size; 241 242 Section.Name = readString(SectionCtx); 243 244 uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start; 245 Ctx.Ptr += SectionNameSize; 246 Size -= SectionNameSize; 247 } 248 249 if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) { 250 return make_error<StringError>("Out of order section type: " + 251 llvm::to_string(Section.Type), 252 object_error::parse_failed); 253 } 254 255 Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size); 256 Ctx.Ptr += Size; 257 return Error::success(); 258 } 259 260 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err) 261 : ObjectFile(Binary::ID_Wasm, Buffer) { 262 ErrorAsOutParameter ErrAsOutParam(&Err); 263 Header.Magic = getData().substr(0, 4); 264 if (Header.Magic != StringRef("\0asm", 4)) { 265 Err = 266 make_error<StringError>("Bad magic number", object_error::parse_failed); 267 return; 268 } 269 270 ReadContext Ctx; 271 Ctx.Start = getData().bytes_begin(); 272 Ctx.Ptr = Ctx.Start + 4; 273 Ctx.End = Ctx.Start + getData().size(); 274 275 if (Ctx.Ptr + 4 > Ctx.End) { 276 Err = make_error<StringError>("Missing version number", 277 object_error::parse_failed); 278 return; 279 } 280 281 Header.Version = readUint32(Ctx); 282 if (Header.Version != wasm::WasmVersion) { 283 Err = make_error<StringError>("Bad version number", 284 object_error::parse_failed); 285 return; 286 } 287 288 WasmSection Sec; 289 WasmSectionOrderChecker Checker; 290 while (Ctx.Ptr < Ctx.End) { 291 if ((Err = readSection(Sec, Ctx, Checker))) 292 return; 293 if ((Err = parseSection(Sec))) 294 return; 295 296 Sections.push_back(Sec); 297 } 298 } 299 300 Error WasmObjectFile::parseSection(WasmSection &Sec) { 301 ReadContext Ctx; 302 Ctx.Start = Sec.Content.data(); 303 Ctx.End = Ctx.Start + Sec.Content.size(); 304 Ctx.Ptr = Ctx.Start; 305 switch (Sec.Type) { 306 case wasm::WASM_SEC_CUSTOM: 307 return parseCustomSection(Sec, Ctx); 308 case wasm::WASM_SEC_TYPE: 309 return parseTypeSection(Ctx); 310 case wasm::WASM_SEC_IMPORT: 311 return parseImportSection(Ctx); 312 case wasm::WASM_SEC_FUNCTION: 313 return parseFunctionSection(Ctx); 314 case wasm::WASM_SEC_TABLE: 315 return parseTableSection(Ctx); 316 case wasm::WASM_SEC_MEMORY: 317 return parseMemorySection(Ctx); 318 case wasm::WASM_SEC_EVENT: 319 return parseEventSection(Ctx); 320 case wasm::WASM_SEC_GLOBAL: 321 return parseGlobalSection(Ctx); 322 case wasm::WASM_SEC_EXPORT: 323 return parseExportSection(Ctx); 324 case wasm::WASM_SEC_START: 325 return parseStartSection(Ctx); 326 case wasm::WASM_SEC_ELEM: 327 return parseElemSection(Ctx); 328 case wasm::WASM_SEC_CODE: 329 return parseCodeSection(Ctx); 330 case wasm::WASM_SEC_DATA: 331 return parseDataSection(Ctx); 332 case wasm::WASM_SEC_DATACOUNT: 333 return parseDataCountSection(Ctx); 334 default: 335 return make_error<GenericBinaryError>( 336 "Invalid section type: " + Twine(Sec.Type), object_error::parse_failed); 337 } 338 } 339 340 Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) { 341 // See https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md 342 HasDylinkSection = true; 343 DylinkInfo.MemorySize = readVaruint32(Ctx); 344 DylinkInfo.MemoryAlignment = readVaruint32(Ctx); 345 DylinkInfo.TableSize = readVaruint32(Ctx); 346 DylinkInfo.TableAlignment = readVaruint32(Ctx); 347 uint32_t Count = readVaruint32(Ctx); 348 while (Count--) { 349 DylinkInfo.Needed.push_back(readString(Ctx)); 350 } 351 if (Ctx.Ptr != Ctx.End) 352 return make_error<GenericBinaryError>("dylink section ended prematurely", 353 object_error::parse_failed); 354 return Error::success(); 355 } 356 357 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) { 358 llvm::DenseSet<uint64_t> SeenFunctions; 359 llvm::DenseSet<uint64_t> SeenGlobals; 360 if (FunctionTypes.size() && !SeenCodeSection) { 361 return make_error<GenericBinaryError>("Names must come after code section", 362 object_error::parse_failed); 363 } 364 365 while (Ctx.Ptr < Ctx.End) { 366 uint8_t Type = readUint8(Ctx); 367 uint32_t Size = readVaruint32(Ctx); 368 const uint8_t *SubSectionEnd = Ctx.Ptr + Size; 369 switch (Type) { 370 case wasm::WASM_NAMES_FUNCTION: 371 case wasm::WASM_NAMES_GLOBAL: { 372 uint32_t Count = readVaruint32(Ctx); 373 while (Count--) { 374 uint32_t Index = readVaruint32(Ctx); 375 StringRef Name = readString(Ctx); 376 if (Type == wasm::WASM_NAMES_FUNCTION) { 377 if (!SeenFunctions.insert(Index).second) 378 return make_error<GenericBinaryError>( 379 "Function named more than once", object_error::parse_failed); 380 if (!isValidFunctionIndex(Index) || Name.empty()) 381 return make_error<GenericBinaryError>("Invalid name entry", 382 object_error::parse_failed); 383 384 if (isDefinedFunctionIndex(Index)) 385 getDefinedFunction(Index).DebugName = Name; 386 } else { 387 if (!SeenGlobals.insert(Index).second) 388 return make_error<GenericBinaryError>("Global named more than once", 389 object_error::parse_failed); 390 if (!isValidGlobalIndex(Index) || Name.empty()) 391 return make_error<GenericBinaryError>("Invalid name entry", 392 object_error::parse_failed); 393 } 394 wasm::NameType T = Type == wasm::WASM_NAMES_FUNCTION 395 ? wasm::NameType::FUNCTION 396 : wasm::NameType::GLOBAL; 397 DebugNames.push_back(wasm::WasmDebugName{T, Index, Name}); 398 } 399 break; 400 } 401 // Ignore local names for now 402 case wasm::WASM_NAMES_LOCAL: 403 default: 404 Ctx.Ptr += Size; 405 break; 406 } 407 if (Ctx.Ptr != SubSectionEnd) 408 return make_error<GenericBinaryError>( 409 "Name sub-section ended prematurely", object_error::parse_failed); 410 } 411 412 if (Ctx.Ptr != Ctx.End) 413 return make_error<GenericBinaryError>("Name section ended prematurely", 414 object_error::parse_failed); 415 return Error::success(); 416 } 417 418 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) { 419 HasLinkingSection = true; 420 if (FunctionTypes.size() && !SeenCodeSection) { 421 return make_error<GenericBinaryError>( 422 "Linking data must come after code section", 423 object_error::parse_failed); 424 } 425 426 LinkingData.Version = readVaruint32(Ctx); 427 if (LinkingData.Version != wasm::WasmMetadataVersion) { 428 return make_error<GenericBinaryError>( 429 "Unexpected metadata version: " + Twine(LinkingData.Version) + 430 " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")", 431 object_error::parse_failed); 432 } 433 434 const uint8_t *OrigEnd = Ctx.End; 435 while (Ctx.Ptr < OrigEnd) { 436 Ctx.End = OrigEnd; 437 uint8_t Type = readUint8(Ctx); 438 uint32_t Size = readVaruint32(Ctx); 439 LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size 440 << "\n"); 441 Ctx.End = Ctx.Ptr + Size; 442 switch (Type) { 443 case wasm::WASM_SYMBOL_TABLE: 444 if (Error Err = parseLinkingSectionSymtab(Ctx)) 445 return Err; 446 break; 447 case wasm::WASM_SEGMENT_INFO: { 448 uint32_t Count = readVaruint32(Ctx); 449 if (Count > DataSegments.size()) 450 return make_error<GenericBinaryError>("Too many segment names", 451 object_error::parse_failed); 452 for (uint32_t I = 0; I < Count; I++) { 453 DataSegments[I].Data.Name = readString(Ctx); 454 DataSegments[I].Data.Alignment = readVaruint32(Ctx); 455 DataSegments[I].Data.LinkerFlags = readVaruint32(Ctx); 456 } 457 break; 458 } 459 case wasm::WASM_INIT_FUNCS: { 460 uint32_t Count = readVaruint32(Ctx); 461 LinkingData.InitFunctions.reserve(Count); 462 for (uint32_t I = 0; I < Count; I++) { 463 wasm::WasmInitFunc Init; 464 Init.Priority = readVaruint32(Ctx); 465 Init.Symbol = readVaruint32(Ctx); 466 if (!isValidFunctionSymbol(Init.Symbol)) 467 return make_error<GenericBinaryError>("Invalid function symbol: " + 468 Twine(Init.Symbol), 469 object_error::parse_failed); 470 LinkingData.InitFunctions.emplace_back(Init); 471 } 472 break; 473 } 474 case wasm::WASM_COMDAT_INFO: 475 if (Error Err = parseLinkingSectionComdat(Ctx)) 476 return Err; 477 break; 478 default: 479 Ctx.Ptr += Size; 480 break; 481 } 482 if (Ctx.Ptr != Ctx.End) 483 return make_error<GenericBinaryError>( 484 "Linking sub-section ended prematurely", object_error::parse_failed); 485 } 486 if (Ctx.Ptr != OrigEnd) 487 return make_error<GenericBinaryError>("Linking section ended prematurely", 488 object_error::parse_failed); 489 return Error::success(); 490 } 491 492 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) { 493 uint32_t Count = readVaruint32(Ctx); 494 LinkingData.SymbolTable.reserve(Count); 495 Symbols.reserve(Count); 496 StringSet<> SymbolNames; 497 498 std::vector<wasm::WasmImport *> ImportedGlobals; 499 std::vector<wasm::WasmImport *> ImportedFunctions; 500 std::vector<wasm::WasmImport *> ImportedEvents; 501 std::vector<wasm::WasmImport *> ImportedTables; 502 ImportedGlobals.reserve(Imports.size()); 503 ImportedFunctions.reserve(Imports.size()); 504 ImportedEvents.reserve(Imports.size()); 505 ImportedTables.reserve(Imports.size()); 506 for (auto &I : Imports) { 507 if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION) 508 ImportedFunctions.emplace_back(&I); 509 else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL) 510 ImportedGlobals.emplace_back(&I); 511 else if (I.Kind == wasm::WASM_EXTERNAL_EVENT) 512 ImportedEvents.emplace_back(&I); 513 else if (I.Kind == wasm::WASM_EXTERNAL_TABLE) 514 ImportedTables.emplace_back(&I); 515 } 516 517 while (Count--) { 518 wasm::WasmSymbolInfo Info; 519 const wasm::WasmSignature *Signature = nullptr; 520 const wasm::WasmGlobalType *GlobalType = nullptr; 521 uint8_t TableType = 0; 522 const wasm::WasmEventType *EventType = nullptr; 523 524 Info.Kind = readUint8(Ctx); 525 Info.Flags = readVaruint32(Ctx); 526 bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0; 527 528 switch (Info.Kind) { 529 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 530 Info.ElementIndex = readVaruint32(Ctx); 531 if (!isValidFunctionIndex(Info.ElementIndex) || 532 IsDefined != isDefinedFunctionIndex(Info.ElementIndex)) 533 return make_error<GenericBinaryError>("invalid function symbol index", 534 object_error::parse_failed); 535 if (IsDefined) { 536 Info.Name = readString(Ctx); 537 unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions; 538 Signature = &Signatures[FunctionTypes[FuncIndex]]; 539 wasm::WasmFunction &Function = Functions[FuncIndex]; 540 if (Function.SymbolName.empty()) 541 Function.SymbolName = Info.Name; 542 } else { 543 wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex]; 544 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 545 Info.Name = readString(Ctx); 546 Info.ImportName = Import.Field; 547 } else { 548 Info.Name = Import.Field; 549 } 550 Signature = &Signatures[Import.SigIndex]; 551 if (!Import.Module.empty()) { 552 Info.ImportModule = Import.Module; 553 } 554 } 555 break; 556 557 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 558 Info.ElementIndex = readVaruint32(Ctx); 559 if (!isValidGlobalIndex(Info.ElementIndex) || 560 IsDefined != isDefinedGlobalIndex(Info.ElementIndex)) 561 return make_error<GenericBinaryError>("invalid global symbol index", 562 object_error::parse_failed); 563 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 564 wasm::WASM_SYMBOL_BINDING_WEAK) 565 return make_error<GenericBinaryError>("undefined weak global symbol", 566 object_error::parse_failed); 567 if (IsDefined) { 568 Info.Name = readString(Ctx); 569 unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals; 570 wasm::WasmGlobal &Global = Globals[GlobalIndex]; 571 GlobalType = &Global.Type; 572 if (Global.SymbolName.empty()) 573 Global.SymbolName = Info.Name; 574 } else { 575 wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex]; 576 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 577 Info.Name = readString(Ctx); 578 Info.ImportName = Import.Field; 579 } else { 580 Info.Name = Import.Field; 581 } 582 GlobalType = &Import.Global; 583 if (!Import.Module.empty()) { 584 Info.ImportModule = Import.Module; 585 } 586 } 587 break; 588 589 case wasm::WASM_SYMBOL_TYPE_TABLE: 590 Info.ElementIndex = readVaruint32(Ctx); 591 if (!isValidTableIndex(Info.ElementIndex) || 592 IsDefined != isDefinedTableIndex(Info.ElementIndex)) 593 return make_error<GenericBinaryError>("invalid table symbol index", 594 object_error::parse_failed); 595 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 596 wasm::WASM_SYMBOL_BINDING_WEAK) 597 return make_error<GenericBinaryError>("undefined weak table symbol", 598 object_error::parse_failed); 599 if (IsDefined) { 600 Info.Name = readString(Ctx); 601 unsigned TableIndex = Info.ElementIndex - NumImportedTables; 602 wasm::WasmTable &Table = Tables[TableIndex]; 603 TableType = Table.Type.ElemType; 604 if (Table.SymbolName.empty()) 605 Table.SymbolName = Info.Name; 606 } else { 607 wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex]; 608 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 609 Info.Name = readString(Ctx); 610 Info.ImportName = Import.Field; 611 } else { 612 Info.Name = Import.Field; 613 } 614 TableType = Import.Table.ElemType; 615 // FIXME: Parse limits here too. 616 if (!Import.Module.empty()) { 617 Info.ImportModule = Import.Module; 618 } 619 } 620 break; 621 622 case wasm::WASM_SYMBOL_TYPE_DATA: 623 Info.Name = readString(Ctx); 624 if (IsDefined) { 625 auto Index = readVaruint32(Ctx); 626 if (Index >= DataSegments.size()) 627 return make_error<GenericBinaryError>("invalid data symbol index", 628 object_error::parse_failed); 629 auto Offset = readVaruint64(Ctx); 630 auto Size = readVaruint64(Ctx); 631 if (Offset + Size > DataSegments[Index].Data.Content.size()) 632 return make_error<GenericBinaryError>("invalid data symbol offset", 633 object_error::parse_failed); 634 Info.DataRef = wasm::WasmDataReference{Index, Offset, Size}; 635 } 636 break; 637 638 case wasm::WASM_SYMBOL_TYPE_SECTION: { 639 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) != 640 wasm::WASM_SYMBOL_BINDING_LOCAL) 641 return make_error<GenericBinaryError>( 642 "Section symbols must have local binding", 643 object_error::parse_failed); 644 Info.ElementIndex = readVaruint32(Ctx); 645 // Use somewhat unique section name as symbol name. 646 StringRef SectionName = Sections[Info.ElementIndex].Name; 647 Info.Name = SectionName; 648 break; 649 } 650 651 case wasm::WASM_SYMBOL_TYPE_EVENT: { 652 Info.ElementIndex = readVaruint32(Ctx); 653 if (!isValidEventIndex(Info.ElementIndex) || 654 IsDefined != isDefinedEventIndex(Info.ElementIndex)) 655 return make_error<GenericBinaryError>("invalid event symbol index", 656 object_error::parse_failed); 657 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 658 wasm::WASM_SYMBOL_BINDING_WEAK) 659 return make_error<GenericBinaryError>("undefined weak global symbol", 660 object_error::parse_failed); 661 if (IsDefined) { 662 Info.Name = readString(Ctx); 663 unsigned EventIndex = Info.ElementIndex - NumImportedEvents; 664 wasm::WasmEvent &Event = Events[EventIndex]; 665 Signature = &Signatures[Event.Type.SigIndex]; 666 EventType = &Event.Type; 667 if (Event.SymbolName.empty()) 668 Event.SymbolName = Info.Name; 669 670 } else { 671 wasm::WasmImport &Import = *ImportedEvents[Info.ElementIndex]; 672 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 673 Info.Name = readString(Ctx); 674 Info.ImportName = Import.Field; 675 } else { 676 Info.Name = Import.Field; 677 } 678 EventType = &Import.Event; 679 Signature = &Signatures[EventType->SigIndex]; 680 if (!Import.Module.empty()) { 681 Info.ImportModule = Import.Module; 682 } 683 } 684 break; 685 } 686 687 default: 688 return make_error<GenericBinaryError>("Invalid symbol type", 689 object_error::parse_failed); 690 } 691 692 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) != 693 wasm::WASM_SYMBOL_BINDING_LOCAL && 694 !SymbolNames.insert(Info.Name).second) 695 return make_error<GenericBinaryError>("Duplicate symbol name " + 696 Twine(Info.Name), 697 object_error::parse_failed); 698 LinkingData.SymbolTable.emplace_back(Info); 699 Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType, TableType, 700 EventType, Signature); 701 LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n"); 702 } 703 704 return Error::success(); 705 } 706 707 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) { 708 uint32_t ComdatCount = readVaruint32(Ctx); 709 StringSet<> ComdatSet; 710 for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) { 711 StringRef Name = readString(Ctx); 712 if (Name.empty() || !ComdatSet.insert(Name).second) 713 return make_error<GenericBinaryError>("Bad/duplicate COMDAT name " + 714 Twine(Name), 715 object_error::parse_failed); 716 LinkingData.Comdats.emplace_back(Name); 717 uint32_t Flags = readVaruint32(Ctx); 718 if (Flags != 0) 719 return make_error<GenericBinaryError>("Unsupported COMDAT flags", 720 object_error::parse_failed); 721 722 uint32_t EntryCount = readVaruint32(Ctx); 723 while (EntryCount--) { 724 unsigned Kind = readVaruint32(Ctx); 725 unsigned Index = readVaruint32(Ctx); 726 switch (Kind) { 727 default: 728 return make_error<GenericBinaryError>("Invalid COMDAT entry type", 729 object_error::parse_failed); 730 case wasm::WASM_COMDAT_DATA: 731 if (Index >= DataSegments.size()) 732 return make_error<GenericBinaryError>( 733 "COMDAT data index out of range", object_error::parse_failed); 734 if (DataSegments[Index].Data.Comdat != UINT32_MAX) 735 return make_error<GenericBinaryError>("Data segment in two COMDATs", 736 object_error::parse_failed); 737 DataSegments[Index].Data.Comdat = ComdatIndex; 738 break; 739 case wasm::WASM_COMDAT_FUNCTION: 740 if (!isDefinedFunctionIndex(Index)) 741 return make_error<GenericBinaryError>( 742 "COMDAT function index out of range", object_error::parse_failed); 743 if (getDefinedFunction(Index).Comdat != UINT32_MAX) 744 return make_error<GenericBinaryError>("Function in two COMDATs", 745 object_error::parse_failed); 746 getDefinedFunction(Index).Comdat = ComdatIndex; 747 break; 748 case wasm::WASM_COMDAT_SECTION: 749 if (Index >= Sections.size()) 750 return make_error<GenericBinaryError>( 751 "COMDAT section index out of range", object_error::parse_failed); 752 if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM) 753 return make_error<GenericBinaryError>( 754 "Non-custom section in a COMDAT", object_error::parse_failed); 755 Sections[Index].Comdat = ComdatIndex; 756 break; 757 } 758 } 759 } 760 return Error::success(); 761 } 762 763 Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) { 764 llvm::SmallSet<StringRef, 3> FieldsSeen; 765 uint32_t Fields = readVaruint32(Ctx); 766 for (size_t I = 0; I < Fields; ++I) { 767 StringRef FieldName = readString(Ctx); 768 if (!FieldsSeen.insert(FieldName).second) 769 return make_error<GenericBinaryError>( 770 "Producers section does not have unique fields", 771 object_error::parse_failed); 772 std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr; 773 if (FieldName == "language") { 774 ProducerVec = &ProducerInfo.Languages; 775 } else if (FieldName == "processed-by") { 776 ProducerVec = &ProducerInfo.Tools; 777 } else if (FieldName == "sdk") { 778 ProducerVec = &ProducerInfo.SDKs; 779 } else { 780 return make_error<GenericBinaryError>( 781 "Producers section field is not named one of language, processed-by, " 782 "or sdk", 783 object_error::parse_failed); 784 } 785 uint32_t ValueCount = readVaruint32(Ctx); 786 llvm::SmallSet<StringRef, 8> ProducersSeen; 787 for (size_t J = 0; J < ValueCount; ++J) { 788 StringRef Name = readString(Ctx); 789 StringRef Version = readString(Ctx); 790 if (!ProducersSeen.insert(Name).second) { 791 return make_error<GenericBinaryError>( 792 "Producers section contains repeated producer", 793 object_error::parse_failed); 794 } 795 ProducerVec->emplace_back(std::string(Name), std::string(Version)); 796 } 797 } 798 if (Ctx.Ptr != Ctx.End) 799 return make_error<GenericBinaryError>("Producers section ended prematurely", 800 object_error::parse_failed); 801 return Error::success(); 802 } 803 804 Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) { 805 llvm::SmallSet<std::string, 8> FeaturesSeen; 806 uint32_t FeatureCount = readVaruint32(Ctx); 807 for (size_t I = 0; I < FeatureCount; ++I) { 808 wasm::WasmFeatureEntry Feature; 809 Feature.Prefix = readUint8(Ctx); 810 switch (Feature.Prefix) { 811 case wasm::WASM_FEATURE_PREFIX_USED: 812 case wasm::WASM_FEATURE_PREFIX_REQUIRED: 813 case wasm::WASM_FEATURE_PREFIX_DISALLOWED: 814 break; 815 default: 816 return make_error<GenericBinaryError>("Unknown feature policy prefix", 817 object_error::parse_failed); 818 } 819 Feature.Name = std::string(readString(Ctx)); 820 if (!FeaturesSeen.insert(Feature.Name).second) 821 return make_error<GenericBinaryError>( 822 "Target features section contains repeated feature \"" + 823 Feature.Name + "\"", 824 object_error::parse_failed); 825 TargetFeatures.push_back(Feature); 826 } 827 if (Ctx.Ptr != Ctx.End) 828 return make_error<GenericBinaryError>( 829 "Target features section ended prematurely", 830 object_error::parse_failed); 831 return Error::success(); 832 } 833 834 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) { 835 uint32_t SectionIndex = readVaruint32(Ctx); 836 if (SectionIndex >= Sections.size()) 837 return make_error<GenericBinaryError>("Invalid section index", 838 object_error::parse_failed); 839 WasmSection &Section = Sections[SectionIndex]; 840 uint32_t RelocCount = readVaruint32(Ctx); 841 uint32_t EndOffset = Section.Content.size(); 842 uint32_t PreviousOffset = 0; 843 while (RelocCount--) { 844 wasm::WasmRelocation Reloc = {}; 845 Reloc.Type = readVaruint32(Ctx); 846 Reloc.Offset = readVaruint32(Ctx); 847 if (Reloc.Offset < PreviousOffset) 848 return make_error<GenericBinaryError>("Relocations not in offset order", 849 object_error::parse_failed); 850 PreviousOffset = Reloc.Offset; 851 Reloc.Index = readVaruint32(Ctx); 852 switch (Reloc.Type) { 853 case wasm::R_WASM_FUNCTION_INDEX_LEB: 854 case wasm::R_WASM_TABLE_INDEX_SLEB: 855 case wasm::R_WASM_TABLE_INDEX_SLEB64: 856 case wasm::R_WASM_TABLE_INDEX_I32: 857 case wasm::R_WASM_TABLE_INDEX_I64: 858 case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 859 if (!isValidFunctionSymbol(Reloc.Index)) 860 return make_error<GenericBinaryError>("Bad relocation function index", 861 object_error::parse_failed); 862 break; 863 case wasm::R_WASM_TABLE_NUMBER_LEB: 864 if (!isValidTableSymbol(Reloc.Index)) 865 return make_error<GenericBinaryError>("Bad relocation table index", 866 object_error::parse_failed); 867 break; 868 case wasm::R_WASM_TYPE_INDEX_LEB: 869 if (Reloc.Index >= Signatures.size()) 870 return make_error<GenericBinaryError>("Bad relocation type index", 871 object_error::parse_failed); 872 break; 873 case wasm::R_WASM_GLOBAL_INDEX_LEB: 874 // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data 875 // symbols to refer to their GOT entries. 876 if (!isValidGlobalSymbol(Reloc.Index) && 877 !isValidDataSymbol(Reloc.Index) && 878 !isValidFunctionSymbol(Reloc.Index)) 879 return make_error<GenericBinaryError>("Bad relocation global index", 880 object_error::parse_failed); 881 break; 882 case wasm::R_WASM_GLOBAL_INDEX_I32: 883 if (!isValidGlobalSymbol(Reloc.Index)) 884 return make_error<GenericBinaryError>("Bad relocation global index", 885 object_error::parse_failed); 886 break; 887 case wasm::R_WASM_EVENT_INDEX_LEB: 888 if (!isValidEventSymbol(Reloc.Index)) 889 return make_error<GenericBinaryError>("Bad relocation event index", 890 object_error::parse_failed); 891 break; 892 case wasm::R_WASM_MEMORY_ADDR_LEB: 893 case wasm::R_WASM_MEMORY_ADDR_SLEB: 894 case wasm::R_WASM_MEMORY_ADDR_I32: 895 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 896 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: 897 if (!isValidDataSymbol(Reloc.Index)) 898 return make_error<GenericBinaryError>("Bad relocation data index", 899 object_error::parse_failed); 900 Reloc.Addend = readVarint32(Ctx); 901 break; 902 case wasm::R_WASM_MEMORY_ADDR_LEB64: 903 case wasm::R_WASM_MEMORY_ADDR_SLEB64: 904 case wasm::R_WASM_MEMORY_ADDR_I64: 905 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 906 if (!isValidDataSymbol(Reloc.Index)) 907 return make_error<GenericBinaryError>("Bad relocation data index", 908 object_error::parse_failed); 909 Reloc.Addend = readVarint64(Ctx); 910 break; 911 case wasm::R_WASM_FUNCTION_OFFSET_I32: 912 if (!isValidFunctionSymbol(Reloc.Index)) 913 return make_error<GenericBinaryError>("Bad relocation function index", 914 object_error::parse_failed); 915 Reloc.Addend = readVarint32(Ctx); 916 break; 917 case wasm::R_WASM_FUNCTION_OFFSET_I64: 918 if (!isValidFunctionSymbol(Reloc.Index)) 919 return make_error<GenericBinaryError>("Bad relocation function index", 920 object_error::parse_failed); 921 Reloc.Addend = readVarint64(Ctx); 922 break; 923 case wasm::R_WASM_SECTION_OFFSET_I32: 924 if (!isValidSectionSymbol(Reloc.Index)) 925 return make_error<GenericBinaryError>("Bad relocation section index", 926 object_error::parse_failed); 927 Reloc.Addend = readVarint32(Ctx); 928 break; 929 default: 930 return make_error<GenericBinaryError>("Bad relocation type: " + 931 Twine(Reloc.Type), 932 object_error::parse_failed); 933 } 934 935 // Relocations must fit inside the section, and must appear in order. They 936 // also shouldn't overlap a function/element boundary, but we don't bother 937 // to check that. 938 uint64_t Size = 5; 939 if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 || 940 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 || 941 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64) 942 Size = 10; 943 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 || 944 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 || 945 Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 || 946 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 947 Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32) 948 Size = 4; 949 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 || 950 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 || 951 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64) 952 Size = 8; 953 if (Reloc.Offset + Size > EndOffset) 954 return make_error<GenericBinaryError>("Bad relocation offset", 955 object_error::parse_failed); 956 957 Section.Relocations.push_back(Reloc); 958 } 959 if (Ctx.Ptr != Ctx.End) 960 return make_error<GenericBinaryError>("Reloc section ended prematurely", 961 object_error::parse_failed); 962 return Error::success(); 963 } 964 965 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) { 966 if (Sec.Name == "dylink") { 967 if (Error Err = parseDylinkSection(Ctx)) 968 return Err; 969 } else if (Sec.Name == "name") { 970 if (Error Err = parseNameSection(Ctx)) 971 return Err; 972 } else if (Sec.Name == "linking") { 973 if (Error Err = parseLinkingSection(Ctx)) 974 return Err; 975 } else if (Sec.Name == "producers") { 976 if (Error Err = parseProducersSection(Ctx)) 977 return Err; 978 } else if (Sec.Name == "target_features") { 979 if (Error Err = parseTargetFeaturesSection(Ctx)) 980 return Err; 981 } else if (Sec.Name.startswith("reloc.")) { 982 if (Error Err = parseRelocSection(Sec.Name, Ctx)) 983 return Err; 984 } 985 return Error::success(); 986 } 987 988 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) { 989 uint32_t Count = readVaruint32(Ctx); 990 Signatures.reserve(Count); 991 while (Count--) { 992 wasm::WasmSignature Sig; 993 uint8_t Form = readUint8(Ctx); 994 if (Form != wasm::WASM_TYPE_FUNC) { 995 return make_error<GenericBinaryError>("Invalid signature type", 996 object_error::parse_failed); 997 } 998 uint32_t ParamCount = readVaruint32(Ctx); 999 Sig.Params.reserve(ParamCount); 1000 while (ParamCount--) { 1001 uint32_t ParamType = readUint8(Ctx); 1002 Sig.Params.push_back(wasm::ValType(ParamType)); 1003 } 1004 uint32_t ReturnCount = readVaruint32(Ctx); 1005 while (ReturnCount--) { 1006 uint32_t ReturnType = readUint8(Ctx); 1007 Sig.Returns.push_back(wasm::ValType(ReturnType)); 1008 } 1009 Signatures.push_back(std::move(Sig)); 1010 } 1011 if (Ctx.Ptr != Ctx.End) 1012 return make_error<GenericBinaryError>("Type section ended prematurely", 1013 object_error::parse_failed); 1014 return Error::success(); 1015 } 1016 1017 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) { 1018 uint32_t Count = readVaruint32(Ctx); 1019 Imports.reserve(Count); 1020 for (uint32_t I = 0; I < Count; I++) { 1021 wasm::WasmImport Im; 1022 Im.Module = readString(Ctx); 1023 Im.Field = readString(Ctx); 1024 Im.Kind = readUint8(Ctx); 1025 switch (Im.Kind) { 1026 case wasm::WASM_EXTERNAL_FUNCTION: 1027 NumImportedFunctions++; 1028 Im.SigIndex = readVaruint32(Ctx); 1029 break; 1030 case wasm::WASM_EXTERNAL_GLOBAL: 1031 NumImportedGlobals++; 1032 Im.Global.Type = readUint8(Ctx); 1033 Im.Global.Mutable = readVaruint1(Ctx); 1034 break; 1035 case wasm::WASM_EXTERNAL_MEMORY: 1036 Im.Memory = readLimits(Ctx); 1037 if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1038 HasMemory64 = true; 1039 break; 1040 case wasm::WASM_EXTERNAL_TABLE: { 1041 Im.Table = readTableType(Ctx); 1042 NumImportedTables++; 1043 auto ElemType = Im.Table.ElemType; 1044 if (ElemType != wasm::WASM_TYPE_FUNCREF && 1045 ElemType != wasm::WASM_TYPE_EXTERNREF) 1046 return make_error<GenericBinaryError>("Invalid table element type", 1047 object_error::parse_failed); 1048 break; 1049 } 1050 case wasm::WASM_EXTERNAL_EVENT: 1051 NumImportedEvents++; 1052 Im.Event.Attribute = readVarint32(Ctx); 1053 Im.Event.SigIndex = readVarint32(Ctx); 1054 break; 1055 default: 1056 return make_error<GenericBinaryError>("Unexpected import kind", 1057 object_error::parse_failed); 1058 } 1059 Imports.push_back(Im); 1060 } 1061 if (Ctx.Ptr != Ctx.End) 1062 return make_error<GenericBinaryError>("Import section ended prematurely", 1063 object_error::parse_failed); 1064 return Error::success(); 1065 } 1066 1067 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) { 1068 uint32_t Count = readVaruint32(Ctx); 1069 FunctionTypes.reserve(Count); 1070 Functions.resize(Count); 1071 uint32_t NumTypes = Signatures.size(); 1072 while (Count--) { 1073 uint32_t Type = readVaruint32(Ctx); 1074 if (Type >= NumTypes) 1075 return make_error<GenericBinaryError>("Invalid function type", 1076 object_error::parse_failed); 1077 FunctionTypes.push_back(Type); 1078 } 1079 if (Ctx.Ptr != Ctx.End) 1080 return make_error<GenericBinaryError>("Function section ended prematurely", 1081 object_error::parse_failed); 1082 return Error::success(); 1083 } 1084 1085 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) { 1086 TableSection = Sections.size(); 1087 uint32_t Count = readVaruint32(Ctx); 1088 Tables.reserve(Count); 1089 while (Count--) { 1090 wasm::WasmTable T; 1091 T.Type = readTableType(Ctx); 1092 T.Index = NumImportedTables + Tables.size(); 1093 Tables.push_back(T); 1094 auto ElemType = Tables.back().Type.ElemType; 1095 if (ElemType != wasm::WASM_TYPE_FUNCREF && 1096 ElemType != wasm::WASM_TYPE_EXTERNREF) { 1097 return make_error<GenericBinaryError>("Invalid table element type", 1098 object_error::parse_failed); 1099 } 1100 } 1101 if (Ctx.Ptr != Ctx.End) 1102 return make_error<GenericBinaryError>("Table section ended prematurely", 1103 object_error::parse_failed); 1104 return Error::success(); 1105 } 1106 1107 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) { 1108 uint32_t Count = readVaruint32(Ctx); 1109 Memories.reserve(Count); 1110 while (Count--) { 1111 auto Limits = readLimits(Ctx); 1112 if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1113 HasMemory64 = true; 1114 Memories.push_back(Limits); 1115 } 1116 if (Ctx.Ptr != Ctx.End) 1117 return make_error<GenericBinaryError>("Memory section ended prematurely", 1118 object_error::parse_failed); 1119 return Error::success(); 1120 } 1121 1122 Error WasmObjectFile::parseEventSection(ReadContext &Ctx) { 1123 EventSection = Sections.size(); 1124 uint32_t Count = readVarint32(Ctx); 1125 Events.reserve(Count); 1126 while (Count--) { 1127 wasm::WasmEvent Event; 1128 Event.Index = NumImportedEvents + Events.size(); 1129 Event.Type.Attribute = readVaruint32(Ctx); 1130 Event.Type.SigIndex = readVarint32(Ctx); 1131 Events.push_back(Event); 1132 } 1133 1134 if (Ctx.Ptr != Ctx.End) 1135 return make_error<GenericBinaryError>("Event section ended prematurely", 1136 object_error::parse_failed); 1137 return Error::success(); 1138 } 1139 1140 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) { 1141 GlobalSection = Sections.size(); 1142 uint32_t Count = readVaruint32(Ctx); 1143 Globals.reserve(Count); 1144 while (Count--) { 1145 wasm::WasmGlobal Global; 1146 Global.Index = NumImportedGlobals + Globals.size(); 1147 Global.Type.Type = readUint8(Ctx); 1148 Global.Type.Mutable = readVaruint1(Ctx); 1149 if (Error Err = readInitExpr(Global.InitExpr, Ctx)) 1150 return Err; 1151 Globals.push_back(Global); 1152 } 1153 if (Ctx.Ptr != Ctx.End) 1154 return make_error<GenericBinaryError>("Global section ended prematurely", 1155 object_error::parse_failed); 1156 return Error::success(); 1157 } 1158 1159 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) { 1160 uint32_t Count = readVaruint32(Ctx); 1161 Exports.reserve(Count); 1162 for (uint32_t I = 0; I < Count; I++) { 1163 wasm::WasmExport Ex; 1164 Ex.Name = readString(Ctx); 1165 Ex.Kind = readUint8(Ctx); 1166 Ex.Index = readVaruint32(Ctx); 1167 switch (Ex.Kind) { 1168 case wasm::WASM_EXTERNAL_FUNCTION: 1169 1170 if (!isDefinedFunctionIndex(Ex.Index)) 1171 return make_error<GenericBinaryError>("Invalid function export", 1172 object_error::parse_failed); 1173 getDefinedFunction(Ex.Index).ExportName = Ex.Name; 1174 break; 1175 case wasm::WASM_EXTERNAL_GLOBAL: 1176 if (!isValidGlobalIndex(Ex.Index)) 1177 return make_error<GenericBinaryError>("Invalid global export", 1178 object_error::parse_failed); 1179 break; 1180 case wasm::WASM_EXTERNAL_EVENT: 1181 if (!isValidEventIndex(Ex.Index)) 1182 return make_error<GenericBinaryError>("Invalid event export", 1183 object_error::parse_failed); 1184 break; 1185 case wasm::WASM_EXTERNAL_MEMORY: 1186 case wasm::WASM_EXTERNAL_TABLE: 1187 break; 1188 default: 1189 return make_error<GenericBinaryError>("Unexpected export kind", 1190 object_error::parse_failed); 1191 } 1192 Exports.push_back(Ex); 1193 } 1194 if (Ctx.Ptr != Ctx.End) 1195 return make_error<GenericBinaryError>("Export section ended prematurely", 1196 object_error::parse_failed); 1197 return Error::success(); 1198 } 1199 1200 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const { 1201 return Index < NumImportedFunctions + FunctionTypes.size(); 1202 } 1203 1204 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const { 1205 return Index >= NumImportedFunctions && isValidFunctionIndex(Index); 1206 } 1207 1208 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const { 1209 return Index < NumImportedGlobals + Globals.size(); 1210 } 1211 1212 bool WasmObjectFile::isValidTableIndex(uint32_t Index) const { 1213 return Index < NumImportedTables + Tables.size(); 1214 } 1215 1216 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const { 1217 return Index >= NumImportedGlobals && isValidGlobalIndex(Index); 1218 } 1219 1220 bool WasmObjectFile::isDefinedTableIndex(uint32_t Index) const { 1221 return Index >= NumImportedTables && isValidTableIndex(Index); 1222 } 1223 1224 bool WasmObjectFile::isValidEventIndex(uint32_t Index) const { 1225 return Index < NumImportedEvents + Events.size(); 1226 } 1227 1228 bool WasmObjectFile::isDefinedEventIndex(uint32_t Index) const { 1229 return Index >= NumImportedEvents && isValidEventIndex(Index); 1230 } 1231 1232 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const { 1233 return Index < Symbols.size() && Symbols[Index].isTypeFunction(); 1234 } 1235 1236 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const { 1237 return Index < Symbols.size() && Symbols[Index].isTypeTable(); 1238 } 1239 1240 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const { 1241 return Index < Symbols.size() && Symbols[Index].isTypeGlobal(); 1242 } 1243 1244 bool WasmObjectFile::isValidEventSymbol(uint32_t Index) const { 1245 return Index < Symbols.size() && Symbols[Index].isTypeEvent(); 1246 } 1247 1248 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const { 1249 return Index < Symbols.size() && Symbols[Index].isTypeData(); 1250 } 1251 1252 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const { 1253 return Index < Symbols.size() && Symbols[Index].isTypeSection(); 1254 } 1255 1256 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) { 1257 assert(isDefinedFunctionIndex(Index)); 1258 return Functions[Index - NumImportedFunctions]; 1259 } 1260 1261 const wasm::WasmFunction & 1262 WasmObjectFile::getDefinedFunction(uint32_t Index) const { 1263 assert(isDefinedFunctionIndex(Index)); 1264 return Functions[Index - NumImportedFunctions]; 1265 } 1266 1267 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) { 1268 assert(isDefinedGlobalIndex(Index)); 1269 return Globals[Index - NumImportedGlobals]; 1270 } 1271 1272 wasm::WasmEvent &WasmObjectFile::getDefinedEvent(uint32_t Index) { 1273 assert(isDefinedEventIndex(Index)); 1274 return Events[Index - NumImportedEvents]; 1275 } 1276 1277 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) { 1278 StartFunction = readVaruint32(Ctx); 1279 if (!isValidFunctionIndex(StartFunction)) 1280 return make_error<GenericBinaryError>("Invalid start function", 1281 object_error::parse_failed); 1282 return Error::success(); 1283 } 1284 1285 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) { 1286 SeenCodeSection = true; 1287 CodeSection = Sections.size(); 1288 uint32_t FunctionCount = readVaruint32(Ctx); 1289 if (FunctionCount != FunctionTypes.size()) { 1290 return make_error<GenericBinaryError>("Invalid function count", 1291 object_error::parse_failed); 1292 } 1293 1294 for (uint32_t i = 0; i < FunctionCount; i++) { 1295 wasm::WasmFunction& Function = Functions[i]; 1296 const uint8_t *FunctionStart = Ctx.Ptr; 1297 uint32_t Size = readVaruint32(Ctx); 1298 const uint8_t *FunctionEnd = Ctx.Ptr + Size; 1299 1300 Function.CodeOffset = Ctx.Ptr - FunctionStart; 1301 Function.Index = NumImportedFunctions + i; 1302 Function.CodeSectionOffset = FunctionStart - Ctx.Start; 1303 Function.Size = FunctionEnd - FunctionStart; 1304 1305 uint32_t NumLocalDecls = readVaruint32(Ctx); 1306 Function.Locals.reserve(NumLocalDecls); 1307 while (NumLocalDecls--) { 1308 wasm::WasmLocalDecl Decl; 1309 Decl.Count = readVaruint32(Ctx); 1310 Decl.Type = readUint8(Ctx); 1311 Function.Locals.push_back(Decl); 1312 } 1313 1314 uint32_t BodySize = FunctionEnd - Ctx.Ptr; 1315 Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize); 1316 // This will be set later when reading in the linking metadata section. 1317 Function.Comdat = UINT32_MAX; 1318 Ctx.Ptr += BodySize; 1319 assert(Ctx.Ptr == FunctionEnd); 1320 } 1321 if (Ctx.Ptr != Ctx.End) 1322 return make_error<GenericBinaryError>("Code section ended prematurely", 1323 object_error::parse_failed); 1324 return Error::success(); 1325 } 1326 1327 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) { 1328 uint32_t Count = readVaruint32(Ctx); 1329 ElemSegments.reserve(Count); 1330 while (Count--) { 1331 wasm::WasmElemSegment Segment; 1332 Segment.TableIndex = readVaruint32(Ctx); 1333 if (Segment.TableIndex != 0) { 1334 return make_error<GenericBinaryError>("Invalid TableIndex", 1335 object_error::parse_failed); 1336 } 1337 if (Error Err = readInitExpr(Segment.Offset, Ctx)) 1338 return Err; 1339 uint32_t NumElems = readVaruint32(Ctx); 1340 while (NumElems--) { 1341 Segment.Functions.push_back(readVaruint32(Ctx)); 1342 } 1343 ElemSegments.push_back(Segment); 1344 } 1345 if (Ctx.Ptr != Ctx.End) 1346 return make_error<GenericBinaryError>("Elem section ended prematurely", 1347 object_error::parse_failed); 1348 return Error::success(); 1349 } 1350 1351 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) { 1352 DataSection = Sections.size(); 1353 uint32_t Count = readVaruint32(Ctx); 1354 if (DataCount && Count != DataCount.getValue()) 1355 return make_error<GenericBinaryError>( 1356 "Number of data segments does not match DataCount section"); 1357 DataSegments.reserve(Count); 1358 while (Count--) { 1359 WasmSegment Segment; 1360 Segment.Data.InitFlags = readVaruint32(Ctx); 1361 Segment.Data.MemoryIndex = (Segment.Data.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX) 1362 ? readVaruint32(Ctx) : 0; 1363 if ((Segment.Data.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) { 1364 if (Error Err = readInitExpr(Segment.Data.Offset, Ctx)) 1365 return Err; 1366 } else { 1367 Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST; 1368 Segment.Data.Offset.Value.Int32 = 0; 1369 } 1370 uint32_t Size = readVaruint32(Ctx); 1371 if (Size > (size_t)(Ctx.End - Ctx.Ptr)) 1372 return make_error<GenericBinaryError>("Invalid segment size", 1373 object_error::parse_failed); 1374 Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size); 1375 // The rest of these Data fields are set later, when reading in the linking 1376 // metadata section. 1377 Segment.Data.Alignment = 0; 1378 Segment.Data.LinkerFlags = 0; 1379 Segment.Data.Comdat = UINT32_MAX; 1380 Segment.SectionOffset = Ctx.Ptr - Ctx.Start; 1381 Ctx.Ptr += Size; 1382 DataSegments.push_back(Segment); 1383 } 1384 if (Ctx.Ptr != Ctx.End) 1385 return make_error<GenericBinaryError>("Data section ended prematurely", 1386 object_error::parse_failed); 1387 return Error::success(); 1388 } 1389 1390 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) { 1391 DataCount = readVaruint32(Ctx); 1392 return Error::success(); 1393 } 1394 1395 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const { 1396 return Header; 1397 } 1398 1399 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; } 1400 1401 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const { 1402 uint32_t Result = SymbolRef::SF_None; 1403 const WasmSymbol &Sym = getWasmSymbol(Symb); 1404 1405 LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n"); 1406 if (Sym.isBindingWeak()) 1407 Result |= SymbolRef::SF_Weak; 1408 if (!Sym.isBindingLocal()) 1409 Result |= SymbolRef::SF_Global; 1410 if (Sym.isHidden()) 1411 Result |= SymbolRef::SF_Hidden; 1412 if (!Sym.isDefined()) 1413 Result |= SymbolRef::SF_Undefined; 1414 if (Sym.isTypeFunction()) 1415 Result |= SymbolRef::SF_Executable; 1416 return Result; 1417 } 1418 1419 basic_symbol_iterator WasmObjectFile::symbol_begin() const { 1420 DataRefImpl Ref; 1421 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1422 Ref.d.b = 0; // Symbol index 1423 return BasicSymbolRef(Ref, this); 1424 } 1425 1426 basic_symbol_iterator WasmObjectFile::symbol_end() const { 1427 DataRefImpl Ref; 1428 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1429 Ref.d.b = Symbols.size(); // Symbol index 1430 return BasicSymbolRef(Ref, this); 1431 } 1432 1433 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const { 1434 return Symbols[Symb.d.b]; 1435 } 1436 1437 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const { 1438 return getWasmSymbol(Symb.getRawDataRefImpl()); 1439 } 1440 1441 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const { 1442 return getWasmSymbol(Symb).Info.Name; 1443 } 1444 1445 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const { 1446 auto &Sym = getWasmSymbol(Symb); 1447 if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION && 1448 isDefinedFunctionIndex(Sym.Info.ElementIndex)) 1449 return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset; 1450 else 1451 return getSymbolValue(Symb); 1452 } 1453 1454 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const { 1455 switch (Sym.Info.Kind) { 1456 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1457 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1458 case wasm::WASM_SYMBOL_TYPE_EVENT: 1459 case wasm::WASM_SYMBOL_TYPE_TABLE: 1460 return Sym.Info.ElementIndex; 1461 case wasm::WASM_SYMBOL_TYPE_DATA: { 1462 // The value of a data symbol is the segment offset, plus the symbol 1463 // offset within the segment. 1464 uint32_t SegmentIndex = Sym.Info.DataRef.Segment; 1465 const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data; 1466 if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) { 1467 return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset; 1468 } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) { 1469 return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset; 1470 } else { 1471 llvm_unreachable("unknown init expr opcode"); 1472 } 1473 } 1474 case wasm::WASM_SYMBOL_TYPE_SECTION: 1475 return 0; 1476 } 1477 llvm_unreachable("invalid symbol type"); 1478 } 1479 1480 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const { 1481 return getWasmSymbolValue(getWasmSymbol(Symb)); 1482 } 1483 1484 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const { 1485 llvm_unreachable("not yet implemented"); 1486 return 0; 1487 } 1488 1489 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const { 1490 llvm_unreachable("not yet implemented"); 1491 return 0; 1492 } 1493 1494 Expected<SymbolRef::Type> 1495 WasmObjectFile::getSymbolType(DataRefImpl Symb) const { 1496 const WasmSymbol &Sym = getWasmSymbol(Symb); 1497 1498 switch (Sym.Info.Kind) { 1499 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1500 return SymbolRef::ST_Function; 1501 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1502 return SymbolRef::ST_Other; 1503 case wasm::WASM_SYMBOL_TYPE_DATA: 1504 return SymbolRef::ST_Data; 1505 case wasm::WASM_SYMBOL_TYPE_SECTION: 1506 return SymbolRef::ST_Debug; 1507 case wasm::WASM_SYMBOL_TYPE_EVENT: 1508 return SymbolRef::ST_Other; 1509 case wasm::WASM_SYMBOL_TYPE_TABLE: 1510 return SymbolRef::ST_Other; 1511 } 1512 1513 llvm_unreachable("Unknown WasmSymbol::SymbolType"); 1514 return SymbolRef::ST_Other; 1515 } 1516 1517 Expected<section_iterator> 1518 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const { 1519 const WasmSymbol &Sym = getWasmSymbol(Symb); 1520 if (Sym.isUndefined()) 1521 return section_end(); 1522 1523 DataRefImpl Ref; 1524 Ref.d.a = getSymbolSectionIdImpl(Sym); 1525 return section_iterator(SectionRef(Ref, this)); 1526 } 1527 1528 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const { 1529 const WasmSymbol &Sym = getWasmSymbol(Symb); 1530 return getSymbolSectionIdImpl(Sym); 1531 } 1532 1533 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const { 1534 switch (Sym.Info.Kind) { 1535 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1536 return CodeSection; 1537 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1538 return GlobalSection; 1539 case wasm::WASM_SYMBOL_TYPE_DATA: 1540 return DataSection; 1541 case wasm::WASM_SYMBOL_TYPE_SECTION: 1542 return Sym.Info.ElementIndex; 1543 case wasm::WASM_SYMBOL_TYPE_EVENT: 1544 return EventSection; 1545 case wasm::WASM_SYMBOL_TYPE_TABLE: 1546 return TableSection; 1547 default: 1548 llvm_unreachable("Unknown WasmSymbol::SymbolType"); 1549 } 1550 } 1551 1552 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; } 1553 1554 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const { 1555 const WasmSection &S = Sections[Sec.d.a]; 1556 #define ECase(X) \ 1557 case wasm::WASM_SEC_##X: \ 1558 return #X; 1559 switch (S.Type) { 1560 ECase(TYPE); 1561 ECase(IMPORT); 1562 ECase(FUNCTION); 1563 ECase(TABLE); 1564 ECase(MEMORY); 1565 ECase(GLOBAL); 1566 ECase(EVENT); 1567 ECase(EXPORT); 1568 ECase(START); 1569 ECase(ELEM); 1570 ECase(CODE); 1571 ECase(DATA); 1572 ECase(DATACOUNT); 1573 case wasm::WASM_SEC_CUSTOM: 1574 return S.Name; 1575 default: 1576 return createStringError(object_error::invalid_section_index, ""); 1577 } 1578 #undef ECase 1579 } 1580 1581 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; } 1582 1583 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const { 1584 return Sec.d.a; 1585 } 1586 1587 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const { 1588 const WasmSection &S = Sections[Sec.d.a]; 1589 return S.Content.size(); 1590 } 1591 1592 Expected<ArrayRef<uint8_t>> 1593 WasmObjectFile::getSectionContents(DataRefImpl Sec) const { 1594 const WasmSection &S = Sections[Sec.d.a]; 1595 // This will never fail since wasm sections can never be empty (user-sections 1596 // must have a name and non-user sections each have a defined structure). 1597 return S.Content; 1598 } 1599 1600 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const { 1601 return 1; 1602 } 1603 1604 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const { 1605 return false; 1606 } 1607 1608 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const { 1609 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE; 1610 } 1611 1612 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const { 1613 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA; 1614 } 1615 1616 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; } 1617 1618 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; } 1619 1620 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const { 1621 DataRefImpl RelocRef; 1622 RelocRef.d.a = Ref.d.a; 1623 RelocRef.d.b = 0; 1624 return relocation_iterator(RelocationRef(RelocRef, this)); 1625 } 1626 1627 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const { 1628 const WasmSection &Sec = getWasmSection(Ref); 1629 DataRefImpl RelocRef; 1630 RelocRef.d.a = Ref.d.a; 1631 RelocRef.d.b = Sec.Relocations.size(); 1632 return relocation_iterator(RelocationRef(RelocRef, this)); 1633 } 1634 1635 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; } 1636 1637 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const { 1638 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1639 return Rel.Offset; 1640 } 1641 1642 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const { 1643 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1644 if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB) 1645 return symbol_end(); 1646 DataRefImpl Sym; 1647 Sym.d.a = 1; 1648 Sym.d.b = Rel.Index; 1649 return symbol_iterator(SymbolRef(Sym, this)); 1650 } 1651 1652 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const { 1653 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1654 return Rel.Type; 1655 } 1656 1657 void WasmObjectFile::getRelocationTypeName( 1658 DataRefImpl Ref, SmallVectorImpl<char> &Result) const { 1659 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1660 StringRef Res = "Unknown"; 1661 1662 #define WASM_RELOC(name, value) \ 1663 case wasm::name: \ 1664 Res = #name; \ 1665 break; 1666 1667 switch (Rel.Type) { 1668 #include "llvm/BinaryFormat/WasmRelocs.def" 1669 } 1670 1671 #undef WASM_RELOC 1672 1673 Result.append(Res.begin(), Res.end()); 1674 } 1675 1676 section_iterator WasmObjectFile::section_begin() const { 1677 DataRefImpl Ref; 1678 Ref.d.a = 0; 1679 return section_iterator(SectionRef(Ref, this)); 1680 } 1681 1682 section_iterator WasmObjectFile::section_end() const { 1683 DataRefImpl Ref; 1684 Ref.d.a = Sections.size(); 1685 return section_iterator(SectionRef(Ref, this)); 1686 } 1687 1688 uint8_t WasmObjectFile::getBytesInAddress() const { 1689 return HasMemory64 ? 8 : 4; 1690 } 1691 1692 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; } 1693 1694 Triple::ArchType WasmObjectFile::getArch() const { 1695 return HasMemory64 ? Triple::wasm64 : Triple::wasm32; 1696 } 1697 1698 SubtargetFeatures WasmObjectFile::getFeatures() const { 1699 return SubtargetFeatures(); 1700 } 1701 1702 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; } 1703 1704 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; } 1705 1706 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const { 1707 assert(Ref.d.a < Sections.size()); 1708 return Sections[Ref.d.a]; 1709 } 1710 1711 const WasmSection & 1712 WasmObjectFile::getWasmSection(const SectionRef &Section) const { 1713 return getWasmSection(Section.getRawDataRefImpl()); 1714 } 1715 1716 const wasm::WasmRelocation & 1717 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const { 1718 return getWasmRelocation(Ref.getRawDataRefImpl()); 1719 } 1720 1721 const wasm::WasmRelocation & 1722 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const { 1723 assert(Ref.d.a < Sections.size()); 1724 const WasmSection &Sec = Sections[Ref.d.a]; 1725 assert(Ref.d.b < Sec.Relocations.size()); 1726 return Sec.Relocations[Ref.d.b]; 1727 } 1728 1729 int WasmSectionOrderChecker::getSectionOrder(unsigned ID, 1730 StringRef CustomSectionName) { 1731 switch (ID) { 1732 case wasm::WASM_SEC_CUSTOM: 1733 return StringSwitch<unsigned>(CustomSectionName) 1734 .Case("dylink", WASM_SEC_ORDER_DYLINK) 1735 .Case("linking", WASM_SEC_ORDER_LINKING) 1736 .StartsWith("reloc.", WASM_SEC_ORDER_RELOC) 1737 .Case("name", WASM_SEC_ORDER_NAME) 1738 .Case("producers", WASM_SEC_ORDER_PRODUCERS) 1739 .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES) 1740 .Default(WASM_SEC_ORDER_NONE); 1741 case wasm::WASM_SEC_TYPE: 1742 return WASM_SEC_ORDER_TYPE; 1743 case wasm::WASM_SEC_IMPORT: 1744 return WASM_SEC_ORDER_IMPORT; 1745 case wasm::WASM_SEC_FUNCTION: 1746 return WASM_SEC_ORDER_FUNCTION; 1747 case wasm::WASM_SEC_TABLE: 1748 return WASM_SEC_ORDER_TABLE; 1749 case wasm::WASM_SEC_MEMORY: 1750 return WASM_SEC_ORDER_MEMORY; 1751 case wasm::WASM_SEC_GLOBAL: 1752 return WASM_SEC_ORDER_GLOBAL; 1753 case wasm::WASM_SEC_EXPORT: 1754 return WASM_SEC_ORDER_EXPORT; 1755 case wasm::WASM_SEC_START: 1756 return WASM_SEC_ORDER_START; 1757 case wasm::WASM_SEC_ELEM: 1758 return WASM_SEC_ORDER_ELEM; 1759 case wasm::WASM_SEC_CODE: 1760 return WASM_SEC_ORDER_CODE; 1761 case wasm::WASM_SEC_DATA: 1762 return WASM_SEC_ORDER_DATA; 1763 case wasm::WASM_SEC_DATACOUNT: 1764 return WASM_SEC_ORDER_DATACOUNT; 1765 case wasm::WASM_SEC_EVENT: 1766 return WASM_SEC_ORDER_EVENT; 1767 default: 1768 return WASM_SEC_ORDER_NONE; 1769 } 1770 } 1771 1772 // Represents the edges in a directed graph where any node B reachable from node 1773 // A is not allowed to appear before A in the section ordering, but may appear 1774 // afterward. 1775 int WasmSectionOrderChecker::DisallowedPredecessors 1776 [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = { 1777 // WASM_SEC_ORDER_NONE 1778 {}, 1779 // WASM_SEC_ORDER_TYPE 1780 {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT}, 1781 // WASM_SEC_ORDER_IMPORT 1782 {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION}, 1783 // WASM_SEC_ORDER_FUNCTION 1784 {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE}, 1785 // WASM_SEC_ORDER_TABLE 1786 {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY}, 1787 // WASM_SEC_ORDER_MEMORY 1788 {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_EVENT}, 1789 // WASM_SEC_ORDER_EVENT 1790 {WASM_SEC_ORDER_EVENT, WASM_SEC_ORDER_GLOBAL}, 1791 // WASM_SEC_ORDER_GLOBAL 1792 {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT}, 1793 // WASM_SEC_ORDER_EXPORT 1794 {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START}, 1795 // WASM_SEC_ORDER_START 1796 {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM}, 1797 // WASM_SEC_ORDER_ELEM 1798 {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT}, 1799 // WASM_SEC_ORDER_DATACOUNT 1800 {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE}, 1801 // WASM_SEC_ORDER_CODE 1802 {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA}, 1803 // WASM_SEC_ORDER_DATA 1804 {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING}, 1805 1806 // Custom Sections 1807 // WASM_SEC_ORDER_DYLINK 1808 {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE}, 1809 // WASM_SEC_ORDER_LINKING 1810 {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME}, 1811 // WASM_SEC_ORDER_RELOC (can be repeated) 1812 {}, 1813 // WASM_SEC_ORDER_NAME 1814 {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS}, 1815 // WASM_SEC_ORDER_PRODUCERS 1816 {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES}, 1817 // WASM_SEC_ORDER_TARGET_FEATURES 1818 {WASM_SEC_ORDER_TARGET_FEATURES}}; 1819 1820 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID, 1821 StringRef CustomSectionName) { 1822 int Order = getSectionOrder(ID, CustomSectionName); 1823 if (Order == WASM_SEC_ORDER_NONE) 1824 return true; 1825 1826 // Disallowed predecessors we need to check for 1827 SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList; 1828 1829 // Keep track of completed checks to avoid repeating work 1830 bool Checked[WASM_NUM_SEC_ORDERS] = {}; 1831 1832 int Curr = Order; 1833 while (true) { 1834 // Add new disallowed predecessors to work list 1835 for (size_t I = 0;; ++I) { 1836 int Next = DisallowedPredecessors[Curr][I]; 1837 if (Next == WASM_SEC_ORDER_NONE) 1838 break; 1839 if (Checked[Next]) 1840 continue; 1841 WorkList.push_back(Next); 1842 Checked[Next] = true; 1843 } 1844 1845 if (WorkList.empty()) 1846 break; 1847 1848 // Consider next disallowed predecessor 1849 Curr = WorkList.pop_back_val(); 1850 if (Seen[Curr]) 1851 return false; 1852 } 1853 1854 // Have not seen any disallowed predecessors 1855 Seen[Order] = true; 1856 return true; 1857 } 1858