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