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)) << ", Flags=0x" 43 << Twine::utohexstr(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.Minimum = 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 = make_error<StringError>("invalid magic number", 266 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>("invalid version number: " + 284 Twine(Header.Version), 285 object_error::parse_failed); 286 return; 287 } 288 289 WasmSectionOrderChecker Checker; 290 while (Ctx.Ptr < Ctx.End) { 291 WasmSection Sec; 292 if ((Err = readSection(Sec, Ctx, Checker))) 293 return; 294 if ((Err = parseSection(Sec))) 295 return; 296 297 Sections.push_back(Sec); 298 } 299 } 300 301 Error WasmObjectFile::parseSection(WasmSection &Sec) { 302 ReadContext Ctx; 303 Ctx.Start = Sec.Content.data(); 304 Ctx.End = Ctx.Start + Sec.Content.size(); 305 Ctx.Ptr = Ctx.Start; 306 switch (Sec.Type) { 307 case wasm::WASM_SEC_CUSTOM: 308 return parseCustomSection(Sec, Ctx); 309 case wasm::WASM_SEC_TYPE: 310 return parseTypeSection(Ctx); 311 case wasm::WASM_SEC_IMPORT: 312 return parseImportSection(Ctx); 313 case wasm::WASM_SEC_FUNCTION: 314 return parseFunctionSection(Ctx); 315 case wasm::WASM_SEC_TABLE: 316 return parseTableSection(Ctx); 317 case wasm::WASM_SEC_MEMORY: 318 return parseMemorySection(Ctx); 319 case wasm::WASM_SEC_TAG: 320 return parseTagSection(Ctx); 321 case wasm::WASM_SEC_GLOBAL: 322 return parseGlobalSection(Ctx); 323 case wasm::WASM_SEC_EXPORT: 324 return parseExportSection(Ctx); 325 case wasm::WASM_SEC_START: 326 return parseStartSection(Ctx); 327 case wasm::WASM_SEC_ELEM: 328 return parseElemSection(Ctx); 329 case wasm::WASM_SEC_CODE: 330 return parseCodeSection(Ctx); 331 case wasm::WASM_SEC_DATA: 332 return parseDataSection(Ctx); 333 case wasm::WASM_SEC_DATACOUNT: 334 return parseDataCountSection(Ctx); 335 default: 336 return make_error<GenericBinaryError>( 337 "invalid section type: " + Twine(Sec.Type), object_error::parse_failed); 338 } 339 } 340 341 Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) { 342 // Legacy "dylink" section support. 343 // See parseDylink0Section for the current "dylink.0" section parsing. 344 HasDylinkSection = true; 345 DylinkInfo.MemorySize = readVaruint32(Ctx); 346 DylinkInfo.MemoryAlignment = readVaruint32(Ctx); 347 DylinkInfo.TableSize = readVaruint32(Ctx); 348 DylinkInfo.TableAlignment = readVaruint32(Ctx); 349 uint32_t Count = readVaruint32(Ctx); 350 while (Count--) { 351 DylinkInfo.Needed.push_back(readString(Ctx)); 352 } 353 354 if (Ctx.Ptr != Ctx.End) 355 return make_error<GenericBinaryError>("dylink section ended prematurely", 356 object_error::parse_failed); 357 return Error::success(); 358 } 359 360 Error WasmObjectFile::parseDylink0Section(ReadContext &Ctx) { 361 // See 362 // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md 363 HasDylinkSection = true; 364 365 const uint8_t *OrigEnd = Ctx.End; 366 while (Ctx.Ptr < OrigEnd) { 367 Ctx.End = OrigEnd; 368 uint8_t Type = readUint8(Ctx); 369 uint32_t Size = readVaruint32(Ctx); 370 LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size 371 << "\n"); 372 Ctx.End = Ctx.Ptr + Size; 373 uint32_t Count; 374 switch (Type) { 375 case wasm::WASM_DYLINK_MEM_INFO: 376 DylinkInfo.MemorySize = readVaruint32(Ctx); 377 DylinkInfo.MemoryAlignment = readVaruint32(Ctx); 378 DylinkInfo.TableSize = readVaruint32(Ctx); 379 DylinkInfo.TableAlignment = readVaruint32(Ctx); 380 break; 381 case wasm::WASM_DYLINK_NEEDED: 382 Count = readVaruint32(Ctx); 383 while (Count--) { 384 DylinkInfo.Needed.push_back(readString(Ctx)); 385 } 386 break; 387 case wasm::WASM_DYLINK_EXPORT_INFO: { 388 uint32_t Count = readVaruint32(Ctx); 389 while (Count--) { 390 DylinkInfo.ExportInfo.push_back({readString(Ctx), readVaruint32(Ctx)}); 391 } 392 break; 393 } 394 default: 395 LLVM_DEBUG(dbgs() << "unknown dylink.0 sub-section: " << Type << "\n"); 396 Ctx.Ptr += Size; 397 break; 398 } 399 if (Ctx.Ptr != Ctx.End) { 400 return make_error<GenericBinaryError>( 401 "dylink.0 sub-section ended prematurely", object_error::parse_failed); 402 } 403 } 404 405 if (Ctx.Ptr != Ctx.End) 406 return make_error<GenericBinaryError>("dylink.0 section ended prematurely", 407 object_error::parse_failed); 408 return Error::success(); 409 } 410 411 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) { 412 llvm::DenseSet<uint64_t> SeenFunctions; 413 llvm::DenseSet<uint64_t> SeenGlobals; 414 llvm::DenseSet<uint64_t> SeenSegments; 415 if (FunctionTypes.size() && !SeenCodeSection) { 416 return make_error<GenericBinaryError>("names must come after code section", 417 object_error::parse_failed); 418 } 419 420 while (Ctx.Ptr < Ctx.End) { 421 uint8_t Type = readUint8(Ctx); 422 uint32_t Size = readVaruint32(Ctx); 423 const uint8_t *SubSectionEnd = Ctx.Ptr + Size; 424 switch (Type) { 425 case wasm::WASM_NAMES_FUNCTION: 426 case wasm::WASM_NAMES_GLOBAL: 427 case wasm::WASM_NAMES_DATA_SEGMENT: { 428 uint32_t Count = readVaruint32(Ctx); 429 while (Count--) { 430 uint32_t Index = readVaruint32(Ctx); 431 StringRef Name = readString(Ctx); 432 wasm::NameType nameType = wasm::NameType::FUNCTION; 433 if (Type == wasm::WASM_NAMES_FUNCTION) { 434 if (!SeenFunctions.insert(Index).second) 435 return make_error<GenericBinaryError>( 436 "function named more than once", object_error::parse_failed); 437 if (!isValidFunctionIndex(Index) || Name.empty()) 438 return make_error<GenericBinaryError>("invalid name entry", 439 object_error::parse_failed); 440 441 if (isDefinedFunctionIndex(Index)) 442 getDefinedFunction(Index).DebugName = Name; 443 } else if (Type == wasm::WASM_NAMES_GLOBAL) { 444 nameType = wasm::NameType::GLOBAL; 445 if (!SeenGlobals.insert(Index).second) 446 return make_error<GenericBinaryError>("global named more than once", 447 object_error::parse_failed); 448 if (!isValidGlobalIndex(Index) || Name.empty()) 449 return make_error<GenericBinaryError>("invalid name entry", 450 object_error::parse_failed); 451 } else { 452 nameType = wasm::NameType::DATA_SEGMENT; 453 if (!SeenSegments.insert(Index).second) 454 return make_error<GenericBinaryError>( 455 "segment named more than once", object_error::parse_failed); 456 if (Index > DataSegments.size()) 457 return make_error<GenericBinaryError>("invalid named data segment", 458 object_error::parse_failed); 459 } 460 DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name}); 461 } 462 break; 463 } 464 // Ignore local names for now 465 case wasm::WASM_NAMES_LOCAL: 466 default: 467 Ctx.Ptr += Size; 468 break; 469 } 470 if (Ctx.Ptr != SubSectionEnd) 471 return make_error<GenericBinaryError>( 472 "name sub-section ended prematurely", object_error::parse_failed); 473 } 474 475 if (Ctx.Ptr != Ctx.End) 476 return make_error<GenericBinaryError>("name section ended prematurely", 477 object_error::parse_failed); 478 return Error::success(); 479 } 480 481 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) { 482 HasLinkingSection = true; 483 if (FunctionTypes.size() && !SeenCodeSection) { 484 return make_error<GenericBinaryError>( 485 "linking data must come after code section", 486 object_error::parse_failed); 487 } 488 489 LinkingData.Version = readVaruint32(Ctx); 490 if (LinkingData.Version != wasm::WasmMetadataVersion) { 491 return make_error<GenericBinaryError>( 492 "unexpected metadata version: " + Twine(LinkingData.Version) + 493 " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")", 494 object_error::parse_failed); 495 } 496 497 const uint8_t *OrigEnd = Ctx.End; 498 while (Ctx.Ptr < OrigEnd) { 499 Ctx.End = OrigEnd; 500 uint8_t Type = readUint8(Ctx); 501 uint32_t Size = readVaruint32(Ctx); 502 LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size 503 << "\n"); 504 Ctx.End = Ctx.Ptr + Size; 505 switch (Type) { 506 case wasm::WASM_SYMBOL_TABLE: 507 if (Error Err = parseLinkingSectionSymtab(Ctx)) 508 return Err; 509 break; 510 case wasm::WASM_SEGMENT_INFO: { 511 uint32_t Count = readVaruint32(Ctx); 512 if (Count > DataSegments.size()) 513 return make_error<GenericBinaryError>("too many segment names", 514 object_error::parse_failed); 515 for (uint32_t I = 0; I < Count; I++) { 516 DataSegments[I].Data.Name = readString(Ctx); 517 DataSegments[I].Data.Alignment = readVaruint32(Ctx); 518 DataSegments[I].Data.LinkingFlags = readVaruint32(Ctx); 519 } 520 break; 521 } 522 case wasm::WASM_INIT_FUNCS: { 523 uint32_t Count = readVaruint32(Ctx); 524 LinkingData.InitFunctions.reserve(Count); 525 for (uint32_t I = 0; I < Count; I++) { 526 wasm::WasmInitFunc Init; 527 Init.Priority = readVaruint32(Ctx); 528 Init.Symbol = readVaruint32(Ctx); 529 if (!isValidFunctionSymbol(Init.Symbol)) 530 return make_error<GenericBinaryError>("invalid function symbol: " + 531 Twine(Init.Symbol), 532 object_error::parse_failed); 533 LinkingData.InitFunctions.emplace_back(Init); 534 } 535 break; 536 } 537 case wasm::WASM_COMDAT_INFO: 538 if (Error Err = parseLinkingSectionComdat(Ctx)) 539 return Err; 540 break; 541 default: 542 Ctx.Ptr += Size; 543 break; 544 } 545 if (Ctx.Ptr != Ctx.End) 546 return make_error<GenericBinaryError>( 547 "linking sub-section ended prematurely", object_error::parse_failed); 548 } 549 if (Ctx.Ptr != OrigEnd) 550 return make_error<GenericBinaryError>("linking section ended prematurely", 551 object_error::parse_failed); 552 return Error::success(); 553 } 554 555 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) { 556 uint32_t Count = readVaruint32(Ctx); 557 LinkingData.SymbolTable.reserve(Count); 558 Symbols.reserve(Count); 559 StringSet<> SymbolNames; 560 561 std::vector<wasm::WasmImport *> ImportedGlobals; 562 std::vector<wasm::WasmImport *> ImportedFunctions; 563 std::vector<wasm::WasmImport *> ImportedTags; 564 std::vector<wasm::WasmImport *> ImportedTables; 565 ImportedGlobals.reserve(Imports.size()); 566 ImportedFunctions.reserve(Imports.size()); 567 ImportedTags.reserve(Imports.size()); 568 ImportedTables.reserve(Imports.size()); 569 for (auto &I : Imports) { 570 if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION) 571 ImportedFunctions.emplace_back(&I); 572 else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL) 573 ImportedGlobals.emplace_back(&I); 574 else if (I.Kind == wasm::WASM_EXTERNAL_TAG) 575 ImportedTags.emplace_back(&I); 576 else if (I.Kind == wasm::WASM_EXTERNAL_TABLE) 577 ImportedTables.emplace_back(&I); 578 } 579 580 while (Count--) { 581 wasm::WasmSymbolInfo Info; 582 const wasm::WasmSignature *Signature = nullptr; 583 const wasm::WasmGlobalType *GlobalType = nullptr; 584 const wasm::WasmTableType *TableType = nullptr; 585 const wasm::WasmTagType *TagType = nullptr; 586 587 Info.Kind = readUint8(Ctx); 588 Info.Flags = readVaruint32(Ctx); 589 bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0; 590 591 switch (Info.Kind) { 592 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 593 Info.ElementIndex = readVaruint32(Ctx); 594 if (!isValidFunctionIndex(Info.ElementIndex) || 595 IsDefined != isDefinedFunctionIndex(Info.ElementIndex)) 596 return make_error<GenericBinaryError>("invalid function symbol index", 597 object_error::parse_failed); 598 if (IsDefined) { 599 Info.Name = readString(Ctx); 600 unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions; 601 Signature = &Signatures[FunctionTypes[FuncIndex]]; 602 wasm::WasmFunction &Function = Functions[FuncIndex]; 603 if (Function.SymbolName.empty()) 604 Function.SymbolName = Info.Name; 605 } else { 606 wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex]; 607 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 608 Info.Name = readString(Ctx); 609 Info.ImportName = Import.Field; 610 } else { 611 Info.Name = Import.Field; 612 } 613 Signature = &Signatures[Import.SigIndex]; 614 if (!Import.Module.empty()) { 615 Info.ImportModule = Import.Module; 616 } 617 } 618 break; 619 620 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 621 Info.ElementIndex = readVaruint32(Ctx); 622 if (!isValidGlobalIndex(Info.ElementIndex) || 623 IsDefined != isDefinedGlobalIndex(Info.ElementIndex)) 624 return make_error<GenericBinaryError>("invalid global symbol index", 625 object_error::parse_failed); 626 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 627 wasm::WASM_SYMBOL_BINDING_WEAK) 628 return make_error<GenericBinaryError>("undefined weak global symbol", 629 object_error::parse_failed); 630 if (IsDefined) { 631 Info.Name = readString(Ctx); 632 unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals; 633 wasm::WasmGlobal &Global = Globals[GlobalIndex]; 634 GlobalType = &Global.Type; 635 if (Global.SymbolName.empty()) 636 Global.SymbolName = Info.Name; 637 } else { 638 wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex]; 639 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 640 Info.Name = readString(Ctx); 641 Info.ImportName = Import.Field; 642 } else { 643 Info.Name = Import.Field; 644 } 645 GlobalType = &Import.Global; 646 if (!Import.Module.empty()) { 647 Info.ImportModule = Import.Module; 648 } 649 } 650 break; 651 652 case wasm::WASM_SYMBOL_TYPE_TABLE: 653 Info.ElementIndex = readVaruint32(Ctx); 654 if (!isValidTableNumber(Info.ElementIndex) || 655 IsDefined != isDefinedTableNumber(Info.ElementIndex)) 656 return make_error<GenericBinaryError>("invalid table symbol index", 657 object_error::parse_failed); 658 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 659 wasm::WASM_SYMBOL_BINDING_WEAK) 660 return make_error<GenericBinaryError>("undefined weak table symbol", 661 object_error::parse_failed); 662 if (IsDefined) { 663 Info.Name = readString(Ctx); 664 unsigned TableNumber = Info.ElementIndex - NumImportedTables; 665 wasm::WasmTable &Table = Tables[TableNumber]; 666 TableType = &Table.Type; 667 if (Table.SymbolName.empty()) 668 Table.SymbolName = Info.Name; 669 } else { 670 wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex]; 671 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 672 Info.Name = readString(Ctx); 673 Info.ImportName = Import.Field; 674 } else { 675 Info.Name = Import.Field; 676 } 677 TableType = &Import.Table; 678 if (!Import.Module.empty()) { 679 Info.ImportModule = Import.Module; 680 } 681 } 682 break; 683 684 case wasm::WASM_SYMBOL_TYPE_DATA: 685 Info.Name = readString(Ctx); 686 if (IsDefined) { 687 auto Index = readVaruint32(Ctx); 688 if (Index >= DataSegments.size()) 689 return make_error<GenericBinaryError>("invalid data symbol index", 690 object_error::parse_failed); 691 auto Offset = readVaruint64(Ctx); 692 auto Size = readVaruint64(Ctx); 693 size_t SegmentSize = DataSegments[Index].Data.Content.size(); 694 if (Offset > SegmentSize) 695 return make_error<GenericBinaryError>( 696 "invalid data symbol offset: `" + Info.Name + "` (offset: " + 697 Twine(Offset) + " segment size: " + Twine(SegmentSize) + ")", 698 object_error::parse_failed); 699 Info.DataRef = wasm::WasmDataReference{Index, Offset, Size}; 700 } 701 break; 702 703 case wasm::WASM_SYMBOL_TYPE_SECTION: { 704 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) != 705 wasm::WASM_SYMBOL_BINDING_LOCAL) 706 return make_error<GenericBinaryError>( 707 "section symbols must have local binding", 708 object_error::parse_failed); 709 Info.ElementIndex = readVaruint32(Ctx); 710 // Use somewhat unique section name as symbol name. 711 StringRef SectionName = Sections[Info.ElementIndex].Name; 712 Info.Name = SectionName; 713 break; 714 } 715 716 case wasm::WASM_SYMBOL_TYPE_TAG: { 717 Info.ElementIndex = readVaruint32(Ctx); 718 if (!isValidTagIndex(Info.ElementIndex) || 719 IsDefined != isDefinedTagIndex(Info.ElementIndex)) 720 return make_error<GenericBinaryError>("invalid tag symbol index", 721 object_error::parse_failed); 722 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 723 wasm::WASM_SYMBOL_BINDING_WEAK) 724 return make_error<GenericBinaryError>("undefined weak global symbol", 725 object_error::parse_failed); 726 if (IsDefined) { 727 Info.Name = readString(Ctx); 728 unsigned TagIndex = Info.ElementIndex - NumImportedTags; 729 wasm::WasmTag &Tag = Tags[TagIndex]; 730 Signature = &Signatures[Tag.Type.SigIndex]; 731 TagType = &Tag.Type; 732 if (Tag.SymbolName.empty()) 733 Tag.SymbolName = Info.Name; 734 735 } else { 736 wasm::WasmImport &Import = *ImportedTags[Info.ElementIndex]; 737 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 738 Info.Name = readString(Ctx); 739 Info.ImportName = Import.Field; 740 } else { 741 Info.Name = Import.Field; 742 } 743 TagType = &Import.Tag; 744 Signature = &Signatures[TagType->SigIndex]; 745 if (!Import.Module.empty()) { 746 Info.ImportModule = Import.Module; 747 } 748 } 749 break; 750 } 751 752 default: 753 return make_error<GenericBinaryError>("invalid symbol type: " + 754 Twine(unsigned(Info.Kind)), 755 object_error::parse_failed); 756 } 757 758 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) != 759 wasm::WASM_SYMBOL_BINDING_LOCAL && 760 !SymbolNames.insert(Info.Name).second) 761 return make_error<GenericBinaryError>("duplicate symbol name " + 762 Twine(Info.Name), 763 object_error::parse_failed); 764 LinkingData.SymbolTable.emplace_back(Info); 765 Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType, TableType, 766 TagType, Signature); 767 LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n"); 768 } 769 770 return Error::success(); 771 } 772 773 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) { 774 uint32_t ComdatCount = readVaruint32(Ctx); 775 StringSet<> ComdatSet; 776 for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) { 777 StringRef Name = readString(Ctx); 778 if (Name.empty() || !ComdatSet.insert(Name).second) 779 return make_error<GenericBinaryError>("bad/duplicate COMDAT name " + 780 Twine(Name), 781 object_error::parse_failed); 782 LinkingData.Comdats.emplace_back(Name); 783 uint32_t Flags = readVaruint32(Ctx); 784 if (Flags != 0) 785 return make_error<GenericBinaryError>("unsupported COMDAT flags", 786 object_error::parse_failed); 787 788 uint32_t EntryCount = readVaruint32(Ctx); 789 while (EntryCount--) { 790 unsigned Kind = readVaruint32(Ctx); 791 unsigned Index = readVaruint32(Ctx); 792 switch (Kind) { 793 default: 794 return make_error<GenericBinaryError>("invalid COMDAT entry type", 795 object_error::parse_failed); 796 case wasm::WASM_COMDAT_DATA: 797 if (Index >= DataSegments.size()) 798 return make_error<GenericBinaryError>( 799 "COMDAT data index out of range", object_error::parse_failed); 800 if (DataSegments[Index].Data.Comdat != UINT32_MAX) 801 return make_error<GenericBinaryError>("data segment in two COMDATs", 802 object_error::parse_failed); 803 DataSegments[Index].Data.Comdat = ComdatIndex; 804 break; 805 case wasm::WASM_COMDAT_FUNCTION: 806 if (!isDefinedFunctionIndex(Index)) 807 return make_error<GenericBinaryError>( 808 "COMDAT function index out of range", object_error::parse_failed); 809 if (getDefinedFunction(Index).Comdat != UINT32_MAX) 810 return make_error<GenericBinaryError>("function in two COMDATs", 811 object_error::parse_failed); 812 getDefinedFunction(Index).Comdat = ComdatIndex; 813 break; 814 case wasm::WASM_COMDAT_SECTION: 815 if (Index >= Sections.size()) 816 return make_error<GenericBinaryError>( 817 "COMDAT section index out of range", object_error::parse_failed); 818 if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM) 819 return make_error<GenericBinaryError>( 820 "non-custom section in a COMDAT", object_error::parse_failed); 821 Sections[Index].Comdat = ComdatIndex; 822 break; 823 } 824 } 825 } 826 return Error::success(); 827 } 828 829 Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) { 830 llvm::SmallSet<StringRef, 3> FieldsSeen; 831 uint32_t Fields = readVaruint32(Ctx); 832 for (size_t I = 0; I < Fields; ++I) { 833 StringRef FieldName = readString(Ctx); 834 if (!FieldsSeen.insert(FieldName).second) 835 return make_error<GenericBinaryError>( 836 "producers section does not have unique fields", 837 object_error::parse_failed); 838 std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr; 839 if (FieldName == "language") { 840 ProducerVec = &ProducerInfo.Languages; 841 } else if (FieldName == "processed-by") { 842 ProducerVec = &ProducerInfo.Tools; 843 } else if (FieldName == "sdk") { 844 ProducerVec = &ProducerInfo.SDKs; 845 } else { 846 return make_error<GenericBinaryError>( 847 "producers section field is not named one of language, processed-by, " 848 "or sdk", 849 object_error::parse_failed); 850 } 851 uint32_t ValueCount = readVaruint32(Ctx); 852 llvm::SmallSet<StringRef, 8> ProducersSeen; 853 for (size_t J = 0; J < ValueCount; ++J) { 854 StringRef Name = readString(Ctx); 855 StringRef Version = readString(Ctx); 856 if (!ProducersSeen.insert(Name).second) { 857 return make_error<GenericBinaryError>( 858 "producers section contains repeated producer", 859 object_error::parse_failed); 860 } 861 ProducerVec->emplace_back(std::string(Name), std::string(Version)); 862 } 863 } 864 if (Ctx.Ptr != Ctx.End) 865 return make_error<GenericBinaryError>("producers section ended prematurely", 866 object_error::parse_failed); 867 return Error::success(); 868 } 869 870 Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) { 871 llvm::SmallSet<std::string, 8> FeaturesSeen; 872 uint32_t FeatureCount = readVaruint32(Ctx); 873 for (size_t I = 0; I < FeatureCount; ++I) { 874 wasm::WasmFeatureEntry Feature; 875 Feature.Prefix = readUint8(Ctx); 876 switch (Feature.Prefix) { 877 case wasm::WASM_FEATURE_PREFIX_USED: 878 case wasm::WASM_FEATURE_PREFIX_REQUIRED: 879 case wasm::WASM_FEATURE_PREFIX_DISALLOWED: 880 break; 881 default: 882 return make_error<GenericBinaryError>("unknown feature policy prefix", 883 object_error::parse_failed); 884 } 885 Feature.Name = std::string(readString(Ctx)); 886 if (!FeaturesSeen.insert(Feature.Name).second) 887 return make_error<GenericBinaryError>( 888 "target features section contains repeated feature \"" + 889 Feature.Name + "\"", 890 object_error::parse_failed); 891 TargetFeatures.push_back(Feature); 892 } 893 if (Ctx.Ptr != Ctx.End) 894 return make_error<GenericBinaryError>( 895 "target features section ended prematurely", 896 object_error::parse_failed); 897 return Error::success(); 898 } 899 900 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) { 901 uint32_t SectionIndex = readVaruint32(Ctx); 902 if (SectionIndex >= Sections.size()) 903 return make_error<GenericBinaryError>("invalid section index", 904 object_error::parse_failed); 905 WasmSection &Section = Sections[SectionIndex]; 906 uint32_t RelocCount = readVaruint32(Ctx); 907 uint32_t EndOffset = Section.Content.size(); 908 uint32_t PreviousOffset = 0; 909 while (RelocCount--) { 910 wasm::WasmRelocation Reloc = {}; 911 uint32_t type = readVaruint32(Ctx); 912 Reloc.Type = type; 913 Reloc.Offset = readVaruint32(Ctx); 914 if (Reloc.Offset < PreviousOffset) 915 return make_error<GenericBinaryError>("relocations not in offset order", 916 object_error::parse_failed); 917 PreviousOffset = Reloc.Offset; 918 Reloc.Index = readVaruint32(Ctx); 919 switch (type) { 920 case wasm::R_WASM_FUNCTION_INDEX_LEB: 921 case wasm::R_WASM_TABLE_INDEX_SLEB: 922 case wasm::R_WASM_TABLE_INDEX_SLEB64: 923 case wasm::R_WASM_TABLE_INDEX_I32: 924 case wasm::R_WASM_TABLE_INDEX_I64: 925 case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 926 case wasm::R_WASM_TABLE_INDEX_REL_SLEB64: 927 if (!isValidFunctionSymbol(Reloc.Index)) 928 return make_error<GenericBinaryError>( 929 "invalid relocation function index", object_error::parse_failed); 930 break; 931 case wasm::R_WASM_TABLE_NUMBER_LEB: 932 if (!isValidTableSymbol(Reloc.Index)) 933 return make_error<GenericBinaryError>("invalid relocation table index", 934 object_error::parse_failed); 935 break; 936 case wasm::R_WASM_TYPE_INDEX_LEB: 937 if (Reloc.Index >= Signatures.size()) 938 return make_error<GenericBinaryError>("invalid relocation type index", 939 object_error::parse_failed); 940 break; 941 case wasm::R_WASM_GLOBAL_INDEX_LEB: 942 // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data 943 // symbols to refer to their GOT entries. 944 if (!isValidGlobalSymbol(Reloc.Index) && 945 !isValidDataSymbol(Reloc.Index) && 946 !isValidFunctionSymbol(Reloc.Index)) 947 return make_error<GenericBinaryError>("invalid relocation global index", 948 object_error::parse_failed); 949 break; 950 case wasm::R_WASM_GLOBAL_INDEX_I32: 951 if (!isValidGlobalSymbol(Reloc.Index)) 952 return make_error<GenericBinaryError>("invalid relocation global index", 953 object_error::parse_failed); 954 break; 955 case wasm::R_WASM_TAG_INDEX_LEB: 956 if (!isValidTagSymbol(Reloc.Index)) 957 return make_error<GenericBinaryError>("invalid relocation tag index", 958 object_error::parse_failed); 959 break; 960 case wasm::R_WASM_MEMORY_ADDR_LEB: 961 case wasm::R_WASM_MEMORY_ADDR_SLEB: 962 case wasm::R_WASM_MEMORY_ADDR_I32: 963 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 964 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: 965 case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: 966 if (!isValidDataSymbol(Reloc.Index)) 967 return make_error<GenericBinaryError>("invalid relocation data index", 968 object_error::parse_failed); 969 Reloc.Addend = readVarint32(Ctx); 970 break; 971 case wasm::R_WASM_MEMORY_ADDR_LEB64: 972 case wasm::R_WASM_MEMORY_ADDR_SLEB64: 973 case wasm::R_WASM_MEMORY_ADDR_I64: 974 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 975 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64: 976 if (!isValidDataSymbol(Reloc.Index)) 977 return make_error<GenericBinaryError>("invalid relocation data index", 978 object_error::parse_failed); 979 Reloc.Addend = readVarint64(Ctx); 980 break; 981 case wasm::R_WASM_FUNCTION_OFFSET_I32: 982 if (!isValidFunctionSymbol(Reloc.Index)) 983 return make_error<GenericBinaryError>( 984 "invalid relocation function index", object_error::parse_failed); 985 Reloc.Addend = readVarint32(Ctx); 986 break; 987 case wasm::R_WASM_FUNCTION_OFFSET_I64: 988 if (!isValidFunctionSymbol(Reloc.Index)) 989 return make_error<GenericBinaryError>( 990 "invalid relocation function index", object_error::parse_failed); 991 Reloc.Addend = readVarint64(Ctx); 992 break; 993 case wasm::R_WASM_SECTION_OFFSET_I32: 994 if (!isValidSectionSymbol(Reloc.Index)) 995 return make_error<GenericBinaryError>( 996 "invalid relocation section index", object_error::parse_failed); 997 Reloc.Addend = readVarint32(Ctx); 998 break; 999 default: 1000 return make_error<GenericBinaryError>("invalid relocation type: " + 1001 Twine(type), 1002 object_error::parse_failed); 1003 } 1004 1005 // Relocations must fit inside the section, and must appear in order. They 1006 // also shouldn't overlap a function/element boundary, but we don't bother 1007 // to check that. 1008 uint64_t Size = 5; 1009 if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 || 1010 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 || 1011 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64) 1012 Size = 10; 1013 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 || 1014 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 || 1015 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LOCREL_I32 || 1016 Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 || 1017 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 1018 Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32) 1019 Size = 4; 1020 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 || 1021 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 || 1022 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64) 1023 Size = 8; 1024 if (Reloc.Offset + Size > EndOffset) 1025 return make_error<GenericBinaryError>("invalid relocation offset", 1026 object_error::parse_failed); 1027 1028 Section.Relocations.push_back(Reloc); 1029 } 1030 if (Ctx.Ptr != Ctx.End) 1031 return make_error<GenericBinaryError>("reloc section ended prematurely", 1032 object_error::parse_failed); 1033 return Error::success(); 1034 } 1035 1036 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) { 1037 if (Sec.Name == "dylink") { 1038 if (Error Err = parseDylinkSection(Ctx)) 1039 return Err; 1040 } else if (Sec.Name == "dylink.0") { 1041 if (Error Err = parseDylink0Section(Ctx)) 1042 return Err; 1043 } else if (Sec.Name == "name") { 1044 if (Error Err = parseNameSection(Ctx)) 1045 return Err; 1046 } else if (Sec.Name == "linking") { 1047 if (Error Err = parseLinkingSection(Ctx)) 1048 return Err; 1049 } else if (Sec.Name == "producers") { 1050 if (Error Err = parseProducersSection(Ctx)) 1051 return Err; 1052 } else if (Sec.Name == "target_features") { 1053 if (Error Err = parseTargetFeaturesSection(Ctx)) 1054 return Err; 1055 } else if (Sec.Name.startswith("reloc.")) { 1056 if (Error Err = parseRelocSection(Sec.Name, Ctx)) 1057 return Err; 1058 } 1059 return Error::success(); 1060 } 1061 1062 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) { 1063 uint32_t Count = readVaruint32(Ctx); 1064 Signatures.reserve(Count); 1065 while (Count--) { 1066 wasm::WasmSignature Sig; 1067 uint8_t Form = readUint8(Ctx); 1068 if (Form != wasm::WASM_TYPE_FUNC) { 1069 return make_error<GenericBinaryError>("invalid signature type", 1070 object_error::parse_failed); 1071 } 1072 uint32_t ParamCount = readVaruint32(Ctx); 1073 Sig.Params.reserve(ParamCount); 1074 while (ParamCount--) { 1075 uint32_t ParamType = readUint8(Ctx); 1076 Sig.Params.push_back(wasm::ValType(ParamType)); 1077 } 1078 uint32_t ReturnCount = readVaruint32(Ctx); 1079 while (ReturnCount--) { 1080 uint32_t ReturnType = readUint8(Ctx); 1081 Sig.Returns.push_back(wasm::ValType(ReturnType)); 1082 } 1083 Signatures.push_back(std::move(Sig)); 1084 } 1085 if (Ctx.Ptr != Ctx.End) 1086 return make_error<GenericBinaryError>("type section ended prematurely", 1087 object_error::parse_failed); 1088 return Error::success(); 1089 } 1090 1091 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) { 1092 uint32_t Count = readVaruint32(Ctx); 1093 Imports.reserve(Count); 1094 for (uint32_t I = 0; I < Count; I++) { 1095 wasm::WasmImport Im; 1096 Im.Module = readString(Ctx); 1097 Im.Field = readString(Ctx); 1098 Im.Kind = readUint8(Ctx); 1099 switch (Im.Kind) { 1100 case wasm::WASM_EXTERNAL_FUNCTION: 1101 NumImportedFunctions++; 1102 Im.SigIndex = readVaruint32(Ctx); 1103 break; 1104 case wasm::WASM_EXTERNAL_GLOBAL: 1105 NumImportedGlobals++; 1106 Im.Global.Type = readUint8(Ctx); 1107 Im.Global.Mutable = readVaruint1(Ctx); 1108 break; 1109 case wasm::WASM_EXTERNAL_MEMORY: 1110 Im.Memory = readLimits(Ctx); 1111 if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1112 HasMemory64 = true; 1113 break; 1114 case wasm::WASM_EXTERNAL_TABLE: { 1115 Im.Table = readTableType(Ctx); 1116 NumImportedTables++; 1117 auto ElemType = Im.Table.ElemType; 1118 if (ElemType != wasm::WASM_TYPE_FUNCREF && 1119 ElemType != wasm::WASM_TYPE_EXTERNREF) 1120 return make_error<GenericBinaryError>("invalid table element type", 1121 object_error::parse_failed); 1122 break; 1123 } 1124 case wasm::WASM_EXTERNAL_TAG: 1125 NumImportedTags++; 1126 Im.Tag.Attribute = readUint8(Ctx); 1127 Im.Tag.SigIndex = readVarint32(Ctx); 1128 break; 1129 default: 1130 return make_error<GenericBinaryError>("unexpected import kind", 1131 object_error::parse_failed); 1132 } 1133 Imports.push_back(Im); 1134 } 1135 if (Ctx.Ptr != Ctx.End) 1136 return make_error<GenericBinaryError>("import section ended prematurely", 1137 object_error::parse_failed); 1138 return Error::success(); 1139 } 1140 1141 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) { 1142 uint32_t Count = readVaruint32(Ctx); 1143 FunctionTypes.reserve(Count); 1144 Functions.resize(Count); 1145 uint32_t NumTypes = Signatures.size(); 1146 while (Count--) { 1147 uint32_t Type = readVaruint32(Ctx); 1148 if (Type >= NumTypes) 1149 return make_error<GenericBinaryError>("invalid function type", 1150 object_error::parse_failed); 1151 FunctionTypes.push_back(Type); 1152 } 1153 if (Ctx.Ptr != Ctx.End) 1154 return make_error<GenericBinaryError>("function section ended prematurely", 1155 object_error::parse_failed); 1156 return Error::success(); 1157 } 1158 1159 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) { 1160 TableSection = Sections.size(); 1161 uint32_t Count = readVaruint32(Ctx); 1162 Tables.reserve(Count); 1163 while (Count--) { 1164 wasm::WasmTable T; 1165 T.Type = readTableType(Ctx); 1166 T.Index = NumImportedTables + Tables.size(); 1167 Tables.push_back(T); 1168 auto ElemType = Tables.back().Type.ElemType; 1169 if (ElemType != wasm::WASM_TYPE_FUNCREF && 1170 ElemType != wasm::WASM_TYPE_EXTERNREF) { 1171 return make_error<GenericBinaryError>("invalid table element type", 1172 object_error::parse_failed); 1173 } 1174 } 1175 if (Ctx.Ptr != Ctx.End) 1176 return make_error<GenericBinaryError>("table section ended prematurely", 1177 object_error::parse_failed); 1178 return Error::success(); 1179 } 1180 1181 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) { 1182 uint32_t Count = readVaruint32(Ctx); 1183 Memories.reserve(Count); 1184 while (Count--) { 1185 auto Limits = readLimits(Ctx); 1186 if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1187 HasMemory64 = true; 1188 Memories.push_back(Limits); 1189 } 1190 if (Ctx.Ptr != Ctx.End) 1191 return make_error<GenericBinaryError>("memory section ended prematurely", 1192 object_error::parse_failed); 1193 return Error::success(); 1194 } 1195 1196 Error WasmObjectFile::parseTagSection(ReadContext &Ctx) { 1197 TagSection = Sections.size(); 1198 uint32_t Count = readVaruint32(Ctx); 1199 Tags.reserve(Count); 1200 while (Count--) { 1201 wasm::WasmTag Tag; 1202 Tag.Index = NumImportedTags + Tags.size(); 1203 Tag.Type.Attribute = readUint8(Ctx); 1204 Tag.Type.SigIndex = readVaruint32(Ctx); 1205 Tags.push_back(Tag); 1206 } 1207 1208 if (Ctx.Ptr != Ctx.End) 1209 return make_error<GenericBinaryError>("tag section ended prematurely", 1210 object_error::parse_failed); 1211 return Error::success(); 1212 } 1213 1214 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) { 1215 GlobalSection = Sections.size(); 1216 uint32_t Count = readVaruint32(Ctx); 1217 Globals.reserve(Count); 1218 while (Count--) { 1219 wasm::WasmGlobal Global; 1220 Global.Index = NumImportedGlobals + Globals.size(); 1221 Global.Type.Type = readUint8(Ctx); 1222 Global.Type.Mutable = readVaruint1(Ctx); 1223 if (Error Err = readInitExpr(Global.InitExpr, Ctx)) 1224 return Err; 1225 Globals.push_back(Global); 1226 } 1227 if (Ctx.Ptr != Ctx.End) 1228 return make_error<GenericBinaryError>("global section ended prematurely", 1229 object_error::parse_failed); 1230 return Error::success(); 1231 } 1232 1233 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) { 1234 uint32_t Count = readVaruint32(Ctx); 1235 Exports.reserve(Count); 1236 for (uint32_t I = 0; I < Count; I++) { 1237 wasm::WasmExport Ex; 1238 Ex.Name = readString(Ctx); 1239 Ex.Kind = readUint8(Ctx); 1240 Ex.Index = readVaruint32(Ctx); 1241 switch (Ex.Kind) { 1242 case wasm::WASM_EXTERNAL_FUNCTION: 1243 1244 if (!isDefinedFunctionIndex(Ex.Index)) 1245 return make_error<GenericBinaryError>("invalid function export", 1246 object_error::parse_failed); 1247 getDefinedFunction(Ex.Index).ExportName = Ex.Name; 1248 break; 1249 case wasm::WASM_EXTERNAL_GLOBAL: 1250 if (!isValidGlobalIndex(Ex.Index)) 1251 return make_error<GenericBinaryError>("invalid global export", 1252 object_error::parse_failed); 1253 break; 1254 case wasm::WASM_EXTERNAL_TAG: 1255 if (!isValidTagIndex(Ex.Index)) 1256 return make_error<GenericBinaryError>("invalid tag export", 1257 object_error::parse_failed); 1258 break; 1259 case wasm::WASM_EXTERNAL_MEMORY: 1260 case wasm::WASM_EXTERNAL_TABLE: 1261 break; 1262 default: 1263 return make_error<GenericBinaryError>("unexpected export kind", 1264 object_error::parse_failed); 1265 } 1266 Exports.push_back(Ex); 1267 } 1268 if (Ctx.Ptr != Ctx.End) 1269 return make_error<GenericBinaryError>("export section ended prematurely", 1270 object_error::parse_failed); 1271 return Error::success(); 1272 } 1273 1274 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const { 1275 return Index < NumImportedFunctions + FunctionTypes.size(); 1276 } 1277 1278 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const { 1279 return Index >= NumImportedFunctions && isValidFunctionIndex(Index); 1280 } 1281 1282 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const { 1283 return Index < NumImportedGlobals + Globals.size(); 1284 } 1285 1286 bool WasmObjectFile::isValidTableNumber(uint32_t Index) const { 1287 return Index < NumImportedTables + Tables.size(); 1288 } 1289 1290 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const { 1291 return Index >= NumImportedGlobals && isValidGlobalIndex(Index); 1292 } 1293 1294 bool WasmObjectFile::isDefinedTableNumber(uint32_t Index) const { 1295 return Index >= NumImportedTables && isValidTableNumber(Index); 1296 } 1297 1298 bool WasmObjectFile::isValidTagIndex(uint32_t Index) const { 1299 return Index < NumImportedTags + Tags.size(); 1300 } 1301 1302 bool WasmObjectFile::isDefinedTagIndex(uint32_t Index) const { 1303 return Index >= NumImportedTags && isValidTagIndex(Index); 1304 } 1305 1306 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const { 1307 return Index < Symbols.size() && Symbols[Index].isTypeFunction(); 1308 } 1309 1310 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const { 1311 return Index < Symbols.size() && Symbols[Index].isTypeTable(); 1312 } 1313 1314 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const { 1315 return Index < Symbols.size() && Symbols[Index].isTypeGlobal(); 1316 } 1317 1318 bool WasmObjectFile::isValidTagSymbol(uint32_t Index) const { 1319 return Index < Symbols.size() && Symbols[Index].isTypeTag(); 1320 } 1321 1322 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const { 1323 return Index < Symbols.size() && Symbols[Index].isTypeData(); 1324 } 1325 1326 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const { 1327 return Index < Symbols.size() && Symbols[Index].isTypeSection(); 1328 } 1329 1330 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) { 1331 assert(isDefinedFunctionIndex(Index)); 1332 return Functions[Index - NumImportedFunctions]; 1333 } 1334 1335 const wasm::WasmFunction & 1336 WasmObjectFile::getDefinedFunction(uint32_t Index) const { 1337 assert(isDefinedFunctionIndex(Index)); 1338 return Functions[Index - NumImportedFunctions]; 1339 } 1340 1341 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) { 1342 assert(isDefinedGlobalIndex(Index)); 1343 return Globals[Index - NumImportedGlobals]; 1344 } 1345 1346 wasm::WasmTag &WasmObjectFile::getDefinedTag(uint32_t Index) { 1347 assert(isDefinedTagIndex(Index)); 1348 return Tags[Index - NumImportedTags]; 1349 } 1350 1351 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) { 1352 StartFunction = readVaruint32(Ctx); 1353 if (!isValidFunctionIndex(StartFunction)) 1354 return make_error<GenericBinaryError>("invalid start function", 1355 object_error::parse_failed); 1356 return Error::success(); 1357 } 1358 1359 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) { 1360 SeenCodeSection = true; 1361 CodeSection = Sections.size(); 1362 uint32_t FunctionCount = readVaruint32(Ctx); 1363 if (FunctionCount != FunctionTypes.size()) { 1364 return make_error<GenericBinaryError>("invalid function count", 1365 object_error::parse_failed); 1366 } 1367 1368 for (uint32_t i = 0; i < FunctionCount; i++) { 1369 wasm::WasmFunction& Function = Functions[i]; 1370 const uint8_t *FunctionStart = Ctx.Ptr; 1371 uint32_t Size = readVaruint32(Ctx); 1372 const uint8_t *FunctionEnd = Ctx.Ptr + Size; 1373 1374 Function.CodeOffset = Ctx.Ptr - FunctionStart; 1375 Function.Index = NumImportedFunctions + i; 1376 Function.CodeSectionOffset = FunctionStart - Ctx.Start; 1377 Function.Size = FunctionEnd - FunctionStart; 1378 1379 uint32_t NumLocalDecls = readVaruint32(Ctx); 1380 Function.Locals.reserve(NumLocalDecls); 1381 while (NumLocalDecls--) { 1382 wasm::WasmLocalDecl Decl; 1383 Decl.Count = readVaruint32(Ctx); 1384 Decl.Type = readUint8(Ctx); 1385 Function.Locals.push_back(Decl); 1386 } 1387 1388 uint32_t BodySize = FunctionEnd - Ctx.Ptr; 1389 Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize); 1390 // This will be set later when reading in the linking metadata section. 1391 Function.Comdat = UINT32_MAX; 1392 Ctx.Ptr += BodySize; 1393 assert(Ctx.Ptr == FunctionEnd); 1394 } 1395 if (Ctx.Ptr != Ctx.End) 1396 return make_error<GenericBinaryError>("code section ended prematurely", 1397 object_error::parse_failed); 1398 return Error::success(); 1399 } 1400 1401 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) { 1402 uint32_t Count = readVaruint32(Ctx); 1403 ElemSegments.reserve(Count); 1404 while (Count--) { 1405 wasm::WasmElemSegment Segment; 1406 Segment.Flags = readVaruint32(Ctx); 1407 1408 uint32_t SupportedFlags = wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER | 1409 wasm::WASM_ELEM_SEGMENT_IS_PASSIVE | 1410 wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS; 1411 if (Segment.Flags & ~SupportedFlags) 1412 return make_error<GenericBinaryError>( 1413 "Unsupported flags for element segment", object_error::parse_failed); 1414 1415 if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER) 1416 Segment.TableNumber = readVaruint32(Ctx); 1417 else 1418 Segment.TableNumber = 0; 1419 if (!isValidTableNumber(Segment.TableNumber)) 1420 return make_error<GenericBinaryError>("invalid TableNumber", 1421 object_error::parse_failed); 1422 1423 if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_PASSIVE) { 1424 Segment.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST; 1425 Segment.Offset.Value.Int32 = 0; 1426 } else { 1427 if (Error Err = readInitExpr(Segment.Offset, Ctx)) 1428 return Err; 1429 } 1430 1431 if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) { 1432 Segment.ElemKind = readUint8(Ctx); 1433 if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) { 1434 if (Segment.ElemKind != uint8_t(wasm::ValType::FUNCREF) && 1435 Segment.ElemKind != uint8_t(wasm::ValType::EXTERNREF)) { 1436 return make_error<GenericBinaryError>("invalid reference type", 1437 object_error::parse_failed); 1438 } 1439 } else { 1440 if (Segment.ElemKind != 0) 1441 return make_error<GenericBinaryError>("invalid elemtype", 1442 object_error::parse_failed); 1443 Segment.ElemKind = uint8_t(wasm::ValType::FUNCREF); 1444 } 1445 } else { 1446 Segment.ElemKind = uint8_t(wasm::ValType::FUNCREF); 1447 } 1448 1449 if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) 1450 return make_error<GenericBinaryError>( 1451 "elem segment init expressions not yet implemented", 1452 object_error::parse_failed); 1453 1454 uint32_t NumElems = readVaruint32(Ctx); 1455 while (NumElems--) { 1456 Segment.Functions.push_back(readVaruint32(Ctx)); 1457 } 1458 ElemSegments.push_back(Segment); 1459 } 1460 if (Ctx.Ptr != Ctx.End) 1461 return make_error<GenericBinaryError>("elem section ended prematurely", 1462 object_error::parse_failed); 1463 return Error::success(); 1464 } 1465 1466 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) { 1467 DataSection = Sections.size(); 1468 uint32_t Count = readVaruint32(Ctx); 1469 if (DataCount && Count != DataCount.getValue()) 1470 return make_error<GenericBinaryError>( 1471 "number of data segments does not match DataCount section"); 1472 DataSegments.reserve(Count); 1473 while (Count--) { 1474 WasmSegment Segment; 1475 Segment.Data.InitFlags = readVaruint32(Ctx); 1476 Segment.Data.MemoryIndex = 1477 (Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX) 1478 ? readVaruint32(Ctx) 1479 : 0; 1480 if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) { 1481 if (Error Err = readInitExpr(Segment.Data.Offset, Ctx)) 1482 return Err; 1483 } else { 1484 Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST; 1485 Segment.Data.Offset.Value.Int32 = 0; 1486 } 1487 uint32_t Size = readVaruint32(Ctx); 1488 if (Size > (size_t)(Ctx.End - Ctx.Ptr)) 1489 return make_error<GenericBinaryError>("invalid segment size", 1490 object_error::parse_failed); 1491 Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size); 1492 // The rest of these Data fields are set later, when reading in the linking 1493 // metadata section. 1494 Segment.Data.Alignment = 0; 1495 Segment.Data.LinkingFlags = 0; 1496 Segment.Data.Comdat = UINT32_MAX; 1497 Segment.SectionOffset = Ctx.Ptr - Ctx.Start; 1498 Ctx.Ptr += Size; 1499 DataSegments.push_back(Segment); 1500 } 1501 if (Ctx.Ptr != Ctx.End) 1502 return make_error<GenericBinaryError>("data section ended prematurely", 1503 object_error::parse_failed); 1504 return Error::success(); 1505 } 1506 1507 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) { 1508 DataCount = readVaruint32(Ctx); 1509 return Error::success(); 1510 } 1511 1512 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const { 1513 return Header; 1514 } 1515 1516 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; } 1517 1518 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const { 1519 uint32_t Result = SymbolRef::SF_None; 1520 const WasmSymbol &Sym = getWasmSymbol(Symb); 1521 1522 LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n"); 1523 if (Sym.isBindingWeak()) 1524 Result |= SymbolRef::SF_Weak; 1525 if (!Sym.isBindingLocal()) 1526 Result |= SymbolRef::SF_Global; 1527 if (Sym.isHidden()) 1528 Result |= SymbolRef::SF_Hidden; 1529 if (!Sym.isDefined()) 1530 Result |= SymbolRef::SF_Undefined; 1531 if (Sym.isTypeFunction()) 1532 Result |= SymbolRef::SF_Executable; 1533 return Result; 1534 } 1535 1536 basic_symbol_iterator WasmObjectFile::symbol_begin() const { 1537 DataRefImpl Ref; 1538 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1539 Ref.d.b = 0; // Symbol index 1540 return BasicSymbolRef(Ref, this); 1541 } 1542 1543 basic_symbol_iterator WasmObjectFile::symbol_end() const { 1544 DataRefImpl Ref; 1545 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1546 Ref.d.b = Symbols.size(); // Symbol index 1547 return BasicSymbolRef(Ref, this); 1548 } 1549 1550 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const { 1551 return Symbols[Symb.d.b]; 1552 } 1553 1554 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const { 1555 return getWasmSymbol(Symb.getRawDataRefImpl()); 1556 } 1557 1558 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const { 1559 return getWasmSymbol(Symb).Info.Name; 1560 } 1561 1562 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const { 1563 auto &Sym = getWasmSymbol(Symb); 1564 if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION && 1565 isDefinedFunctionIndex(Sym.Info.ElementIndex)) 1566 return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset; 1567 else 1568 return getSymbolValue(Symb); 1569 } 1570 1571 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const { 1572 switch (Sym.Info.Kind) { 1573 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1574 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1575 case wasm::WASM_SYMBOL_TYPE_TAG: 1576 case wasm::WASM_SYMBOL_TYPE_TABLE: 1577 return Sym.Info.ElementIndex; 1578 case wasm::WASM_SYMBOL_TYPE_DATA: { 1579 // The value of a data symbol is the segment offset, plus the symbol 1580 // offset within the segment. 1581 uint32_t SegmentIndex = Sym.Info.DataRef.Segment; 1582 const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data; 1583 if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) { 1584 return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset; 1585 } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) { 1586 return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset; 1587 } else { 1588 llvm_unreachable("unknown init expr opcode"); 1589 } 1590 } 1591 case wasm::WASM_SYMBOL_TYPE_SECTION: 1592 return 0; 1593 } 1594 llvm_unreachable("invalid symbol type"); 1595 } 1596 1597 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const { 1598 return getWasmSymbolValue(getWasmSymbol(Symb)); 1599 } 1600 1601 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const { 1602 llvm_unreachable("not yet implemented"); 1603 return 0; 1604 } 1605 1606 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const { 1607 llvm_unreachable("not yet implemented"); 1608 return 0; 1609 } 1610 1611 Expected<SymbolRef::Type> 1612 WasmObjectFile::getSymbolType(DataRefImpl Symb) const { 1613 const WasmSymbol &Sym = getWasmSymbol(Symb); 1614 1615 switch (Sym.Info.Kind) { 1616 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1617 return SymbolRef::ST_Function; 1618 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1619 return SymbolRef::ST_Other; 1620 case wasm::WASM_SYMBOL_TYPE_DATA: 1621 return SymbolRef::ST_Data; 1622 case wasm::WASM_SYMBOL_TYPE_SECTION: 1623 return SymbolRef::ST_Debug; 1624 case wasm::WASM_SYMBOL_TYPE_TAG: 1625 return SymbolRef::ST_Other; 1626 case wasm::WASM_SYMBOL_TYPE_TABLE: 1627 return SymbolRef::ST_Other; 1628 } 1629 1630 llvm_unreachable("unknown WasmSymbol::SymbolType"); 1631 return SymbolRef::ST_Other; 1632 } 1633 1634 Expected<section_iterator> 1635 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const { 1636 const WasmSymbol &Sym = getWasmSymbol(Symb); 1637 if (Sym.isUndefined()) 1638 return section_end(); 1639 1640 DataRefImpl Ref; 1641 Ref.d.a = getSymbolSectionIdImpl(Sym); 1642 return section_iterator(SectionRef(Ref, this)); 1643 } 1644 1645 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const { 1646 const WasmSymbol &Sym = getWasmSymbol(Symb); 1647 return getSymbolSectionIdImpl(Sym); 1648 } 1649 1650 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const { 1651 switch (Sym.Info.Kind) { 1652 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1653 return CodeSection; 1654 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1655 return GlobalSection; 1656 case wasm::WASM_SYMBOL_TYPE_DATA: 1657 return DataSection; 1658 case wasm::WASM_SYMBOL_TYPE_SECTION: 1659 return Sym.Info.ElementIndex; 1660 case wasm::WASM_SYMBOL_TYPE_TAG: 1661 return TagSection; 1662 case wasm::WASM_SYMBOL_TYPE_TABLE: 1663 return TableSection; 1664 default: 1665 llvm_unreachable("unknown WasmSymbol::SymbolType"); 1666 } 1667 } 1668 1669 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; } 1670 1671 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const { 1672 const WasmSection &S = Sections[Sec.d.a]; 1673 #define ECase(X) \ 1674 case wasm::WASM_SEC_##X: \ 1675 return #X; 1676 switch (S.Type) { 1677 ECase(TYPE); 1678 ECase(IMPORT); 1679 ECase(FUNCTION); 1680 ECase(TABLE); 1681 ECase(MEMORY); 1682 ECase(GLOBAL); 1683 ECase(TAG); 1684 ECase(EXPORT); 1685 ECase(START); 1686 ECase(ELEM); 1687 ECase(CODE); 1688 ECase(DATA); 1689 ECase(DATACOUNT); 1690 case wasm::WASM_SEC_CUSTOM: 1691 return S.Name; 1692 default: 1693 return createStringError(object_error::invalid_section_index, ""); 1694 } 1695 #undef ECase 1696 } 1697 1698 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; } 1699 1700 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const { 1701 return Sec.d.a; 1702 } 1703 1704 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const { 1705 const WasmSection &S = Sections[Sec.d.a]; 1706 return S.Content.size(); 1707 } 1708 1709 Expected<ArrayRef<uint8_t>> 1710 WasmObjectFile::getSectionContents(DataRefImpl Sec) const { 1711 const WasmSection &S = Sections[Sec.d.a]; 1712 // This will never fail since wasm sections can never be empty (user-sections 1713 // must have a name and non-user sections each have a defined structure). 1714 return S.Content; 1715 } 1716 1717 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const { 1718 return 1; 1719 } 1720 1721 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const { 1722 return false; 1723 } 1724 1725 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const { 1726 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE; 1727 } 1728 1729 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const { 1730 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA; 1731 } 1732 1733 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; } 1734 1735 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; } 1736 1737 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const { 1738 DataRefImpl RelocRef; 1739 RelocRef.d.a = Ref.d.a; 1740 RelocRef.d.b = 0; 1741 return relocation_iterator(RelocationRef(RelocRef, this)); 1742 } 1743 1744 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const { 1745 const WasmSection &Sec = getWasmSection(Ref); 1746 DataRefImpl RelocRef; 1747 RelocRef.d.a = Ref.d.a; 1748 RelocRef.d.b = Sec.Relocations.size(); 1749 return relocation_iterator(RelocationRef(RelocRef, this)); 1750 } 1751 1752 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; } 1753 1754 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const { 1755 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1756 return Rel.Offset; 1757 } 1758 1759 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const { 1760 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1761 if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB) 1762 return symbol_end(); 1763 DataRefImpl Sym; 1764 Sym.d.a = 1; 1765 Sym.d.b = Rel.Index; 1766 return symbol_iterator(SymbolRef(Sym, this)); 1767 } 1768 1769 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const { 1770 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1771 return Rel.Type; 1772 } 1773 1774 void WasmObjectFile::getRelocationTypeName( 1775 DataRefImpl Ref, SmallVectorImpl<char> &Result) const { 1776 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1777 StringRef Res = "Unknown"; 1778 1779 #define WASM_RELOC(name, value) \ 1780 case wasm::name: \ 1781 Res = #name; \ 1782 break; 1783 1784 switch (Rel.Type) { 1785 #include "llvm/BinaryFormat/WasmRelocs.def" 1786 } 1787 1788 #undef WASM_RELOC 1789 1790 Result.append(Res.begin(), Res.end()); 1791 } 1792 1793 section_iterator WasmObjectFile::section_begin() const { 1794 DataRefImpl Ref; 1795 Ref.d.a = 0; 1796 return section_iterator(SectionRef(Ref, this)); 1797 } 1798 1799 section_iterator WasmObjectFile::section_end() const { 1800 DataRefImpl Ref; 1801 Ref.d.a = Sections.size(); 1802 return section_iterator(SectionRef(Ref, this)); 1803 } 1804 1805 uint8_t WasmObjectFile::getBytesInAddress() const { 1806 return HasMemory64 ? 8 : 4; 1807 } 1808 1809 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; } 1810 1811 Triple::ArchType WasmObjectFile::getArch() const { 1812 return HasMemory64 ? Triple::wasm64 : Triple::wasm32; 1813 } 1814 1815 SubtargetFeatures WasmObjectFile::getFeatures() const { 1816 return SubtargetFeatures(); 1817 } 1818 1819 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; } 1820 1821 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; } 1822 1823 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const { 1824 assert(Ref.d.a < Sections.size()); 1825 return Sections[Ref.d.a]; 1826 } 1827 1828 const WasmSection & 1829 WasmObjectFile::getWasmSection(const SectionRef &Section) const { 1830 return getWasmSection(Section.getRawDataRefImpl()); 1831 } 1832 1833 const wasm::WasmRelocation & 1834 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const { 1835 return getWasmRelocation(Ref.getRawDataRefImpl()); 1836 } 1837 1838 const wasm::WasmRelocation & 1839 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const { 1840 assert(Ref.d.a < Sections.size()); 1841 const WasmSection &Sec = Sections[Ref.d.a]; 1842 assert(Ref.d.b < Sec.Relocations.size()); 1843 return Sec.Relocations[Ref.d.b]; 1844 } 1845 1846 int WasmSectionOrderChecker::getSectionOrder(unsigned ID, 1847 StringRef CustomSectionName) { 1848 switch (ID) { 1849 case wasm::WASM_SEC_CUSTOM: 1850 return StringSwitch<unsigned>(CustomSectionName) 1851 .Case("dylink", WASM_SEC_ORDER_DYLINK) 1852 .Case("dylink.0", WASM_SEC_ORDER_DYLINK) 1853 .Case("linking", WASM_SEC_ORDER_LINKING) 1854 .StartsWith("reloc.", WASM_SEC_ORDER_RELOC) 1855 .Case("name", WASM_SEC_ORDER_NAME) 1856 .Case("producers", WASM_SEC_ORDER_PRODUCERS) 1857 .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES) 1858 .Default(WASM_SEC_ORDER_NONE); 1859 case wasm::WASM_SEC_TYPE: 1860 return WASM_SEC_ORDER_TYPE; 1861 case wasm::WASM_SEC_IMPORT: 1862 return WASM_SEC_ORDER_IMPORT; 1863 case wasm::WASM_SEC_FUNCTION: 1864 return WASM_SEC_ORDER_FUNCTION; 1865 case wasm::WASM_SEC_TABLE: 1866 return WASM_SEC_ORDER_TABLE; 1867 case wasm::WASM_SEC_MEMORY: 1868 return WASM_SEC_ORDER_MEMORY; 1869 case wasm::WASM_SEC_GLOBAL: 1870 return WASM_SEC_ORDER_GLOBAL; 1871 case wasm::WASM_SEC_EXPORT: 1872 return WASM_SEC_ORDER_EXPORT; 1873 case wasm::WASM_SEC_START: 1874 return WASM_SEC_ORDER_START; 1875 case wasm::WASM_SEC_ELEM: 1876 return WASM_SEC_ORDER_ELEM; 1877 case wasm::WASM_SEC_CODE: 1878 return WASM_SEC_ORDER_CODE; 1879 case wasm::WASM_SEC_DATA: 1880 return WASM_SEC_ORDER_DATA; 1881 case wasm::WASM_SEC_DATACOUNT: 1882 return WASM_SEC_ORDER_DATACOUNT; 1883 case wasm::WASM_SEC_TAG: 1884 return WASM_SEC_ORDER_TAG; 1885 default: 1886 return WASM_SEC_ORDER_NONE; 1887 } 1888 } 1889 1890 // Represents the edges in a directed graph where any node B reachable from node 1891 // A is not allowed to appear before A in the section ordering, but may appear 1892 // afterward. 1893 int WasmSectionOrderChecker::DisallowedPredecessors 1894 [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = { 1895 // WASM_SEC_ORDER_NONE 1896 {}, 1897 // WASM_SEC_ORDER_TYPE 1898 {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT}, 1899 // WASM_SEC_ORDER_IMPORT 1900 {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION}, 1901 // WASM_SEC_ORDER_FUNCTION 1902 {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE}, 1903 // WASM_SEC_ORDER_TABLE 1904 {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY}, 1905 // WASM_SEC_ORDER_MEMORY 1906 {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_TAG}, 1907 // WASM_SEC_ORDER_TAG 1908 {WASM_SEC_ORDER_TAG, WASM_SEC_ORDER_GLOBAL}, 1909 // WASM_SEC_ORDER_GLOBAL 1910 {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT}, 1911 // WASM_SEC_ORDER_EXPORT 1912 {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START}, 1913 // WASM_SEC_ORDER_START 1914 {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM}, 1915 // WASM_SEC_ORDER_ELEM 1916 {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT}, 1917 // WASM_SEC_ORDER_DATACOUNT 1918 {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE}, 1919 // WASM_SEC_ORDER_CODE 1920 {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA}, 1921 // WASM_SEC_ORDER_DATA 1922 {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING}, 1923 1924 // Custom Sections 1925 // WASM_SEC_ORDER_DYLINK 1926 {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE}, 1927 // WASM_SEC_ORDER_LINKING 1928 {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME}, 1929 // WASM_SEC_ORDER_RELOC (can be repeated) 1930 {}, 1931 // WASM_SEC_ORDER_NAME 1932 {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS}, 1933 // WASM_SEC_ORDER_PRODUCERS 1934 {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES}, 1935 // WASM_SEC_ORDER_TARGET_FEATURES 1936 {WASM_SEC_ORDER_TARGET_FEATURES}}; 1937 1938 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID, 1939 StringRef CustomSectionName) { 1940 int Order = getSectionOrder(ID, CustomSectionName); 1941 if (Order == WASM_SEC_ORDER_NONE) 1942 return true; 1943 1944 // Disallowed predecessors we need to check for 1945 SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList; 1946 1947 // Keep track of completed checks to avoid repeating work 1948 bool Checked[WASM_NUM_SEC_ORDERS] = {}; 1949 1950 int Curr = Order; 1951 while (true) { 1952 // Add new disallowed predecessors to work list 1953 for (size_t I = 0;; ++I) { 1954 int Next = DisallowedPredecessors[Curr][I]; 1955 if (Next == WASM_SEC_ORDER_NONE) 1956 break; 1957 if (Checked[Next]) 1958 continue; 1959 WorkList.push_back(Next); 1960 Checked[Next] = true; 1961 } 1962 1963 if (WorkList.empty()) 1964 break; 1965 1966 // Consider next disallowed predecessor 1967 Curr = WorkList.pop_back_val(); 1968 if (Seen[Curr]) 1969 return false; 1970 } 1971 1972 // Have not seen any disallowed predecessors 1973 Seen[Order] = true; 1974 return true; 1975 } 1976