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