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 (Functions.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 (Functions.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 wasm::WasmFunction &Function = Functions[FuncIndex]; 602 Signature = &Signatures[Function.SigIndex]; 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 Functions.reserve(Count); 1144 uint32_t NumTypes = Signatures.size(); 1145 while (Count--) { 1146 uint32_t Type = readVaruint32(Ctx); 1147 if (Type >= NumTypes) 1148 return make_error<GenericBinaryError>("invalid function type", 1149 object_error::parse_failed); 1150 wasm::WasmFunction F; 1151 F.SigIndex = Type; 1152 Functions.push_back(F); 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 + Functions.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 != Functions.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