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_SECTION_OFFSET_I32: 880 if (!isValidSectionSymbol(Reloc.Index)) 881 return make_error<GenericBinaryError>("Bad relocation section index", 882 object_error::parse_failed); 883 Reloc.Addend = readVarint32(Ctx); 884 break; 885 default: 886 return make_error<GenericBinaryError>("Bad relocation type: " + 887 Twine(Reloc.Type), 888 object_error::parse_failed); 889 } 890 891 // Relocations must fit inside the section, and must appear in order. They 892 // also shouldn't overlap a function/element boundary, but we don't bother 893 // to check that. 894 uint64_t Size = 5; 895 if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 || 896 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 || 897 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64) 898 Size = 10; 899 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 || 900 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 || 901 Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 || 902 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 903 Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32) 904 Size = 4; 905 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 || 906 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64) 907 Size = 8; 908 if (Reloc.Offset + Size > EndOffset) 909 return make_error<GenericBinaryError>("Bad relocation offset", 910 object_error::parse_failed); 911 912 Section.Relocations.push_back(Reloc); 913 } 914 if (Ctx.Ptr != Ctx.End) 915 return make_error<GenericBinaryError>("Reloc section ended prematurely", 916 object_error::parse_failed); 917 return Error::success(); 918 } 919 920 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) { 921 if (Sec.Name == "dylink") { 922 if (Error Err = parseDylinkSection(Ctx)) 923 return Err; 924 } else if (Sec.Name == "name") { 925 if (Error Err = parseNameSection(Ctx)) 926 return Err; 927 } else if (Sec.Name == "linking") { 928 if (Error Err = parseLinkingSection(Ctx)) 929 return Err; 930 } else if (Sec.Name == "producers") { 931 if (Error Err = parseProducersSection(Ctx)) 932 return Err; 933 } else if (Sec.Name == "target_features") { 934 if (Error Err = parseTargetFeaturesSection(Ctx)) 935 return Err; 936 } else if (Sec.Name.startswith("reloc.")) { 937 if (Error Err = parseRelocSection(Sec.Name, Ctx)) 938 return Err; 939 } 940 return Error::success(); 941 } 942 943 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) { 944 uint32_t Count = readVaruint32(Ctx); 945 Signatures.reserve(Count); 946 while (Count--) { 947 wasm::WasmSignature Sig; 948 uint8_t Form = readUint8(Ctx); 949 if (Form != wasm::WASM_TYPE_FUNC) { 950 return make_error<GenericBinaryError>("Invalid signature type", 951 object_error::parse_failed); 952 } 953 uint32_t ParamCount = readVaruint32(Ctx); 954 Sig.Params.reserve(ParamCount); 955 while (ParamCount--) { 956 uint32_t ParamType = readUint8(Ctx); 957 Sig.Params.push_back(wasm::ValType(ParamType)); 958 } 959 uint32_t ReturnCount = readVaruint32(Ctx); 960 while (ReturnCount--) { 961 uint32_t ReturnType = readUint8(Ctx); 962 Sig.Returns.push_back(wasm::ValType(ReturnType)); 963 } 964 Signatures.push_back(std::move(Sig)); 965 } 966 if (Ctx.Ptr != Ctx.End) 967 return make_error<GenericBinaryError>("Type section ended prematurely", 968 object_error::parse_failed); 969 return Error::success(); 970 } 971 972 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) { 973 uint32_t Count = readVaruint32(Ctx); 974 Imports.reserve(Count); 975 for (uint32_t I = 0; I < Count; I++) { 976 wasm::WasmImport Im; 977 Im.Module = readString(Ctx); 978 Im.Field = readString(Ctx); 979 Im.Kind = readUint8(Ctx); 980 switch (Im.Kind) { 981 case wasm::WASM_EXTERNAL_FUNCTION: 982 NumImportedFunctions++; 983 Im.SigIndex = readVaruint32(Ctx); 984 break; 985 case wasm::WASM_EXTERNAL_GLOBAL: 986 NumImportedGlobals++; 987 Im.Global.Type = readUint8(Ctx); 988 Im.Global.Mutable = readVaruint1(Ctx); 989 break; 990 case wasm::WASM_EXTERNAL_MEMORY: 991 Im.Memory = readLimits(Ctx); 992 if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 993 HasMemory64 = true; 994 break; 995 case wasm::WASM_EXTERNAL_TABLE: { 996 Im.Table = readTable(Ctx); 997 Im.Table.Index = NumImportedTables + Tables.size(); 998 NumImportedTables++; 999 auto ElemType = Im.Table.ElemType; 1000 if (ElemType != wasm::WASM_TYPE_FUNCREF && 1001 ElemType != wasm::WASM_TYPE_EXTERNREF) 1002 return make_error<GenericBinaryError>("Invalid table element type", 1003 object_error::parse_failed); 1004 break; 1005 } 1006 case wasm::WASM_EXTERNAL_EVENT: 1007 NumImportedEvents++; 1008 Im.Event.Attribute = readVarint32(Ctx); 1009 Im.Event.SigIndex = readVarint32(Ctx); 1010 break; 1011 default: 1012 return make_error<GenericBinaryError>("Unexpected import kind", 1013 object_error::parse_failed); 1014 } 1015 Imports.push_back(Im); 1016 } 1017 if (Ctx.Ptr != Ctx.End) 1018 return make_error<GenericBinaryError>("Import section ended prematurely", 1019 object_error::parse_failed); 1020 return Error::success(); 1021 } 1022 1023 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) { 1024 uint32_t Count = readVaruint32(Ctx); 1025 FunctionTypes.reserve(Count); 1026 Functions.resize(Count); 1027 uint32_t NumTypes = Signatures.size(); 1028 while (Count--) { 1029 uint32_t Type = readVaruint32(Ctx); 1030 if (Type >= NumTypes) 1031 return make_error<GenericBinaryError>("Invalid function type", 1032 object_error::parse_failed); 1033 FunctionTypes.push_back(Type); 1034 } 1035 if (Ctx.Ptr != Ctx.End) 1036 return make_error<GenericBinaryError>("Function section ended prematurely", 1037 object_error::parse_failed); 1038 return Error::success(); 1039 } 1040 1041 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) { 1042 uint32_t Count = readVaruint32(Ctx); 1043 Tables.reserve(Count); 1044 while (Count--) { 1045 wasm::WasmTable T = readTable(Ctx); 1046 T.Index = NumImportedTables + Tables.size(); 1047 Tables.push_back(T); 1048 auto ElemType = Tables.back().ElemType; 1049 if (ElemType != wasm::WASM_TYPE_FUNCREF && 1050 ElemType != wasm::WASM_TYPE_EXTERNREF) { 1051 return make_error<GenericBinaryError>("Invalid table element type", 1052 object_error::parse_failed); 1053 } 1054 } 1055 if (Ctx.Ptr != Ctx.End) 1056 return make_error<GenericBinaryError>("Table section ended prematurely", 1057 object_error::parse_failed); 1058 return Error::success(); 1059 } 1060 1061 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) { 1062 uint32_t Count = readVaruint32(Ctx); 1063 Memories.reserve(Count); 1064 while (Count--) { 1065 auto Limits = readLimits(Ctx); 1066 if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1067 HasMemory64 = true; 1068 Memories.push_back(Limits); 1069 } 1070 if (Ctx.Ptr != Ctx.End) 1071 return make_error<GenericBinaryError>("Memory section ended prematurely", 1072 object_error::parse_failed); 1073 return Error::success(); 1074 } 1075 1076 Error WasmObjectFile::parseEventSection(ReadContext &Ctx) { 1077 EventSection = Sections.size(); 1078 uint32_t Count = readVarint32(Ctx); 1079 Events.reserve(Count); 1080 while (Count--) { 1081 wasm::WasmEvent Event; 1082 Event.Index = NumImportedEvents + Events.size(); 1083 Event.Type.Attribute = readVaruint32(Ctx); 1084 Event.Type.SigIndex = readVarint32(Ctx); 1085 Events.push_back(Event); 1086 } 1087 1088 if (Ctx.Ptr != Ctx.End) 1089 return make_error<GenericBinaryError>("Event section ended prematurely", 1090 object_error::parse_failed); 1091 return Error::success(); 1092 } 1093 1094 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) { 1095 GlobalSection = Sections.size(); 1096 uint32_t Count = readVaruint32(Ctx); 1097 Globals.reserve(Count); 1098 while (Count--) { 1099 wasm::WasmGlobal Global; 1100 Global.Index = NumImportedGlobals + Globals.size(); 1101 Global.Type.Type = readUint8(Ctx); 1102 Global.Type.Mutable = readVaruint1(Ctx); 1103 if (Error Err = readInitExpr(Global.InitExpr, Ctx)) 1104 return Err; 1105 Globals.push_back(Global); 1106 } 1107 if (Ctx.Ptr != Ctx.End) 1108 return make_error<GenericBinaryError>("Global section ended prematurely", 1109 object_error::parse_failed); 1110 return Error::success(); 1111 } 1112 1113 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) { 1114 uint32_t Count = readVaruint32(Ctx); 1115 Exports.reserve(Count); 1116 for (uint32_t I = 0; I < Count; I++) { 1117 wasm::WasmExport Ex; 1118 Ex.Name = readString(Ctx); 1119 Ex.Kind = readUint8(Ctx); 1120 Ex.Index = readVaruint32(Ctx); 1121 switch (Ex.Kind) { 1122 case wasm::WASM_EXTERNAL_FUNCTION: 1123 1124 if (!isDefinedFunctionIndex(Ex.Index)) 1125 return make_error<GenericBinaryError>("Invalid function export", 1126 object_error::parse_failed); 1127 getDefinedFunction(Ex.Index).ExportName = Ex.Name; 1128 break; 1129 case wasm::WASM_EXTERNAL_GLOBAL: 1130 if (!isValidGlobalIndex(Ex.Index)) 1131 return make_error<GenericBinaryError>("Invalid global export", 1132 object_error::parse_failed); 1133 break; 1134 case wasm::WASM_EXTERNAL_EVENT: 1135 if (!isValidEventIndex(Ex.Index)) 1136 return make_error<GenericBinaryError>("Invalid event export", 1137 object_error::parse_failed); 1138 break; 1139 case wasm::WASM_EXTERNAL_MEMORY: 1140 case wasm::WASM_EXTERNAL_TABLE: 1141 break; 1142 default: 1143 return make_error<GenericBinaryError>("Unexpected export kind", 1144 object_error::parse_failed); 1145 } 1146 Exports.push_back(Ex); 1147 } 1148 if (Ctx.Ptr != Ctx.End) 1149 return make_error<GenericBinaryError>("Export section ended prematurely", 1150 object_error::parse_failed); 1151 return Error::success(); 1152 } 1153 1154 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const { 1155 return Index < NumImportedFunctions + FunctionTypes.size(); 1156 } 1157 1158 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const { 1159 return Index >= NumImportedFunctions && isValidFunctionIndex(Index); 1160 } 1161 1162 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const { 1163 return Index < NumImportedGlobals + Globals.size(); 1164 } 1165 1166 bool WasmObjectFile::isValidTableIndex(uint32_t Index) const { 1167 return Index < NumImportedTables + Tables.size(); 1168 } 1169 1170 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const { 1171 return Index >= NumImportedGlobals && isValidGlobalIndex(Index); 1172 } 1173 1174 bool WasmObjectFile::isDefinedTableIndex(uint32_t Index) const { 1175 return Index >= NumImportedTables && isValidTableIndex(Index); 1176 } 1177 1178 bool WasmObjectFile::isValidEventIndex(uint32_t Index) const { 1179 return Index < NumImportedEvents + Events.size(); 1180 } 1181 1182 bool WasmObjectFile::isDefinedEventIndex(uint32_t Index) const { 1183 return Index >= NumImportedEvents && isValidEventIndex(Index); 1184 } 1185 1186 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const { 1187 return Index < Symbols.size() && Symbols[Index].isTypeFunction(); 1188 } 1189 1190 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const { 1191 return Index < Symbols.size() && Symbols[Index].isTypeTable(); 1192 } 1193 1194 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const { 1195 return Index < Symbols.size() && Symbols[Index].isTypeGlobal(); 1196 } 1197 1198 bool WasmObjectFile::isValidEventSymbol(uint32_t Index) const { 1199 return Index < Symbols.size() && Symbols[Index].isTypeEvent(); 1200 } 1201 1202 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const { 1203 return Index < Symbols.size() && Symbols[Index].isTypeData(); 1204 } 1205 1206 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const { 1207 return Index < Symbols.size() && Symbols[Index].isTypeSection(); 1208 } 1209 1210 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) { 1211 assert(isDefinedFunctionIndex(Index)); 1212 return Functions[Index - NumImportedFunctions]; 1213 } 1214 1215 const wasm::WasmFunction & 1216 WasmObjectFile::getDefinedFunction(uint32_t Index) const { 1217 assert(isDefinedFunctionIndex(Index)); 1218 return Functions[Index - NumImportedFunctions]; 1219 } 1220 1221 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) { 1222 assert(isDefinedGlobalIndex(Index)); 1223 return Globals[Index - NumImportedGlobals]; 1224 } 1225 1226 wasm::WasmEvent &WasmObjectFile::getDefinedEvent(uint32_t Index) { 1227 assert(isDefinedEventIndex(Index)); 1228 return Events[Index - NumImportedEvents]; 1229 } 1230 1231 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) { 1232 StartFunction = readVaruint32(Ctx); 1233 if (!isValidFunctionIndex(StartFunction)) 1234 return make_error<GenericBinaryError>("Invalid start function", 1235 object_error::parse_failed); 1236 return Error::success(); 1237 } 1238 1239 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) { 1240 SeenCodeSection = true; 1241 CodeSection = Sections.size(); 1242 uint32_t FunctionCount = readVaruint32(Ctx); 1243 if (FunctionCount != FunctionTypes.size()) { 1244 return make_error<GenericBinaryError>("Invalid function count", 1245 object_error::parse_failed); 1246 } 1247 1248 for (uint32_t i = 0; i < FunctionCount; i++) { 1249 wasm::WasmFunction& Function = Functions[i]; 1250 const uint8_t *FunctionStart = Ctx.Ptr; 1251 uint32_t Size = readVaruint32(Ctx); 1252 const uint8_t *FunctionEnd = Ctx.Ptr + Size; 1253 1254 Function.CodeOffset = Ctx.Ptr - FunctionStart; 1255 Function.Index = NumImportedFunctions + i; 1256 Function.CodeSectionOffset = FunctionStart - Ctx.Start; 1257 Function.Size = FunctionEnd - FunctionStart; 1258 1259 uint32_t NumLocalDecls = readVaruint32(Ctx); 1260 Function.Locals.reserve(NumLocalDecls); 1261 while (NumLocalDecls--) { 1262 wasm::WasmLocalDecl Decl; 1263 Decl.Count = readVaruint32(Ctx); 1264 Decl.Type = readUint8(Ctx); 1265 Function.Locals.push_back(Decl); 1266 } 1267 1268 uint32_t BodySize = FunctionEnd - Ctx.Ptr; 1269 Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize); 1270 // This will be set later when reading in the linking metadata section. 1271 Function.Comdat = UINT32_MAX; 1272 Ctx.Ptr += BodySize; 1273 assert(Ctx.Ptr == FunctionEnd); 1274 } 1275 if (Ctx.Ptr != Ctx.End) 1276 return make_error<GenericBinaryError>("Code section ended prematurely", 1277 object_error::parse_failed); 1278 return Error::success(); 1279 } 1280 1281 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) { 1282 uint32_t Count = readVaruint32(Ctx); 1283 ElemSegments.reserve(Count); 1284 while (Count--) { 1285 wasm::WasmElemSegment Segment; 1286 Segment.TableIndex = readVaruint32(Ctx); 1287 if (Segment.TableIndex != 0) { 1288 return make_error<GenericBinaryError>("Invalid TableIndex", 1289 object_error::parse_failed); 1290 } 1291 if (Error Err = readInitExpr(Segment.Offset, Ctx)) 1292 return Err; 1293 uint32_t NumElems = readVaruint32(Ctx); 1294 while (NumElems--) { 1295 Segment.Functions.push_back(readVaruint32(Ctx)); 1296 } 1297 ElemSegments.push_back(Segment); 1298 } 1299 if (Ctx.Ptr != Ctx.End) 1300 return make_error<GenericBinaryError>("Elem section ended prematurely", 1301 object_error::parse_failed); 1302 return Error::success(); 1303 } 1304 1305 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) { 1306 DataSection = Sections.size(); 1307 uint32_t Count = readVaruint32(Ctx); 1308 if (DataCount && Count != DataCount.getValue()) 1309 return make_error<GenericBinaryError>( 1310 "Number of data segments does not match DataCount section"); 1311 DataSegments.reserve(Count); 1312 while (Count--) { 1313 WasmSegment Segment; 1314 Segment.Data.InitFlags = readVaruint32(Ctx); 1315 Segment.Data.MemoryIndex = (Segment.Data.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX) 1316 ? readVaruint32(Ctx) : 0; 1317 if ((Segment.Data.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) { 1318 if (Error Err = readInitExpr(Segment.Data.Offset, Ctx)) 1319 return Err; 1320 } else { 1321 Segment.Data.Offset.Opcode = wasm::WASM_OPCODE_I32_CONST; 1322 Segment.Data.Offset.Value.Int32 = 0; 1323 } 1324 uint32_t Size = readVaruint32(Ctx); 1325 if (Size > (size_t)(Ctx.End - Ctx.Ptr)) 1326 return make_error<GenericBinaryError>("Invalid segment size", 1327 object_error::parse_failed); 1328 Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size); 1329 // The rest of these Data fields are set later, when reading in the linking 1330 // metadata section. 1331 Segment.Data.Alignment = 0; 1332 Segment.Data.LinkerFlags = 0; 1333 Segment.Data.Comdat = UINT32_MAX; 1334 Segment.SectionOffset = Ctx.Ptr - Ctx.Start; 1335 Ctx.Ptr += Size; 1336 DataSegments.push_back(Segment); 1337 } 1338 if (Ctx.Ptr != Ctx.End) 1339 return make_error<GenericBinaryError>("Data section ended prematurely", 1340 object_error::parse_failed); 1341 return Error::success(); 1342 } 1343 1344 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) { 1345 DataCount = readVaruint32(Ctx); 1346 return Error::success(); 1347 } 1348 1349 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const { 1350 return Header; 1351 } 1352 1353 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; } 1354 1355 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const { 1356 uint32_t Result = SymbolRef::SF_None; 1357 const WasmSymbol &Sym = getWasmSymbol(Symb); 1358 1359 LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n"); 1360 if (Sym.isBindingWeak()) 1361 Result |= SymbolRef::SF_Weak; 1362 if (!Sym.isBindingLocal()) 1363 Result |= SymbolRef::SF_Global; 1364 if (Sym.isHidden()) 1365 Result |= SymbolRef::SF_Hidden; 1366 if (!Sym.isDefined()) 1367 Result |= SymbolRef::SF_Undefined; 1368 if (Sym.isTypeFunction()) 1369 Result |= SymbolRef::SF_Executable; 1370 return Result; 1371 } 1372 1373 basic_symbol_iterator WasmObjectFile::symbol_begin() const { 1374 DataRefImpl Ref; 1375 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1376 Ref.d.b = 0; // Symbol index 1377 return BasicSymbolRef(Ref, this); 1378 } 1379 1380 basic_symbol_iterator WasmObjectFile::symbol_end() const { 1381 DataRefImpl Ref; 1382 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1383 Ref.d.b = Symbols.size(); // Symbol index 1384 return BasicSymbolRef(Ref, this); 1385 } 1386 1387 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const { 1388 return Symbols[Symb.d.b]; 1389 } 1390 1391 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const { 1392 return getWasmSymbol(Symb.getRawDataRefImpl()); 1393 } 1394 1395 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const { 1396 return getWasmSymbol(Symb).Info.Name; 1397 } 1398 1399 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const { 1400 auto &Sym = getWasmSymbol(Symb); 1401 if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION && 1402 isDefinedFunctionIndex(Sym.Info.ElementIndex)) 1403 return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset; 1404 else 1405 return getSymbolValue(Symb); 1406 } 1407 1408 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const { 1409 switch (Sym.Info.Kind) { 1410 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1411 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1412 case wasm::WASM_SYMBOL_TYPE_EVENT: 1413 return Sym.Info.ElementIndex; 1414 case wasm::WASM_SYMBOL_TYPE_DATA: { 1415 // The value of a data symbol is the segment offset, plus the symbol 1416 // offset within the segment. 1417 uint32_t SegmentIndex = Sym.Info.DataRef.Segment; 1418 const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data; 1419 if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I32_CONST) { 1420 return Segment.Offset.Value.Int32 + Sym.Info.DataRef.Offset; 1421 } else if (Segment.Offset.Opcode == wasm::WASM_OPCODE_I64_CONST) { 1422 return Segment.Offset.Value.Int64 + Sym.Info.DataRef.Offset; 1423 } else { 1424 llvm_unreachable("unknown init expr opcode"); 1425 } 1426 } 1427 case wasm::WASM_SYMBOL_TYPE_SECTION: 1428 return 0; 1429 } 1430 llvm_unreachable("invalid symbol type"); 1431 } 1432 1433 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const { 1434 return getWasmSymbolValue(getWasmSymbol(Symb)); 1435 } 1436 1437 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const { 1438 llvm_unreachable("not yet implemented"); 1439 return 0; 1440 } 1441 1442 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const { 1443 llvm_unreachable("not yet implemented"); 1444 return 0; 1445 } 1446 1447 Expected<SymbolRef::Type> 1448 WasmObjectFile::getSymbolType(DataRefImpl Symb) const { 1449 const WasmSymbol &Sym = getWasmSymbol(Symb); 1450 1451 switch (Sym.Info.Kind) { 1452 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1453 return SymbolRef::ST_Function; 1454 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1455 return SymbolRef::ST_Other; 1456 case wasm::WASM_SYMBOL_TYPE_DATA: 1457 return SymbolRef::ST_Data; 1458 case wasm::WASM_SYMBOL_TYPE_SECTION: 1459 return SymbolRef::ST_Debug; 1460 case wasm::WASM_SYMBOL_TYPE_EVENT: 1461 return SymbolRef::ST_Other; 1462 } 1463 1464 llvm_unreachable("Unknown WasmSymbol::SymbolType"); 1465 return SymbolRef::ST_Other; 1466 } 1467 1468 Expected<section_iterator> 1469 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const { 1470 const WasmSymbol &Sym = getWasmSymbol(Symb); 1471 if (Sym.isUndefined()) 1472 return section_end(); 1473 1474 DataRefImpl Ref; 1475 Ref.d.a = getSymbolSectionIdImpl(Sym); 1476 return section_iterator(SectionRef(Ref, this)); 1477 } 1478 1479 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const { 1480 const WasmSymbol &Sym = getWasmSymbol(Symb); 1481 return getSymbolSectionIdImpl(Sym); 1482 } 1483 1484 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const { 1485 switch (Sym.Info.Kind) { 1486 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1487 return CodeSection; 1488 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1489 return GlobalSection; 1490 case wasm::WASM_SYMBOL_TYPE_DATA: 1491 return DataSection; 1492 case wasm::WASM_SYMBOL_TYPE_SECTION: 1493 return Sym.Info.ElementIndex; 1494 case wasm::WASM_SYMBOL_TYPE_EVENT: 1495 return EventSection; 1496 default: 1497 llvm_unreachable("Unknown WasmSymbol::SymbolType"); 1498 } 1499 } 1500 1501 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; } 1502 1503 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const { 1504 const WasmSection &S = Sections[Sec.d.a]; 1505 #define ECase(X) \ 1506 case wasm::WASM_SEC_##X: \ 1507 return #X; 1508 switch (S.Type) { 1509 ECase(TYPE); 1510 ECase(IMPORT); 1511 ECase(FUNCTION); 1512 ECase(TABLE); 1513 ECase(MEMORY); 1514 ECase(GLOBAL); 1515 ECase(EVENT); 1516 ECase(EXPORT); 1517 ECase(START); 1518 ECase(ELEM); 1519 ECase(CODE); 1520 ECase(DATA); 1521 ECase(DATACOUNT); 1522 case wasm::WASM_SEC_CUSTOM: 1523 return S.Name; 1524 default: 1525 return createStringError(object_error::invalid_section_index, ""); 1526 } 1527 #undef ECase 1528 } 1529 1530 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; } 1531 1532 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const { 1533 return Sec.d.a; 1534 } 1535 1536 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const { 1537 const WasmSection &S = Sections[Sec.d.a]; 1538 return S.Content.size(); 1539 } 1540 1541 Expected<ArrayRef<uint8_t>> 1542 WasmObjectFile::getSectionContents(DataRefImpl Sec) const { 1543 const WasmSection &S = Sections[Sec.d.a]; 1544 // This will never fail since wasm sections can never be empty (user-sections 1545 // must have a name and non-user sections each have a defined structure). 1546 return S.Content; 1547 } 1548 1549 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const { 1550 return 1; 1551 } 1552 1553 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const { 1554 return false; 1555 } 1556 1557 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const { 1558 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE; 1559 } 1560 1561 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const { 1562 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA; 1563 } 1564 1565 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; } 1566 1567 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; } 1568 1569 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const { 1570 DataRefImpl RelocRef; 1571 RelocRef.d.a = Ref.d.a; 1572 RelocRef.d.b = 0; 1573 return relocation_iterator(RelocationRef(RelocRef, this)); 1574 } 1575 1576 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const { 1577 const WasmSection &Sec = getWasmSection(Ref); 1578 DataRefImpl RelocRef; 1579 RelocRef.d.a = Ref.d.a; 1580 RelocRef.d.b = Sec.Relocations.size(); 1581 return relocation_iterator(RelocationRef(RelocRef, this)); 1582 } 1583 1584 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; } 1585 1586 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const { 1587 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1588 return Rel.Offset; 1589 } 1590 1591 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const { 1592 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1593 if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB) 1594 return symbol_end(); 1595 DataRefImpl Sym; 1596 Sym.d.a = 1; 1597 Sym.d.b = Rel.Index; 1598 return symbol_iterator(SymbolRef(Sym, this)); 1599 } 1600 1601 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const { 1602 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1603 return Rel.Type; 1604 } 1605 1606 void WasmObjectFile::getRelocationTypeName( 1607 DataRefImpl Ref, SmallVectorImpl<char> &Result) const { 1608 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1609 StringRef Res = "Unknown"; 1610 1611 #define WASM_RELOC(name, value) \ 1612 case wasm::name: \ 1613 Res = #name; \ 1614 break; 1615 1616 switch (Rel.Type) { 1617 #include "llvm/BinaryFormat/WasmRelocs.def" 1618 } 1619 1620 #undef WASM_RELOC 1621 1622 Result.append(Res.begin(), Res.end()); 1623 } 1624 1625 section_iterator WasmObjectFile::section_begin() const { 1626 DataRefImpl Ref; 1627 Ref.d.a = 0; 1628 return section_iterator(SectionRef(Ref, this)); 1629 } 1630 1631 section_iterator WasmObjectFile::section_end() const { 1632 DataRefImpl Ref; 1633 Ref.d.a = Sections.size(); 1634 return section_iterator(SectionRef(Ref, this)); 1635 } 1636 1637 uint8_t WasmObjectFile::getBytesInAddress() const { 1638 return HasMemory64 ? 8 : 4; 1639 } 1640 1641 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; } 1642 1643 Triple::ArchType WasmObjectFile::getArch() const { 1644 return HasMemory64 ? Triple::wasm64 : Triple::wasm32; 1645 } 1646 1647 SubtargetFeatures WasmObjectFile::getFeatures() const { 1648 return SubtargetFeatures(); 1649 } 1650 1651 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; } 1652 1653 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; } 1654 1655 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const { 1656 assert(Ref.d.a < Sections.size()); 1657 return Sections[Ref.d.a]; 1658 } 1659 1660 const WasmSection & 1661 WasmObjectFile::getWasmSection(const SectionRef &Section) const { 1662 return getWasmSection(Section.getRawDataRefImpl()); 1663 } 1664 1665 const wasm::WasmRelocation & 1666 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const { 1667 return getWasmRelocation(Ref.getRawDataRefImpl()); 1668 } 1669 1670 const wasm::WasmRelocation & 1671 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const { 1672 assert(Ref.d.a < Sections.size()); 1673 const WasmSection &Sec = Sections[Ref.d.a]; 1674 assert(Ref.d.b < Sec.Relocations.size()); 1675 return Sec.Relocations[Ref.d.b]; 1676 } 1677 1678 int WasmSectionOrderChecker::getSectionOrder(unsigned ID, 1679 StringRef CustomSectionName) { 1680 switch (ID) { 1681 case wasm::WASM_SEC_CUSTOM: 1682 return StringSwitch<unsigned>(CustomSectionName) 1683 .Case("dylink", WASM_SEC_ORDER_DYLINK) 1684 .Case("linking", WASM_SEC_ORDER_LINKING) 1685 .StartsWith("reloc.", WASM_SEC_ORDER_RELOC) 1686 .Case("name", WASM_SEC_ORDER_NAME) 1687 .Case("producers", WASM_SEC_ORDER_PRODUCERS) 1688 .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES) 1689 .Default(WASM_SEC_ORDER_NONE); 1690 case wasm::WASM_SEC_TYPE: 1691 return WASM_SEC_ORDER_TYPE; 1692 case wasm::WASM_SEC_IMPORT: 1693 return WASM_SEC_ORDER_IMPORT; 1694 case wasm::WASM_SEC_FUNCTION: 1695 return WASM_SEC_ORDER_FUNCTION; 1696 case wasm::WASM_SEC_TABLE: 1697 return WASM_SEC_ORDER_TABLE; 1698 case wasm::WASM_SEC_MEMORY: 1699 return WASM_SEC_ORDER_MEMORY; 1700 case wasm::WASM_SEC_GLOBAL: 1701 return WASM_SEC_ORDER_GLOBAL; 1702 case wasm::WASM_SEC_EXPORT: 1703 return WASM_SEC_ORDER_EXPORT; 1704 case wasm::WASM_SEC_START: 1705 return WASM_SEC_ORDER_START; 1706 case wasm::WASM_SEC_ELEM: 1707 return WASM_SEC_ORDER_ELEM; 1708 case wasm::WASM_SEC_CODE: 1709 return WASM_SEC_ORDER_CODE; 1710 case wasm::WASM_SEC_DATA: 1711 return WASM_SEC_ORDER_DATA; 1712 case wasm::WASM_SEC_DATACOUNT: 1713 return WASM_SEC_ORDER_DATACOUNT; 1714 case wasm::WASM_SEC_EVENT: 1715 return WASM_SEC_ORDER_EVENT; 1716 default: 1717 return WASM_SEC_ORDER_NONE; 1718 } 1719 } 1720 1721 // Represents the edges in a directed graph where any node B reachable from node 1722 // A is not allowed to appear before A in the section ordering, but may appear 1723 // afterward. 1724 int WasmSectionOrderChecker::DisallowedPredecessors 1725 [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = { 1726 // WASM_SEC_ORDER_NONE 1727 {}, 1728 // WASM_SEC_ORDER_TYPE 1729 {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT}, 1730 // WASM_SEC_ORDER_IMPORT 1731 {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION}, 1732 // WASM_SEC_ORDER_FUNCTION 1733 {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE}, 1734 // WASM_SEC_ORDER_TABLE 1735 {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY}, 1736 // WASM_SEC_ORDER_MEMORY 1737 {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_EVENT}, 1738 // WASM_SEC_ORDER_EVENT 1739 {WASM_SEC_ORDER_EVENT, WASM_SEC_ORDER_GLOBAL}, 1740 // WASM_SEC_ORDER_GLOBAL 1741 {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT}, 1742 // WASM_SEC_ORDER_EXPORT 1743 {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START}, 1744 // WASM_SEC_ORDER_START 1745 {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM}, 1746 // WASM_SEC_ORDER_ELEM 1747 {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT}, 1748 // WASM_SEC_ORDER_DATACOUNT 1749 {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE}, 1750 // WASM_SEC_ORDER_CODE 1751 {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA}, 1752 // WASM_SEC_ORDER_DATA 1753 {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING}, 1754 1755 // Custom Sections 1756 // WASM_SEC_ORDER_DYLINK 1757 {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE}, 1758 // WASM_SEC_ORDER_LINKING 1759 {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME}, 1760 // WASM_SEC_ORDER_RELOC (can be repeated) 1761 {}, 1762 // WASM_SEC_ORDER_NAME 1763 {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS}, 1764 // WASM_SEC_ORDER_PRODUCERS 1765 {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES}, 1766 // WASM_SEC_ORDER_TARGET_FEATURES 1767 {WASM_SEC_ORDER_TARGET_FEATURES}}; 1768 1769 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID, 1770 StringRef CustomSectionName) { 1771 int Order = getSectionOrder(ID, CustomSectionName); 1772 if (Order == WASM_SEC_ORDER_NONE) 1773 return true; 1774 1775 // Disallowed predecessors we need to check for 1776 SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList; 1777 1778 // Keep track of completed checks to avoid repeating work 1779 bool Checked[WASM_NUM_SEC_ORDERS] = {}; 1780 1781 int Curr = Order; 1782 while (true) { 1783 // Add new disallowed predecessors to work list 1784 for (size_t I = 0;; ++I) { 1785 int Next = DisallowedPredecessors[Curr][I]; 1786 if (Next == WASM_SEC_ORDER_NONE) 1787 break; 1788 if (Checked[Next]) 1789 continue; 1790 WorkList.push_back(Next); 1791 Checked[Next] = true; 1792 } 1793 1794 if (WorkList.empty()) 1795 break; 1796 1797 // Consider next disallowed predecessor 1798 Curr = WorkList.pop_back_val(); 1799 if (Seen[Curr]) 1800 return false; 1801 } 1802 1803 // Have not seen any disallowed predecessors 1804 Seen[Order] = true; 1805 return true; 1806 } 1807