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