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