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