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