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/SmallSet.h" 12 #include "llvm/ADT/StringRef.h" 13 #include "llvm/ADT/StringSet.h" 14 #include "llvm/ADT/StringSwitch.h" 15 #include "llvm/BinaryFormat/Wasm.h" 16 #include "llvm/Object/Binary.h" 17 #include "llvm/Object/Error.h" 18 #include "llvm/Object/ObjectFile.h" 19 #include "llvm/Object/SymbolicFile.h" 20 #include "llvm/Object/Wasm.h" 21 #include "llvm/Support/Endian.h" 22 #include "llvm/Support/Error.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/Support/Format.h" 25 #include "llvm/Support/LEB128.h" 26 #include "llvm/Support/ScopedPrinter.h" 27 #include "llvm/TargetParser/SubtargetFeature.h" 28 #include "llvm/TargetParser/Triple.h" 29 #include <algorithm> 30 #include <cassert> 31 #include <cstdint> 32 #include <cstring> 33 #include <limits> 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)) << ", Flags=0x" 43 << Twine::utohexstr(Info.Flags) << " ["; 44 switch (getBinding()) { 45 case wasm::WASM_SYMBOL_BINDING_GLOBAL: Out << "global"; break; 46 case wasm::WASM_SYMBOL_BINDING_LOCAL: Out << "local"; break; 47 case wasm::WASM_SYMBOL_BINDING_WEAK: Out << "weak"; break; 48 } 49 if (isHidden()) { 50 Out << ", hidden"; 51 } else { 52 Out << ", default"; 53 } 54 Out << "]"; 55 if (!isTypeData()) { 56 Out << ", ElemIndex=" << Info.ElementIndex; 57 } else if (isDefined()) { 58 Out << ", Segment=" << Info.DataRef.Segment; 59 Out << ", Offset=" << Info.DataRef.Offset; 60 Out << ", Size=" << Info.DataRef.Size; 61 } 62 } 63 64 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 65 LLVM_DUMP_METHOD void WasmSymbol::dump() const { print(dbgs()); } 66 #endif 67 68 Expected<std::unique_ptr<WasmObjectFile>> 69 ObjectFile::createWasmObjectFile(MemoryBufferRef Buffer) { 70 Error Err = Error::success(); 71 auto ObjectFile = std::make_unique<WasmObjectFile>(Buffer, Err); 72 if (Err) 73 return std::move(Err); 74 75 return std::move(ObjectFile); 76 } 77 78 #define VARINT7_MAX ((1 << 7) - 1) 79 #define VARINT7_MIN (-(1 << 7)) 80 #define VARUINT7_MAX (1 << 7) 81 #define VARUINT1_MAX (1) 82 83 static uint8_t readUint8(WasmObjectFile::ReadContext &Ctx) { 84 if (Ctx.Ptr == Ctx.End) 85 report_fatal_error("EOF while reading uint8"); 86 return *Ctx.Ptr++; 87 } 88 89 static uint32_t readUint32(WasmObjectFile::ReadContext &Ctx) { 90 if (Ctx.Ptr + 4 > Ctx.End) 91 report_fatal_error("EOF while reading uint32"); 92 uint32_t Result = support::endian::read32le(Ctx.Ptr); 93 Ctx.Ptr += 4; 94 return Result; 95 } 96 97 static int32_t readFloat32(WasmObjectFile::ReadContext &Ctx) { 98 if (Ctx.Ptr + 4 > Ctx.End) 99 report_fatal_error("EOF while reading float64"); 100 int32_t Result = 0; 101 memcpy(&Result, Ctx.Ptr, sizeof(Result)); 102 Ctx.Ptr += sizeof(Result); 103 return Result; 104 } 105 106 static int64_t readFloat64(WasmObjectFile::ReadContext &Ctx) { 107 if (Ctx.Ptr + 8 > Ctx.End) 108 report_fatal_error("EOF while reading float64"); 109 int64_t Result = 0; 110 memcpy(&Result, Ctx.Ptr, sizeof(Result)); 111 Ctx.Ptr += sizeof(Result); 112 return Result; 113 } 114 115 static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx) { 116 unsigned Count; 117 const char *Error = nullptr; 118 uint64_t Result = decodeULEB128(Ctx.Ptr, &Count, Ctx.End, &Error); 119 if (Error) 120 report_fatal_error(Error); 121 Ctx.Ptr += Count; 122 return Result; 123 } 124 125 static StringRef readString(WasmObjectFile::ReadContext &Ctx) { 126 uint32_t StringLen = readULEB128(Ctx); 127 if (Ctx.Ptr + StringLen > Ctx.End) 128 report_fatal_error("EOF while reading string"); 129 StringRef Return = 130 StringRef(reinterpret_cast<const char *>(Ctx.Ptr), StringLen); 131 Ctx.Ptr += StringLen; 132 return Return; 133 } 134 135 static int64_t readLEB128(WasmObjectFile::ReadContext &Ctx) { 136 unsigned Count; 137 const char *Error = nullptr; 138 uint64_t Result = decodeSLEB128(Ctx.Ptr, &Count, Ctx.End, &Error); 139 if (Error) 140 report_fatal_error(Error); 141 Ctx.Ptr += Count; 142 return Result; 143 } 144 145 static uint8_t readVaruint1(WasmObjectFile::ReadContext &Ctx) { 146 int64_t Result = readLEB128(Ctx); 147 if (Result > VARUINT1_MAX || Result < 0) 148 report_fatal_error("LEB is outside Varuint1 range"); 149 return Result; 150 } 151 152 static int32_t readVarint32(WasmObjectFile::ReadContext &Ctx) { 153 int64_t Result = readLEB128(Ctx); 154 if (Result > INT32_MAX || Result < INT32_MIN) 155 report_fatal_error("LEB is outside Varint32 range"); 156 return Result; 157 } 158 159 static uint32_t readVaruint32(WasmObjectFile::ReadContext &Ctx) { 160 uint64_t Result = readULEB128(Ctx); 161 if (Result > UINT32_MAX) 162 report_fatal_error("LEB is outside Varuint32 range"); 163 return Result; 164 } 165 166 static int64_t readVarint64(WasmObjectFile::ReadContext &Ctx) { 167 return readLEB128(Ctx); 168 } 169 170 static uint64_t readVaruint64(WasmObjectFile::ReadContext &Ctx) { 171 return readULEB128(Ctx); 172 } 173 174 static uint8_t readOpcode(WasmObjectFile::ReadContext &Ctx) { 175 return readUint8(Ctx); 176 } 177 178 static wasm::ValType parseValType(WasmObjectFile::ReadContext &Ctx, 179 uint32_t Code) { 180 // only directly encoded FUNCREF/EXTERNREF are supported 181 // (not ref null func or ref null extern) 182 switch (Code) { 183 case wasm::WASM_TYPE_I32: 184 case wasm::WASM_TYPE_I64: 185 case wasm::WASM_TYPE_F32: 186 case wasm::WASM_TYPE_F64: 187 case wasm::WASM_TYPE_V128: 188 case wasm::WASM_TYPE_FUNCREF: 189 case wasm::WASM_TYPE_EXTERNREF: 190 return wasm::ValType(Code); 191 } 192 if (Code == wasm::WASM_TYPE_NULLABLE || Code == wasm::WASM_TYPE_NONNULLABLE) { 193 /* Discard HeapType */ readVarint64(Ctx); 194 } 195 return wasm::ValType(wasm::ValType::OTHERREF); 196 } 197 198 static Error readInitExpr(wasm::WasmInitExpr &Expr, 199 WasmObjectFile::ReadContext &Ctx) { 200 auto Start = Ctx.Ptr; 201 202 Expr.Extended = false; 203 Expr.Inst.Opcode = readOpcode(Ctx); 204 switch (Expr.Inst.Opcode) { 205 case wasm::WASM_OPCODE_I32_CONST: 206 Expr.Inst.Value.Int32 = readVarint32(Ctx); 207 break; 208 case wasm::WASM_OPCODE_I64_CONST: 209 Expr.Inst.Value.Int64 = readVarint64(Ctx); 210 break; 211 case wasm::WASM_OPCODE_F32_CONST: 212 Expr.Inst.Value.Float32 = readFloat32(Ctx); 213 break; 214 case wasm::WASM_OPCODE_F64_CONST: 215 Expr.Inst.Value.Float64 = readFloat64(Ctx); 216 break; 217 case wasm::WASM_OPCODE_GLOBAL_GET: 218 Expr.Inst.Value.Global = readULEB128(Ctx); 219 break; 220 case wasm::WASM_OPCODE_REF_NULL: { 221 /* Discard type */ parseValType(Ctx, readVaruint32(Ctx)); 222 break; 223 } 224 default: 225 Expr.Extended = true; 226 } 227 228 if (!Expr.Extended) { 229 uint8_t EndOpcode = readOpcode(Ctx); 230 if (EndOpcode != wasm::WASM_OPCODE_END) 231 Expr.Extended = true; 232 } 233 234 if (Expr.Extended) { 235 Ctx.Ptr = Start; 236 while (true) { 237 uint8_t Opcode = readOpcode(Ctx); 238 switch (Opcode) { 239 case wasm::WASM_OPCODE_I32_CONST: 240 case wasm::WASM_OPCODE_GLOBAL_GET: 241 case wasm::WASM_OPCODE_REF_NULL: 242 case wasm::WASM_OPCODE_REF_FUNC: 243 case wasm::WASM_OPCODE_I64_CONST: 244 readULEB128(Ctx); 245 break; 246 case wasm::WASM_OPCODE_F32_CONST: 247 readFloat32(Ctx); 248 break; 249 case wasm::WASM_OPCODE_F64_CONST: 250 readFloat64(Ctx); 251 break; 252 case wasm::WASM_OPCODE_I32_ADD: 253 case wasm::WASM_OPCODE_I32_SUB: 254 case wasm::WASM_OPCODE_I32_MUL: 255 case wasm::WASM_OPCODE_I64_ADD: 256 case wasm::WASM_OPCODE_I64_SUB: 257 case wasm::WASM_OPCODE_I64_MUL: 258 break; 259 case wasm::WASM_OPCODE_GC_PREFIX: 260 break; 261 // The GC opcodes are in a separate (prefixed space). This flat switch 262 // structure works as long as there is no overlap between the GC and 263 // general opcodes used in init exprs. 264 case wasm::WASM_OPCODE_STRUCT_NEW: 265 case wasm::WASM_OPCODE_STRUCT_NEW_DEFAULT: 266 case wasm::WASM_OPCODE_ARRAY_NEW: 267 case wasm::WASM_OPCODE_ARRAY_NEW_DEFAULT: 268 readULEB128(Ctx); // heap type index 269 break; 270 case wasm::WASM_OPCODE_ARRAY_NEW_FIXED: 271 readULEB128(Ctx); // heap type index 272 readULEB128(Ctx); // array size 273 break; 274 case wasm::WASM_OPCODE_REF_I31: 275 break; 276 case wasm::WASM_OPCODE_END: 277 Expr.Body = ArrayRef<uint8_t>(Start, Ctx.Ptr - Start); 278 return Error::success(); 279 default: 280 return make_error<GenericBinaryError>( 281 Twine("invalid opcode in init_expr: ") + Twine(unsigned(Opcode)), 282 object_error::parse_failed); 283 } 284 } 285 } 286 287 return Error::success(); 288 } 289 290 static wasm::WasmLimits readLimits(WasmObjectFile::ReadContext &Ctx) { 291 wasm::WasmLimits Result; 292 Result.Flags = readVaruint32(Ctx); 293 Result.Minimum = readVaruint64(Ctx); 294 if (Result.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX) 295 Result.Maximum = readVaruint64(Ctx); 296 return Result; 297 } 298 299 static wasm::WasmTableType readTableType(WasmObjectFile::ReadContext &Ctx) { 300 wasm::WasmTableType TableType; 301 auto ElemType = parseValType(Ctx, readVaruint32(Ctx)); 302 TableType.ElemType = ElemType; 303 TableType.Limits = readLimits(Ctx); 304 return TableType; 305 } 306 307 static Error readSection(WasmSection &Section, WasmObjectFile::ReadContext &Ctx, 308 WasmSectionOrderChecker &Checker) { 309 Section.Type = readUint8(Ctx); 310 LLVM_DEBUG(dbgs() << "readSection type=" << Section.Type << "\n"); 311 // When reading the section's size, store the size of the LEB used to encode 312 // it. This allows objcopy/strip to reproduce the binary identically. 313 const uint8_t *PreSizePtr = Ctx.Ptr; 314 uint32_t Size = readVaruint32(Ctx); 315 Section.HeaderSecSizeEncodingLen = Ctx.Ptr - PreSizePtr; 316 Section.Offset = Ctx.Ptr - Ctx.Start; 317 if (Size == 0) 318 return make_error<StringError>("zero length section", 319 object_error::parse_failed); 320 if (Ctx.Ptr + Size > Ctx.End) 321 return make_error<StringError>("section too large", 322 object_error::parse_failed); 323 if (Section.Type == wasm::WASM_SEC_CUSTOM) { 324 WasmObjectFile::ReadContext SectionCtx; 325 SectionCtx.Start = Ctx.Ptr; 326 SectionCtx.Ptr = Ctx.Ptr; 327 SectionCtx.End = Ctx.Ptr + Size; 328 329 Section.Name = readString(SectionCtx); 330 331 uint32_t SectionNameSize = SectionCtx.Ptr - SectionCtx.Start; 332 Ctx.Ptr += SectionNameSize; 333 Size -= SectionNameSize; 334 } 335 336 if (!Checker.isValidSectionOrder(Section.Type, Section.Name)) { 337 return make_error<StringError>("out of order section type: " + 338 llvm::to_string(Section.Type), 339 object_error::parse_failed); 340 } 341 342 Section.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size); 343 Ctx.Ptr += Size; 344 return Error::success(); 345 } 346 347 WasmObjectFile::WasmObjectFile(MemoryBufferRef Buffer, Error &Err) 348 : ObjectFile(Binary::ID_Wasm, Buffer) { 349 ErrorAsOutParameter ErrAsOutParam(&Err); 350 Header.Magic = getData().substr(0, 4); 351 if (Header.Magic != StringRef("\0asm", 4)) { 352 Err = make_error<StringError>("invalid magic number", 353 object_error::parse_failed); 354 return; 355 } 356 357 ReadContext Ctx; 358 Ctx.Start = getData().bytes_begin(); 359 Ctx.Ptr = Ctx.Start + 4; 360 Ctx.End = Ctx.Start + getData().size(); 361 362 if (Ctx.Ptr + 4 > Ctx.End) { 363 Err = make_error<StringError>("missing version number", 364 object_error::parse_failed); 365 return; 366 } 367 368 Header.Version = readUint32(Ctx); 369 if (Header.Version != wasm::WasmVersion) { 370 Err = make_error<StringError>("invalid version number: " + 371 Twine(Header.Version), 372 object_error::parse_failed); 373 return; 374 } 375 376 WasmSectionOrderChecker Checker; 377 while (Ctx.Ptr < Ctx.End) { 378 WasmSection Sec; 379 if ((Err = readSection(Sec, Ctx, Checker))) 380 return; 381 if ((Err = parseSection(Sec))) 382 return; 383 384 Sections.push_back(Sec); 385 } 386 } 387 388 Error WasmObjectFile::parseSection(WasmSection &Sec) { 389 ReadContext Ctx; 390 Ctx.Start = Sec.Content.data(); 391 Ctx.End = Ctx.Start + Sec.Content.size(); 392 Ctx.Ptr = Ctx.Start; 393 switch (Sec.Type) { 394 case wasm::WASM_SEC_CUSTOM: 395 return parseCustomSection(Sec, Ctx); 396 case wasm::WASM_SEC_TYPE: 397 return parseTypeSection(Ctx); 398 case wasm::WASM_SEC_IMPORT: 399 return parseImportSection(Ctx); 400 case wasm::WASM_SEC_FUNCTION: 401 return parseFunctionSection(Ctx); 402 case wasm::WASM_SEC_TABLE: 403 return parseTableSection(Ctx); 404 case wasm::WASM_SEC_MEMORY: 405 return parseMemorySection(Ctx); 406 case wasm::WASM_SEC_TAG: 407 return parseTagSection(Ctx); 408 case wasm::WASM_SEC_GLOBAL: 409 return parseGlobalSection(Ctx); 410 case wasm::WASM_SEC_EXPORT: 411 return parseExportSection(Ctx); 412 case wasm::WASM_SEC_START: 413 return parseStartSection(Ctx); 414 case wasm::WASM_SEC_ELEM: 415 return parseElemSection(Ctx); 416 case wasm::WASM_SEC_CODE: 417 return parseCodeSection(Ctx); 418 case wasm::WASM_SEC_DATA: 419 return parseDataSection(Ctx); 420 case wasm::WASM_SEC_DATACOUNT: 421 return parseDataCountSection(Ctx); 422 default: 423 return make_error<GenericBinaryError>( 424 "invalid section type: " + Twine(Sec.Type), object_error::parse_failed); 425 } 426 } 427 428 Error WasmObjectFile::parseDylinkSection(ReadContext &Ctx) { 429 // Legacy "dylink" section support. 430 // See parseDylink0Section for the current "dylink.0" section parsing. 431 HasDylinkSection = true; 432 DylinkInfo.MemorySize = readVaruint32(Ctx); 433 DylinkInfo.MemoryAlignment = readVaruint32(Ctx); 434 DylinkInfo.TableSize = readVaruint32(Ctx); 435 DylinkInfo.TableAlignment = readVaruint32(Ctx); 436 uint32_t Count = readVaruint32(Ctx); 437 while (Count--) { 438 DylinkInfo.Needed.push_back(readString(Ctx)); 439 } 440 441 if (Ctx.Ptr != Ctx.End) 442 return make_error<GenericBinaryError>("dylink section ended prematurely", 443 object_error::parse_failed); 444 return Error::success(); 445 } 446 447 Error WasmObjectFile::parseDylink0Section(ReadContext &Ctx) { 448 // See 449 // https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md 450 HasDylinkSection = true; 451 452 const uint8_t *OrigEnd = Ctx.End; 453 while (Ctx.Ptr < OrigEnd) { 454 Ctx.End = OrigEnd; 455 uint8_t Type = readUint8(Ctx); 456 uint32_t Size = readVaruint32(Ctx); 457 LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size 458 << "\n"); 459 Ctx.End = Ctx.Ptr + Size; 460 uint32_t Count; 461 switch (Type) { 462 case wasm::WASM_DYLINK_MEM_INFO: 463 DylinkInfo.MemorySize = readVaruint32(Ctx); 464 DylinkInfo.MemoryAlignment = readVaruint32(Ctx); 465 DylinkInfo.TableSize = readVaruint32(Ctx); 466 DylinkInfo.TableAlignment = readVaruint32(Ctx); 467 break; 468 case wasm::WASM_DYLINK_NEEDED: 469 Count = readVaruint32(Ctx); 470 while (Count--) { 471 DylinkInfo.Needed.push_back(readString(Ctx)); 472 } 473 break; 474 case wasm::WASM_DYLINK_EXPORT_INFO: { 475 uint32_t Count = readVaruint32(Ctx); 476 while (Count--) { 477 DylinkInfo.ExportInfo.push_back({readString(Ctx), readVaruint32(Ctx)}); 478 } 479 break; 480 } 481 case wasm::WASM_DYLINK_IMPORT_INFO: { 482 uint32_t Count = readVaruint32(Ctx); 483 while (Count--) { 484 DylinkInfo.ImportInfo.push_back( 485 {readString(Ctx), readString(Ctx), readVaruint32(Ctx)}); 486 } 487 break; 488 } 489 default: 490 LLVM_DEBUG(dbgs() << "unknown dylink.0 sub-section: " << Type << "\n"); 491 Ctx.Ptr += Size; 492 break; 493 } 494 if (Ctx.Ptr != Ctx.End) { 495 return make_error<GenericBinaryError>( 496 "dylink.0 sub-section ended prematurely", object_error::parse_failed); 497 } 498 } 499 500 if (Ctx.Ptr != Ctx.End) 501 return make_error<GenericBinaryError>("dylink.0 section ended prematurely", 502 object_error::parse_failed); 503 return Error::success(); 504 } 505 506 Error WasmObjectFile::parseNameSection(ReadContext &Ctx) { 507 llvm::DenseSet<uint64_t> SeenFunctions; 508 llvm::DenseSet<uint64_t> SeenGlobals; 509 llvm::DenseSet<uint64_t> SeenSegments; 510 511 while (Ctx.Ptr < Ctx.End) { 512 uint8_t Type = readUint8(Ctx); 513 uint32_t Size = readVaruint32(Ctx); 514 const uint8_t *SubSectionEnd = Ctx.Ptr + Size; 515 switch (Type) { 516 case wasm::WASM_NAMES_FUNCTION: 517 case wasm::WASM_NAMES_GLOBAL: 518 case wasm::WASM_NAMES_DATA_SEGMENT: { 519 uint32_t Count = readVaruint32(Ctx); 520 while (Count--) { 521 uint32_t Index = readVaruint32(Ctx); 522 StringRef Name = readString(Ctx); 523 wasm::NameType nameType = wasm::NameType::FUNCTION; 524 if (Type == wasm::WASM_NAMES_FUNCTION) { 525 if (!SeenFunctions.insert(Index).second) 526 return make_error<GenericBinaryError>( 527 "function named more than once", object_error::parse_failed); 528 if (!isValidFunctionIndex(Index) || Name.empty()) 529 return make_error<GenericBinaryError>("invalid function name entry", 530 object_error::parse_failed); 531 532 if (isDefinedFunctionIndex(Index)) 533 getDefinedFunction(Index).DebugName = Name; 534 } else if (Type == wasm::WASM_NAMES_GLOBAL) { 535 nameType = wasm::NameType::GLOBAL; 536 if (!SeenGlobals.insert(Index).second) 537 return make_error<GenericBinaryError>("global named more than once", 538 object_error::parse_failed); 539 if (!isValidGlobalIndex(Index) || Name.empty()) 540 return make_error<GenericBinaryError>("invalid global name entry", 541 object_error::parse_failed); 542 } else { 543 nameType = wasm::NameType::DATA_SEGMENT; 544 if (!SeenSegments.insert(Index).second) 545 return make_error<GenericBinaryError>( 546 "segment named more than once", object_error::parse_failed); 547 if (Index > DataSegments.size()) 548 return make_error<GenericBinaryError>("invalid data segment name entry", 549 object_error::parse_failed); 550 } 551 DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name}); 552 } 553 break; 554 } 555 // Ignore local names for now 556 case wasm::WASM_NAMES_LOCAL: 557 default: 558 Ctx.Ptr += Size; 559 break; 560 } 561 if (Ctx.Ptr != SubSectionEnd) 562 return make_error<GenericBinaryError>( 563 "name sub-section ended prematurely", object_error::parse_failed); 564 } 565 566 if (Ctx.Ptr != Ctx.End) 567 return make_error<GenericBinaryError>("name section ended prematurely", 568 object_error::parse_failed); 569 return Error::success(); 570 } 571 572 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) { 573 HasLinkingSection = true; 574 575 LinkingData.Version = readVaruint32(Ctx); 576 if (LinkingData.Version != wasm::WasmMetadataVersion) { 577 return make_error<GenericBinaryError>( 578 "unexpected metadata version: " + Twine(LinkingData.Version) + 579 " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")", 580 object_error::parse_failed); 581 } 582 583 const uint8_t *OrigEnd = Ctx.End; 584 while (Ctx.Ptr < OrigEnd) { 585 Ctx.End = OrigEnd; 586 uint8_t Type = readUint8(Ctx); 587 uint32_t Size = readVaruint32(Ctx); 588 LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size 589 << "\n"); 590 Ctx.End = Ctx.Ptr + Size; 591 switch (Type) { 592 case wasm::WASM_SYMBOL_TABLE: 593 if (Error Err = parseLinkingSectionSymtab(Ctx)) 594 return Err; 595 break; 596 case wasm::WASM_SEGMENT_INFO: { 597 uint32_t Count = readVaruint32(Ctx); 598 if (Count > DataSegments.size()) 599 return make_error<GenericBinaryError>("too many segment names", 600 object_error::parse_failed); 601 for (uint32_t I = 0; I < Count; I++) { 602 DataSegments[I].Data.Name = readString(Ctx); 603 DataSegments[I].Data.Alignment = readVaruint32(Ctx); 604 DataSegments[I].Data.LinkingFlags = readVaruint32(Ctx); 605 } 606 break; 607 } 608 case wasm::WASM_INIT_FUNCS: { 609 uint32_t Count = readVaruint32(Ctx); 610 LinkingData.InitFunctions.reserve(Count); 611 for (uint32_t I = 0; I < Count; I++) { 612 wasm::WasmInitFunc Init; 613 Init.Priority = readVaruint32(Ctx); 614 Init.Symbol = readVaruint32(Ctx); 615 if (!isValidFunctionSymbol(Init.Symbol)) 616 return make_error<GenericBinaryError>("invalid function symbol: " + 617 Twine(Init.Symbol), 618 object_error::parse_failed); 619 LinkingData.InitFunctions.emplace_back(Init); 620 } 621 break; 622 } 623 case wasm::WASM_COMDAT_INFO: 624 if (Error Err = parseLinkingSectionComdat(Ctx)) 625 return Err; 626 break; 627 default: 628 Ctx.Ptr += Size; 629 break; 630 } 631 if (Ctx.Ptr != Ctx.End) 632 return make_error<GenericBinaryError>( 633 "linking sub-section ended prematurely", object_error::parse_failed); 634 } 635 if (Ctx.Ptr != OrigEnd) 636 return make_error<GenericBinaryError>("linking section ended prematurely", 637 object_error::parse_failed); 638 return Error::success(); 639 } 640 641 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) { 642 uint32_t Count = readVaruint32(Ctx); 643 // Clear out any symbol information that was derived from the exports 644 // section. 645 Symbols.clear(); 646 Symbols.reserve(Count); 647 StringSet<> SymbolNames; 648 649 std::vector<wasm::WasmImport *> ImportedGlobals; 650 std::vector<wasm::WasmImport *> ImportedFunctions; 651 std::vector<wasm::WasmImport *> ImportedTags; 652 std::vector<wasm::WasmImport *> ImportedTables; 653 ImportedGlobals.reserve(Imports.size()); 654 ImportedFunctions.reserve(Imports.size()); 655 ImportedTags.reserve(Imports.size()); 656 ImportedTables.reserve(Imports.size()); 657 for (auto &I : Imports) { 658 if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION) 659 ImportedFunctions.emplace_back(&I); 660 else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL) 661 ImportedGlobals.emplace_back(&I); 662 else if (I.Kind == wasm::WASM_EXTERNAL_TAG) 663 ImportedTags.emplace_back(&I); 664 else if (I.Kind == wasm::WASM_EXTERNAL_TABLE) 665 ImportedTables.emplace_back(&I); 666 } 667 668 while (Count--) { 669 wasm::WasmSymbolInfo Info; 670 const wasm::WasmSignature *Signature = nullptr; 671 const wasm::WasmGlobalType *GlobalType = nullptr; 672 const wasm::WasmTableType *TableType = nullptr; 673 674 Info.Kind = readUint8(Ctx); 675 Info.Flags = readVaruint32(Ctx); 676 bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0; 677 678 switch (Info.Kind) { 679 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 680 Info.ElementIndex = readVaruint32(Ctx); 681 if (!isValidFunctionIndex(Info.ElementIndex) || 682 IsDefined != isDefinedFunctionIndex(Info.ElementIndex)) 683 return make_error<GenericBinaryError>("invalid function symbol index", 684 object_error::parse_failed); 685 if (IsDefined) { 686 Info.Name = readString(Ctx); 687 unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions; 688 wasm::WasmFunction &Function = Functions[FuncIndex]; 689 Signature = &Signatures[Function.SigIndex]; 690 if (Function.SymbolName.empty()) 691 Function.SymbolName = Info.Name; 692 } else { 693 wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex]; 694 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 695 Info.Name = readString(Ctx); 696 Info.ImportName = Import.Field; 697 } else { 698 Info.Name = Import.Field; 699 } 700 Signature = &Signatures[Import.SigIndex]; 701 Info.ImportModule = Import.Module; 702 } 703 break; 704 705 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 706 Info.ElementIndex = readVaruint32(Ctx); 707 if (!isValidGlobalIndex(Info.ElementIndex) || 708 IsDefined != isDefinedGlobalIndex(Info.ElementIndex)) 709 return make_error<GenericBinaryError>("invalid global symbol index", 710 object_error::parse_failed); 711 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 712 wasm::WASM_SYMBOL_BINDING_WEAK) 713 return make_error<GenericBinaryError>("undefined weak global symbol", 714 object_error::parse_failed); 715 if (IsDefined) { 716 Info.Name = readString(Ctx); 717 unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals; 718 wasm::WasmGlobal &Global = Globals[GlobalIndex]; 719 GlobalType = &Global.Type; 720 if (Global.SymbolName.empty()) 721 Global.SymbolName = Info.Name; 722 } else { 723 wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex]; 724 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 725 Info.Name = readString(Ctx); 726 Info.ImportName = Import.Field; 727 } else { 728 Info.Name = Import.Field; 729 } 730 GlobalType = &Import.Global; 731 Info.ImportModule = Import.Module; 732 } 733 break; 734 735 case wasm::WASM_SYMBOL_TYPE_TABLE: 736 Info.ElementIndex = readVaruint32(Ctx); 737 if (!isValidTableNumber(Info.ElementIndex) || 738 IsDefined != isDefinedTableNumber(Info.ElementIndex)) 739 return make_error<GenericBinaryError>("invalid table symbol index", 740 object_error::parse_failed); 741 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 742 wasm::WASM_SYMBOL_BINDING_WEAK) 743 return make_error<GenericBinaryError>("undefined weak table symbol", 744 object_error::parse_failed); 745 if (IsDefined) { 746 Info.Name = readString(Ctx); 747 unsigned TableNumber = Info.ElementIndex - NumImportedTables; 748 wasm::WasmTable &Table = Tables[TableNumber]; 749 TableType = &Table.Type; 750 if (Table.SymbolName.empty()) 751 Table.SymbolName = Info.Name; 752 } else { 753 wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex]; 754 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 755 Info.Name = readString(Ctx); 756 Info.ImportName = Import.Field; 757 } else { 758 Info.Name = Import.Field; 759 } 760 TableType = &Import.Table; 761 Info.ImportModule = Import.Module; 762 } 763 break; 764 765 case wasm::WASM_SYMBOL_TYPE_DATA: 766 Info.Name = readString(Ctx); 767 if (IsDefined) { 768 auto Index = readVaruint32(Ctx); 769 auto Offset = readVaruint64(Ctx); 770 auto Size = readVaruint64(Ctx); 771 if (!(Info.Flags & wasm::WASM_SYMBOL_ABSOLUTE)) { 772 if (static_cast<size_t>(Index) >= DataSegments.size()) 773 return make_error<GenericBinaryError>( 774 "invalid data segment index: " + Twine(Index), 775 object_error::parse_failed); 776 size_t SegmentSize = DataSegments[Index].Data.Content.size(); 777 if (Offset > SegmentSize) 778 return make_error<GenericBinaryError>( 779 "invalid data symbol offset: `" + Info.Name + 780 "` (offset: " + Twine(Offset) + 781 " segment size: " + Twine(SegmentSize) + ")", 782 object_error::parse_failed); 783 } 784 Info.DataRef = wasm::WasmDataReference{Index, Offset, Size}; 785 } 786 break; 787 788 case wasm::WASM_SYMBOL_TYPE_SECTION: { 789 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) != 790 wasm::WASM_SYMBOL_BINDING_LOCAL) 791 return make_error<GenericBinaryError>( 792 "section symbols must have local binding", 793 object_error::parse_failed); 794 Info.ElementIndex = readVaruint32(Ctx); 795 // Use somewhat unique section name as symbol name. 796 StringRef SectionName = Sections[Info.ElementIndex].Name; 797 Info.Name = SectionName; 798 break; 799 } 800 801 case wasm::WASM_SYMBOL_TYPE_TAG: { 802 Info.ElementIndex = readVaruint32(Ctx); 803 if (!isValidTagIndex(Info.ElementIndex) || 804 IsDefined != isDefinedTagIndex(Info.ElementIndex)) 805 return make_error<GenericBinaryError>("invalid tag symbol index", 806 object_error::parse_failed); 807 if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) == 808 wasm::WASM_SYMBOL_BINDING_WEAK) 809 return make_error<GenericBinaryError>("undefined weak global symbol", 810 object_error::parse_failed); 811 if (IsDefined) { 812 Info.Name = readString(Ctx); 813 unsigned TagIndex = Info.ElementIndex - NumImportedTags; 814 wasm::WasmTag &Tag = Tags[TagIndex]; 815 Signature = &Signatures[Tag.SigIndex]; 816 if (Tag.SymbolName.empty()) 817 Tag.SymbolName = Info.Name; 818 819 } else { 820 wasm::WasmImport &Import = *ImportedTags[Info.ElementIndex]; 821 if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) { 822 Info.Name = readString(Ctx); 823 Info.ImportName = Import.Field; 824 } else { 825 Info.Name = Import.Field; 826 } 827 Signature = &Signatures[Import.SigIndex]; 828 Info.ImportModule = Import.Module; 829 } 830 break; 831 } 832 833 default: 834 return make_error<GenericBinaryError>("invalid symbol type: " + 835 Twine(unsigned(Info.Kind)), 836 object_error::parse_failed); 837 } 838 839 if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) != 840 wasm::WASM_SYMBOL_BINDING_LOCAL && 841 !SymbolNames.insert(Info.Name).second) 842 return make_error<GenericBinaryError>("duplicate symbol name " + 843 Twine(Info.Name), 844 object_error::parse_failed); 845 Symbols.emplace_back(Info, GlobalType, TableType, Signature); 846 LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n"); 847 } 848 849 return Error::success(); 850 } 851 852 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) { 853 uint32_t ComdatCount = readVaruint32(Ctx); 854 StringSet<> ComdatSet; 855 for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) { 856 StringRef Name = readString(Ctx); 857 if (Name.empty() || !ComdatSet.insert(Name).second) 858 return make_error<GenericBinaryError>("bad/duplicate COMDAT name " + 859 Twine(Name), 860 object_error::parse_failed); 861 LinkingData.Comdats.emplace_back(Name); 862 uint32_t Flags = readVaruint32(Ctx); 863 if (Flags != 0) 864 return make_error<GenericBinaryError>("unsupported COMDAT flags", 865 object_error::parse_failed); 866 867 uint32_t EntryCount = readVaruint32(Ctx); 868 while (EntryCount--) { 869 unsigned Kind = readVaruint32(Ctx); 870 unsigned Index = readVaruint32(Ctx); 871 switch (Kind) { 872 default: 873 return make_error<GenericBinaryError>("invalid COMDAT entry type", 874 object_error::parse_failed); 875 case wasm::WASM_COMDAT_DATA: 876 if (Index >= DataSegments.size()) 877 return make_error<GenericBinaryError>( 878 "COMDAT data index out of range", object_error::parse_failed); 879 if (DataSegments[Index].Data.Comdat != UINT32_MAX) 880 return make_error<GenericBinaryError>("data segment in two COMDATs", 881 object_error::parse_failed); 882 DataSegments[Index].Data.Comdat = ComdatIndex; 883 break; 884 case wasm::WASM_COMDAT_FUNCTION: 885 if (!isDefinedFunctionIndex(Index)) 886 return make_error<GenericBinaryError>( 887 "COMDAT function index out of range", object_error::parse_failed); 888 if (getDefinedFunction(Index).Comdat != UINT32_MAX) 889 return make_error<GenericBinaryError>("function in two COMDATs", 890 object_error::parse_failed); 891 getDefinedFunction(Index).Comdat = ComdatIndex; 892 break; 893 case wasm::WASM_COMDAT_SECTION: 894 if (Index >= Sections.size()) 895 return make_error<GenericBinaryError>( 896 "COMDAT section index out of range", object_error::parse_failed); 897 if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM) 898 return make_error<GenericBinaryError>( 899 "non-custom section in a COMDAT", object_error::parse_failed); 900 Sections[Index].Comdat = ComdatIndex; 901 break; 902 } 903 } 904 } 905 return Error::success(); 906 } 907 908 Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) { 909 llvm::SmallSet<StringRef, 3> FieldsSeen; 910 uint32_t Fields = readVaruint32(Ctx); 911 for (size_t I = 0; I < Fields; ++I) { 912 StringRef FieldName = readString(Ctx); 913 if (!FieldsSeen.insert(FieldName).second) 914 return make_error<GenericBinaryError>( 915 "producers section does not have unique fields", 916 object_error::parse_failed); 917 std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr; 918 if (FieldName == "language") { 919 ProducerVec = &ProducerInfo.Languages; 920 } else if (FieldName == "processed-by") { 921 ProducerVec = &ProducerInfo.Tools; 922 } else if (FieldName == "sdk") { 923 ProducerVec = &ProducerInfo.SDKs; 924 } else { 925 return make_error<GenericBinaryError>( 926 "producers section field is not named one of language, processed-by, " 927 "or sdk", 928 object_error::parse_failed); 929 } 930 uint32_t ValueCount = readVaruint32(Ctx); 931 llvm::SmallSet<StringRef, 8> ProducersSeen; 932 for (size_t J = 0; J < ValueCount; ++J) { 933 StringRef Name = readString(Ctx); 934 StringRef Version = readString(Ctx); 935 if (!ProducersSeen.insert(Name).second) { 936 return make_error<GenericBinaryError>( 937 "producers section contains repeated producer", 938 object_error::parse_failed); 939 } 940 ProducerVec->emplace_back(std::string(Name), std::string(Version)); 941 } 942 } 943 if (Ctx.Ptr != Ctx.End) 944 return make_error<GenericBinaryError>("producers section ended prematurely", 945 object_error::parse_failed); 946 return Error::success(); 947 } 948 949 Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) { 950 llvm::SmallSet<std::string, 8> FeaturesSeen; 951 uint32_t FeatureCount = readVaruint32(Ctx); 952 for (size_t I = 0; I < FeatureCount; ++I) { 953 wasm::WasmFeatureEntry Feature; 954 Feature.Prefix = readUint8(Ctx); 955 switch (Feature.Prefix) { 956 case wasm::WASM_FEATURE_PREFIX_USED: 957 case wasm::WASM_FEATURE_PREFIX_REQUIRED: 958 case wasm::WASM_FEATURE_PREFIX_DISALLOWED: 959 break; 960 default: 961 return make_error<GenericBinaryError>("unknown feature policy prefix", 962 object_error::parse_failed); 963 } 964 Feature.Name = std::string(readString(Ctx)); 965 if (!FeaturesSeen.insert(Feature.Name).second) 966 return make_error<GenericBinaryError>( 967 "target features section contains repeated feature \"" + 968 Feature.Name + "\"", 969 object_error::parse_failed); 970 TargetFeatures.push_back(Feature); 971 } 972 if (Ctx.Ptr != Ctx.End) 973 return make_error<GenericBinaryError>( 974 "target features section ended prematurely", 975 object_error::parse_failed); 976 return Error::success(); 977 } 978 979 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) { 980 uint32_t SectionIndex = readVaruint32(Ctx); 981 if (SectionIndex >= Sections.size()) 982 return make_error<GenericBinaryError>("invalid section index", 983 object_error::parse_failed); 984 WasmSection &Section = Sections[SectionIndex]; 985 uint32_t RelocCount = readVaruint32(Ctx); 986 uint32_t EndOffset = Section.Content.size(); 987 uint32_t PreviousOffset = 0; 988 while (RelocCount--) { 989 wasm::WasmRelocation Reloc = {}; 990 uint32_t type = readVaruint32(Ctx); 991 Reloc.Type = type; 992 Reloc.Offset = readVaruint32(Ctx); 993 if (Reloc.Offset < PreviousOffset) 994 return make_error<GenericBinaryError>("relocations not in offset order", 995 object_error::parse_failed); 996 PreviousOffset = Reloc.Offset; 997 Reloc.Index = readVaruint32(Ctx); 998 switch (type) { 999 case wasm::R_WASM_FUNCTION_INDEX_LEB: 1000 case wasm::R_WASM_FUNCTION_INDEX_I32: 1001 case wasm::R_WASM_TABLE_INDEX_SLEB: 1002 case wasm::R_WASM_TABLE_INDEX_SLEB64: 1003 case wasm::R_WASM_TABLE_INDEX_I32: 1004 case wasm::R_WASM_TABLE_INDEX_I64: 1005 case wasm::R_WASM_TABLE_INDEX_REL_SLEB: 1006 case wasm::R_WASM_TABLE_INDEX_REL_SLEB64: 1007 if (!isValidFunctionSymbol(Reloc.Index)) 1008 return make_error<GenericBinaryError>( 1009 "invalid relocation function index", object_error::parse_failed); 1010 break; 1011 case wasm::R_WASM_TABLE_NUMBER_LEB: 1012 if (!isValidTableSymbol(Reloc.Index)) 1013 return make_error<GenericBinaryError>("invalid relocation table index", 1014 object_error::parse_failed); 1015 break; 1016 case wasm::R_WASM_TYPE_INDEX_LEB: 1017 if (Reloc.Index >= Signatures.size()) 1018 return make_error<GenericBinaryError>("invalid relocation type index", 1019 object_error::parse_failed); 1020 break; 1021 case wasm::R_WASM_GLOBAL_INDEX_LEB: 1022 // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data 1023 // symbols to refer to their GOT entries. 1024 if (!isValidGlobalSymbol(Reloc.Index) && 1025 !isValidDataSymbol(Reloc.Index) && 1026 !isValidFunctionSymbol(Reloc.Index)) 1027 return make_error<GenericBinaryError>("invalid relocation global index", 1028 object_error::parse_failed); 1029 break; 1030 case wasm::R_WASM_GLOBAL_INDEX_I32: 1031 if (!isValidGlobalSymbol(Reloc.Index)) 1032 return make_error<GenericBinaryError>("invalid relocation global index", 1033 object_error::parse_failed); 1034 break; 1035 case wasm::R_WASM_TAG_INDEX_LEB: 1036 if (!isValidTagSymbol(Reloc.Index)) 1037 return make_error<GenericBinaryError>("invalid relocation tag index", 1038 object_error::parse_failed); 1039 break; 1040 case wasm::R_WASM_MEMORY_ADDR_LEB: 1041 case wasm::R_WASM_MEMORY_ADDR_SLEB: 1042 case wasm::R_WASM_MEMORY_ADDR_I32: 1043 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB: 1044 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB: 1045 case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: 1046 if (!isValidDataSymbol(Reloc.Index)) 1047 return make_error<GenericBinaryError>("invalid relocation data index", 1048 object_error::parse_failed); 1049 Reloc.Addend = readVarint32(Ctx); 1050 break; 1051 case wasm::R_WASM_MEMORY_ADDR_LEB64: 1052 case wasm::R_WASM_MEMORY_ADDR_SLEB64: 1053 case wasm::R_WASM_MEMORY_ADDR_I64: 1054 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64: 1055 case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64: 1056 if (!isValidDataSymbol(Reloc.Index)) 1057 return make_error<GenericBinaryError>("invalid relocation data index", 1058 object_error::parse_failed); 1059 Reloc.Addend = readVarint64(Ctx); 1060 break; 1061 case wasm::R_WASM_FUNCTION_OFFSET_I32: 1062 if (!isValidFunctionSymbol(Reloc.Index)) 1063 return make_error<GenericBinaryError>( 1064 "invalid relocation function index", object_error::parse_failed); 1065 Reloc.Addend = readVarint32(Ctx); 1066 break; 1067 case wasm::R_WASM_FUNCTION_OFFSET_I64: 1068 if (!isValidFunctionSymbol(Reloc.Index)) 1069 return make_error<GenericBinaryError>( 1070 "invalid relocation function index", object_error::parse_failed); 1071 Reloc.Addend = readVarint64(Ctx); 1072 break; 1073 case wasm::R_WASM_SECTION_OFFSET_I32: 1074 if (!isValidSectionSymbol(Reloc.Index)) 1075 return make_error<GenericBinaryError>( 1076 "invalid relocation section index", object_error::parse_failed); 1077 Reloc.Addend = readVarint32(Ctx); 1078 break; 1079 default: 1080 return make_error<GenericBinaryError>("invalid relocation type: " + 1081 Twine(type), 1082 object_error::parse_failed); 1083 } 1084 1085 // Relocations must fit inside the section, and must appear in order. They 1086 // also shouldn't overlap a function/element boundary, but we don't bother 1087 // to check that. 1088 uint64_t Size = 5; 1089 if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 || 1090 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 || 1091 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64) 1092 Size = 10; 1093 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 || 1094 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 || 1095 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LOCREL_I32 || 1096 Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 || 1097 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 || 1098 Reloc.Type == wasm::R_WASM_FUNCTION_INDEX_I32 || 1099 Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32) 1100 Size = 4; 1101 if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 || 1102 Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 || 1103 Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64) 1104 Size = 8; 1105 if (Reloc.Offset + Size > EndOffset) 1106 return make_error<GenericBinaryError>("invalid relocation offset", 1107 object_error::parse_failed); 1108 1109 Section.Relocations.push_back(Reloc); 1110 } 1111 if (Ctx.Ptr != Ctx.End) 1112 return make_error<GenericBinaryError>("reloc section ended prematurely", 1113 object_error::parse_failed); 1114 return Error::success(); 1115 } 1116 1117 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) { 1118 if (Sec.Name == "dylink") { 1119 if (Error Err = parseDylinkSection(Ctx)) 1120 return Err; 1121 } else if (Sec.Name == "dylink.0") { 1122 if (Error Err = parseDylink0Section(Ctx)) 1123 return Err; 1124 } else if (Sec.Name == "name") { 1125 if (Error Err = parseNameSection(Ctx)) 1126 return Err; 1127 } else if (Sec.Name == "linking") { 1128 if (Error Err = parseLinkingSection(Ctx)) 1129 return Err; 1130 } else if (Sec.Name == "producers") { 1131 if (Error Err = parseProducersSection(Ctx)) 1132 return Err; 1133 } else if (Sec.Name == "target_features") { 1134 if (Error Err = parseTargetFeaturesSection(Ctx)) 1135 return Err; 1136 } else if (Sec.Name.starts_with("reloc.")) { 1137 if (Error Err = parseRelocSection(Sec.Name, Ctx)) 1138 return Err; 1139 } 1140 return Error::success(); 1141 } 1142 1143 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) { 1144 auto parseFieldDef = [&]() { 1145 uint32_t TypeCode = readVaruint32((Ctx)); 1146 /* Discard StorageType */ parseValType(Ctx, TypeCode); 1147 /* Discard Mutability */ readVaruint32(Ctx); 1148 }; 1149 1150 uint32_t Count = readVaruint32(Ctx); 1151 Signatures.reserve(Count); 1152 while (Count--) { 1153 wasm::WasmSignature Sig; 1154 uint8_t Form = readUint8(Ctx); 1155 if (Form == wasm::WASM_TYPE_REC) { 1156 // Rec groups expand the type index space (beyond what was declared at 1157 // the top of the section, and also consume one element in that space. 1158 uint32_t RecSize = readVaruint32(Ctx); 1159 if (RecSize == 0) 1160 return make_error<GenericBinaryError>("Rec group size cannot be 0", 1161 object_error::parse_failed); 1162 Signatures.reserve(Signatures.size() + RecSize); 1163 Count += RecSize; 1164 Sig.Kind = wasm::WasmSignature::Placeholder; 1165 Signatures.push_back(std::move(Sig)); 1166 HasUnmodeledTypes = true; 1167 continue; 1168 } 1169 if (Form != wasm::WASM_TYPE_FUNC) { 1170 // Currently LLVM only models function types, and not other composite 1171 // types. Here we parse the type declarations just enough to skip past 1172 // them in the binary. 1173 if (Form == wasm::WASM_TYPE_SUB || Form == wasm::WASM_TYPE_SUB_FINAL) { 1174 uint32_t Supers = readVaruint32(Ctx); 1175 if (Supers > 0) { 1176 if (Supers != 1) 1177 return make_error<GenericBinaryError>( 1178 "Invalid number of supertypes", object_error::parse_failed); 1179 /* Discard SuperIndex */ readVaruint32(Ctx); 1180 } 1181 Form = readVaruint32(Ctx); 1182 } 1183 if (Form == wasm::WASM_TYPE_STRUCT) { 1184 uint32_t FieldCount = readVaruint32(Ctx); 1185 while (FieldCount--) { 1186 parseFieldDef(); 1187 } 1188 } else if (Form == wasm::WASM_TYPE_ARRAY) { 1189 parseFieldDef(); 1190 } else { 1191 return make_error<GenericBinaryError>("bad form", 1192 object_error::parse_failed); 1193 } 1194 Sig.Kind = wasm::WasmSignature::Placeholder; 1195 Signatures.push_back(std::move(Sig)); 1196 HasUnmodeledTypes = true; 1197 continue; 1198 } 1199 1200 uint32_t ParamCount = readVaruint32(Ctx); 1201 Sig.Params.reserve(ParamCount); 1202 while (ParamCount--) { 1203 uint32_t ParamType = readUint8(Ctx); 1204 Sig.Params.push_back(parseValType(Ctx, ParamType)); 1205 continue; 1206 } 1207 uint32_t ReturnCount = readVaruint32(Ctx); 1208 while (ReturnCount--) { 1209 uint32_t ReturnType = readUint8(Ctx); 1210 Sig.Returns.push_back(parseValType(Ctx, ReturnType)); 1211 } 1212 1213 Signatures.push_back(std::move(Sig)); 1214 } 1215 if (Ctx.Ptr != Ctx.End) 1216 return make_error<GenericBinaryError>("type section ended prematurely", 1217 object_error::parse_failed); 1218 return Error::success(); 1219 } 1220 1221 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) { 1222 uint32_t Count = readVaruint32(Ctx); 1223 uint32_t NumTypes = Signatures.size(); 1224 Imports.reserve(Count); 1225 for (uint32_t I = 0; I < Count; I++) { 1226 wasm::WasmImport Im; 1227 Im.Module = readString(Ctx); 1228 Im.Field = readString(Ctx); 1229 Im.Kind = readUint8(Ctx); 1230 switch (Im.Kind) { 1231 case wasm::WASM_EXTERNAL_FUNCTION: 1232 NumImportedFunctions++; 1233 Im.SigIndex = readVaruint32(Ctx); 1234 if (Im.SigIndex >= NumTypes) 1235 return make_error<GenericBinaryError>("invalid function type", 1236 object_error::parse_failed); 1237 break; 1238 case wasm::WASM_EXTERNAL_GLOBAL: 1239 NumImportedGlobals++; 1240 Im.Global.Type = readUint8(Ctx); 1241 Im.Global.Mutable = readVaruint1(Ctx); 1242 break; 1243 case wasm::WASM_EXTERNAL_MEMORY: 1244 Im.Memory = readLimits(Ctx); 1245 if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1246 HasMemory64 = true; 1247 break; 1248 case wasm::WASM_EXTERNAL_TABLE: { 1249 Im.Table = readTableType(Ctx); 1250 NumImportedTables++; 1251 auto ElemType = Im.Table.ElemType; 1252 if (ElemType != wasm::ValType::FUNCREF && 1253 ElemType != wasm::ValType::EXTERNREF && 1254 ElemType != wasm::ValType::OTHERREF) 1255 return make_error<GenericBinaryError>("invalid table element type", 1256 object_error::parse_failed); 1257 break; 1258 } 1259 case wasm::WASM_EXTERNAL_TAG: 1260 NumImportedTags++; 1261 if (readUint8(Ctx) != 0) // Reserved 'attribute' field 1262 return make_error<GenericBinaryError>("invalid attribute", 1263 object_error::parse_failed); 1264 Im.SigIndex = readVaruint32(Ctx); 1265 if (Im.SigIndex >= NumTypes) 1266 return make_error<GenericBinaryError>("invalid tag type", 1267 object_error::parse_failed); 1268 break; 1269 default: 1270 return make_error<GenericBinaryError>("unexpected import kind", 1271 object_error::parse_failed); 1272 } 1273 Imports.push_back(Im); 1274 } 1275 if (Ctx.Ptr != Ctx.End) 1276 return make_error<GenericBinaryError>("import section ended prematurely", 1277 object_error::parse_failed); 1278 return Error::success(); 1279 } 1280 1281 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) { 1282 uint32_t Count = readVaruint32(Ctx); 1283 Functions.reserve(Count); 1284 uint32_t NumTypes = Signatures.size(); 1285 while (Count--) { 1286 uint32_t Type = readVaruint32(Ctx); 1287 if (Type >= NumTypes) 1288 return make_error<GenericBinaryError>("invalid function type", 1289 object_error::parse_failed); 1290 wasm::WasmFunction F; 1291 F.SigIndex = Type; 1292 Functions.push_back(F); 1293 } 1294 if (Ctx.Ptr != Ctx.End) 1295 return make_error<GenericBinaryError>("function section ended prematurely", 1296 object_error::parse_failed); 1297 return Error::success(); 1298 } 1299 1300 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) { 1301 TableSection = Sections.size(); 1302 uint32_t Count = readVaruint32(Ctx); 1303 Tables.reserve(Count); 1304 while (Count--) { 1305 wasm::WasmTable T; 1306 T.Type = readTableType(Ctx); 1307 T.Index = NumImportedTables + Tables.size(); 1308 Tables.push_back(T); 1309 auto ElemType = Tables.back().Type.ElemType; 1310 if (ElemType != wasm::ValType::FUNCREF && 1311 ElemType != wasm::ValType::EXTERNREF && 1312 ElemType != wasm::ValType::OTHERREF) { 1313 return make_error<GenericBinaryError>("invalid table element type", 1314 object_error::parse_failed); 1315 } 1316 } 1317 if (Ctx.Ptr != Ctx.End) 1318 return make_error<GenericBinaryError>("table section ended prematurely", 1319 object_error::parse_failed); 1320 return Error::success(); 1321 } 1322 1323 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) { 1324 uint32_t Count = readVaruint32(Ctx); 1325 Memories.reserve(Count); 1326 while (Count--) { 1327 auto Limits = readLimits(Ctx); 1328 if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64) 1329 HasMemory64 = true; 1330 Memories.push_back(Limits); 1331 } 1332 if (Ctx.Ptr != Ctx.End) 1333 return make_error<GenericBinaryError>("memory section ended prematurely", 1334 object_error::parse_failed); 1335 return Error::success(); 1336 } 1337 1338 Error WasmObjectFile::parseTagSection(ReadContext &Ctx) { 1339 TagSection = Sections.size(); 1340 uint32_t Count = readVaruint32(Ctx); 1341 Tags.reserve(Count); 1342 uint32_t NumTypes = Signatures.size(); 1343 while (Count--) { 1344 if (readUint8(Ctx) != 0) // Reserved 'attribute' field 1345 return make_error<GenericBinaryError>("invalid attribute", 1346 object_error::parse_failed); 1347 uint32_t Type = readVaruint32(Ctx); 1348 if (Type >= NumTypes) 1349 return make_error<GenericBinaryError>("invalid tag type", 1350 object_error::parse_failed); 1351 wasm::WasmTag Tag; 1352 Tag.Index = NumImportedTags + Tags.size(); 1353 Tag.SigIndex = Type; 1354 Signatures[Type].Kind = wasm::WasmSignature::Tag; 1355 Tags.push_back(Tag); 1356 } 1357 1358 if (Ctx.Ptr != Ctx.End) 1359 return make_error<GenericBinaryError>("tag section ended prematurely", 1360 object_error::parse_failed); 1361 return Error::success(); 1362 } 1363 1364 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) { 1365 GlobalSection = Sections.size(); 1366 uint32_t Count = readVaruint32(Ctx); 1367 Globals.reserve(Count); 1368 while (Count--) { 1369 wasm::WasmGlobal Global; 1370 Global.Index = NumImportedGlobals + Globals.size(); 1371 auto GlobalOpcode = readVaruint32(Ctx); 1372 auto GlobalType = parseValType(Ctx, GlobalOpcode); 1373 // assert(GlobalType <= std::numeric_limits<wasm::ValType>::max()); 1374 Global.Type.Type = (uint8_t)GlobalType; 1375 Global.Type.Mutable = readVaruint1(Ctx); 1376 if (Error Err = readInitExpr(Global.InitExpr, Ctx)) 1377 return Err; 1378 Globals.push_back(Global); 1379 } 1380 if (Ctx.Ptr != Ctx.End) 1381 return make_error<GenericBinaryError>("global section ended prematurely", 1382 object_error::parse_failed); 1383 return Error::success(); 1384 } 1385 1386 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) { 1387 uint32_t Count = readVaruint32(Ctx); 1388 Exports.reserve(Count); 1389 Symbols.reserve(Count); 1390 for (uint32_t I = 0; I < Count; I++) { 1391 wasm::WasmExport Ex; 1392 Ex.Name = readString(Ctx); 1393 Ex.Kind = readUint8(Ctx); 1394 Ex.Index = readVaruint32(Ctx); 1395 const wasm::WasmSignature *Signature = nullptr; 1396 const wasm::WasmGlobalType *GlobalType = nullptr; 1397 const wasm::WasmTableType *TableType = nullptr; 1398 wasm::WasmSymbolInfo Info; 1399 Info.Name = Ex.Name; 1400 Info.Flags = 0; 1401 switch (Ex.Kind) { 1402 case wasm::WASM_EXTERNAL_FUNCTION: { 1403 if (!isDefinedFunctionIndex(Ex.Index)) 1404 return make_error<GenericBinaryError>("invalid function export", 1405 object_error::parse_failed); 1406 getDefinedFunction(Ex.Index).ExportName = Ex.Name; 1407 Info.Kind = wasm::WASM_SYMBOL_TYPE_FUNCTION; 1408 Info.ElementIndex = Ex.Index; 1409 unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions; 1410 wasm::WasmFunction &Function = Functions[FuncIndex]; 1411 Signature = &Signatures[Function.SigIndex]; 1412 break; 1413 } 1414 case wasm::WASM_EXTERNAL_GLOBAL: { 1415 if (!isValidGlobalIndex(Ex.Index)) 1416 return make_error<GenericBinaryError>("invalid global export", 1417 object_error::parse_failed); 1418 Info.Kind = wasm::WASM_SYMBOL_TYPE_DATA; 1419 uint64_t Offset = 0; 1420 if (isDefinedGlobalIndex(Ex.Index)) { 1421 auto Global = getDefinedGlobal(Ex.Index); 1422 if (!Global.InitExpr.Extended) { 1423 auto Inst = Global.InitExpr.Inst; 1424 if (Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) { 1425 Offset = Inst.Value.Int32; 1426 } else if (Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) { 1427 Offset = Inst.Value.Int64; 1428 } 1429 } 1430 } 1431 Info.DataRef = wasm::WasmDataReference{0, Offset, 0}; 1432 break; 1433 } 1434 case wasm::WASM_EXTERNAL_TAG: 1435 if (!isValidTagIndex(Ex.Index)) 1436 return make_error<GenericBinaryError>("invalid tag export", 1437 object_error::parse_failed); 1438 Info.Kind = wasm::WASM_SYMBOL_TYPE_TAG; 1439 Info.ElementIndex = Ex.Index; 1440 break; 1441 case wasm::WASM_EXTERNAL_MEMORY: 1442 break; 1443 case wasm::WASM_EXTERNAL_TABLE: 1444 Info.Kind = wasm::WASM_SYMBOL_TYPE_TABLE; 1445 Info.ElementIndex = Ex.Index; 1446 break; 1447 default: 1448 return make_error<GenericBinaryError>("unexpected export kind", 1449 object_error::parse_failed); 1450 } 1451 Exports.push_back(Ex); 1452 if (Ex.Kind != wasm::WASM_EXTERNAL_MEMORY) { 1453 Symbols.emplace_back(Info, GlobalType, TableType, Signature); 1454 LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n"); 1455 } 1456 } 1457 if (Ctx.Ptr != Ctx.End) 1458 return make_error<GenericBinaryError>("export section ended prematurely", 1459 object_error::parse_failed); 1460 return Error::success(); 1461 } 1462 1463 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const { 1464 return Index < NumImportedFunctions + Functions.size(); 1465 } 1466 1467 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const { 1468 return Index >= NumImportedFunctions && isValidFunctionIndex(Index); 1469 } 1470 1471 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const { 1472 return Index < NumImportedGlobals + Globals.size(); 1473 } 1474 1475 bool WasmObjectFile::isValidTableNumber(uint32_t Index) const { 1476 return Index < NumImportedTables + Tables.size(); 1477 } 1478 1479 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const { 1480 return Index >= NumImportedGlobals && isValidGlobalIndex(Index); 1481 } 1482 1483 bool WasmObjectFile::isDefinedTableNumber(uint32_t Index) const { 1484 return Index >= NumImportedTables && isValidTableNumber(Index); 1485 } 1486 1487 bool WasmObjectFile::isValidTagIndex(uint32_t Index) const { 1488 return Index < NumImportedTags + Tags.size(); 1489 } 1490 1491 bool WasmObjectFile::isDefinedTagIndex(uint32_t Index) const { 1492 return Index >= NumImportedTags && isValidTagIndex(Index); 1493 } 1494 1495 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const { 1496 return Index < Symbols.size() && Symbols[Index].isTypeFunction(); 1497 } 1498 1499 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const { 1500 return Index < Symbols.size() && Symbols[Index].isTypeTable(); 1501 } 1502 1503 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const { 1504 return Index < Symbols.size() && Symbols[Index].isTypeGlobal(); 1505 } 1506 1507 bool WasmObjectFile::isValidTagSymbol(uint32_t Index) const { 1508 return Index < Symbols.size() && Symbols[Index].isTypeTag(); 1509 } 1510 1511 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const { 1512 return Index < Symbols.size() && Symbols[Index].isTypeData(); 1513 } 1514 1515 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const { 1516 return Index < Symbols.size() && Symbols[Index].isTypeSection(); 1517 } 1518 1519 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) { 1520 assert(isDefinedFunctionIndex(Index)); 1521 return Functions[Index - NumImportedFunctions]; 1522 } 1523 1524 const wasm::WasmFunction & 1525 WasmObjectFile::getDefinedFunction(uint32_t Index) const { 1526 assert(isDefinedFunctionIndex(Index)); 1527 return Functions[Index - NumImportedFunctions]; 1528 } 1529 1530 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) { 1531 assert(isDefinedGlobalIndex(Index)); 1532 return Globals[Index - NumImportedGlobals]; 1533 } 1534 1535 wasm::WasmTag &WasmObjectFile::getDefinedTag(uint32_t Index) { 1536 assert(isDefinedTagIndex(Index)); 1537 return Tags[Index - NumImportedTags]; 1538 } 1539 1540 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) { 1541 StartFunction = readVaruint32(Ctx); 1542 if (!isValidFunctionIndex(StartFunction)) 1543 return make_error<GenericBinaryError>("invalid start function", 1544 object_error::parse_failed); 1545 return Error::success(); 1546 } 1547 1548 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) { 1549 CodeSection = Sections.size(); 1550 uint32_t FunctionCount = readVaruint32(Ctx); 1551 if (FunctionCount != Functions.size()) { 1552 return make_error<GenericBinaryError>("invalid function count", 1553 object_error::parse_failed); 1554 } 1555 1556 for (uint32_t i = 0; i < FunctionCount; i++) { 1557 wasm::WasmFunction& Function = Functions[i]; 1558 const uint8_t *FunctionStart = Ctx.Ptr; 1559 uint32_t Size = readVaruint32(Ctx); 1560 const uint8_t *FunctionEnd = Ctx.Ptr + Size; 1561 1562 Function.CodeOffset = Ctx.Ptr - FunctionStart; 1563 Function.Index = NumImportedFunctions + i; 1564 Function.CodeSectionOffset = FunctionStart - Ctx.Start; 1565 Function.Size = FunctionEnd - FunctionStart; 1566 1567 uint32_t NumLocalDecls = readVaruint32(Ctx); 1568 Function.Locals.reserve(NumLocalDecls); 1569 while (NumLocalDecls--) { 1570 wasm::WasmLocalDecl Decl; 1571 Decl.Count = readVaruint32(Ctx); 1572 Decl.Type = readUint8(Ctx); 1573 Function.Locals.push_back(Decl); 1574 } 1575 1576 uint32_t BodySize = FunctionEnd - Ctx.Ptr; 1577 // Ensure that Function is within Ctx's buffer. 1578 if (Ctx.Ptr + BodySize > Ctx.End) { 1579 return make_error<GenericBinaryError>("Function extends beyond buffer", 1580 object_error::parse_failed); 1581 } 1582 Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize); 1583 // This will be set later when reading in the linking metadata section. 1584 Function.Comdat = UINT32_MAX; 1585 Ctx.Ptr += BodySize; 1586 assert(Ctx.Ptr == FunctionEnd); 1587 } 1588 if (Ctx.Ptr != Ctx.End) 1589 return make_error<GenericBinaryError>("code section ended prematurely", 1590 object_error::parse_failed); 1591 return Error::success(); 1592 } 1593 1594 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) { 1595 uint32_t Count = readVaruint32(Ctx); 1596 ElemSegments.reserve(Count); 1597 while (Count--) { 1598 wasm::WasmElemSegment Segment; 1599 Segment.Flags = readVaruint32(Ctx); 1600 1601 uint32_t SupportedFlags = wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER | 1602 wasm::WASM_ELEM_SEGMENT_IS_PASSIVE | 1603 wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS; 1604 if (Segment.Flags & ~SupportedFlags) 1605 return make_error<GenericBinaryError>( 1606 "Unsupported flags for element segment", object_error::parse_failed); 1607 1608 bool IsPassive = (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_PASSIVE) != 0; 1609 bool IsDeclarative = 1610 IsPassive && (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_DECLARATIVE); 1611 bool HasTableNumber = 1612 !IsPassive && 1613 (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER); 1614 bool HasInitExprs = 1615 (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS); 1616 bool HasElemKind = 1617 (Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) && 1618 !HasInitExprs; 1619 1620 if (HasTableNumber) 1621 Segment.TableNumber = readVaruint32(Ctx); 1622 else 1623 Segment.TableNumber = 0; 1624 1625 if (!isValidTableNumber(Segment.TableNumber)) 1626 return make_error<GenericBinaryError>("invalid TableNumber", 1627 object_error::parse_failed); 1628 1629 if (IsPassive || IsDeclarative) { 1630 Segment.Offset.Extended = false; 1631 Segment.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST; 1632 Segment.Offset.Inst.Value.Int32 = 0; 1633 } else { 1634 if (Error Err = readInitExpr(Segment.Offset, Ctx)) 1635 return Err; 1636 } 1637 1638 if (HasElemKind) { 1639 auto ElemKind = readVaruint32(Ctx); 1640 if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) { 1641 Segment.ElemKind = parseValType(Ctx, ElemKind); 1642 if (Segment.ElemKind != wasm::ValType::FUNCREF && 1643 Segment.ElemKind != wasm::ValType::EXTERNREF && 1644 Segment.ElemKind != wasm::ValType::OTHERREF) { 1645 return make_error<GenericBinaryError>("invalid elem type", 1646 object_error::parse_failed); 1647 } 1648 } else { 1649 if (ElemKind != 0) 1650 return make_error<GenericBinaryError>("invalid elem type", 1651 object_error::parse_failed); 1652 Segment.ElemKind = wasm::ValType::FUNCREF; 1653 } 1654 } else if (HasInitExprs) { 1655 auto ElemType = parseValType(Ctx, readVaruint32(Ctx)); 1656 Segment.ElemKind = ElemType; 1657 } else { 1658 Segment.ElemKind = wasm::ValType::FUNCREF; 1659 } 1660 1661 uint32_t NumElems = readVaruint32(Ctx); 1662 1663 if (HasInitExprs) { 1664 while (NumElems--) { 1665 wasm::WasmInitExpr Expr; 1666 if (Error Err = readInitExpr(Expr, Ctx)) 1667 return Err; 1668 } 1669 } else { 1670 while (NumElems--) { 1671 Segment.Functions.push_back(readVaruint32(Ctx)); 1672 } 1673 } 1674 ElemSegments.push_back(Segment); 1675 } 1676 if (Ctx.Ptr != Ctx.End) 1677 return make_error<GenericBinaryError>("elem section ended prematurely", 1678 object_error::parse_failed); 1679 return Error::success(); 1680 } 1681 1682 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) { 1683 DataSection = Sections.size(); 1684 uint32_t Count = readVaruint32(Ctx); 1685 if (DataCount && Count != *DataCount) 1686 return make_error<GenericBinaryError>( 1687 "number of data segments does not match DataCount section"); 1688 DataSegments.reserve(Count); 1689 while (Count--) { 1690 WasmSegment Segment; 1691 Segment.Data.InitFlags = readVaruint32(Ctx); 1692 Segment.Data.MemoryIndex = 1693 (Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX) 1694 ? readVaruint32(Ctx) 1695 : 0; 1696 if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) { 1697 if (Error Err = readInitExpr(Segment.Data.Offset, Ctx)) 1698 return Err; 1699 } else { 1700 Segment.Data.Offset.Extended = false; 1701 Segment.Data.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST; 1702 Segment.Data.Offset.Inst.Value.Int32 = 0; 1703 } 1704 uint32_t Size = readVaruint32(Ctx); 1705 if (Size > (size_t)(Ctx.End - Ctx.Ptr)) 1706 return make_error<GenericBinaryError>("invalid segment size", 1707 object_error::parse_failed); 1708 Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size); 1709 // The rest of these Data fields are set later, when reading in the linking 1710 // metadata section. 1711 Segment.Data.Alignment = 0; 1712 Segment.Data.LinkingFlags = 0; 1713 Segment.Data.Comdat = UINT32_MAX; 1714 Segment.SectionOffset = Ctx.Ptr - Ctx.Start; 1715 Ctx.Ptr += Size; 1716 DataSegments.push_back(Segment); 1717 } 1718 if (Ctx.Ptr != Ctx.End) 1719 return make_error<GenericBinaryError>("data section ended prematurely", 1720 object_error::parse_failed); 1721 return Error::success(); 1722 } 1723 1724 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) { 1725 DataCount = readVaruint32(Ctx); 1726 return Error::success(); 1727 } 1728 1729 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const { 1730 return Header; 1731 } 1732 1733 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; } 1734 1735 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const { 1736 uint32_t Result = SymbolRef::SF_None; 1737 const WasmSymbol &Sym = getWasmSymbol(Symb); 1738 1739 LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n"); 1740 if (Sym.isBindingWeak()) 1741 Result |= SymbolRef::SF_Weak; 1742 if (!Sym.isBindingLocal()) 1743 Result |= SymbolRef::SF_Global; 1744 if (Sym.isHidden()) 1745 Result |= SymbolRef::SF_Hidden; 1746 if (!Sym.isDefined()) 1747 Result |= SymbolRef::SF_Undefined; 1748 if (Sym.isTypeFunction()) 1749 Result |= SymbolRef::SF_Executable; 1750 return Result; 1751 } 1752 1753 basic_symbol_iterator WasmObjectFile::symbol_begin() const { 1754 DataRefImpl Ref; 1755 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1756 Ref.d.b = 0; // Symbol index 1757 return BasicSymbolRef(Ref, this); 1758 } 1759 1760 basic_symbol_iterator WasmObjectFile::symbol_end() const { 1761 DataRefImpl Ref; 1762 Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null 1763 Ref.d.b = Symbols.size(); // Symbol index 1764 return BasicSymbolRef(Ref, this); 1765 } 1766 1767 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const { 1768 return Symbols[Symb.d.b]; 1769 } 1770 1771 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const { 1772 return getWasmSymbol(Symb.getRawDataRefImpl()); 1773 } 1774 1775 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const { 1776 return getWasmSymbol(Symb).Info.Name; 1777 } 1778 1779 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const { 1780 auto &Sym = getWasmSymbol(Symb); 1781 if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION && 1782 isDefinedFunctionIndex(Sym.Info.ElementIndex)) { 1783 // For object files, use the section offset. The linker relies on this. 1784 // For linked files, use the file offset. This behavior matches the way 1785 // browsers print stack traces and is useful for binary size analysis. 1786 // (see https://webassembly.github.io/spec/web-api/index.html#conventions) 1787 uint32_t Adjustment = isRelocatableObject() || isSharedObject() 1788 ? 0 1789 : Sections[CodeSection].Offset; 1790 return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset + 1791 Adjustment; 1792 } 1793 return getSymbolValue(Symb); 1794 } 1795 1796 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const { 1797 switch (Sym.Info.Kind) { 1798 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1799 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1800 case wasm::WASM_SYMBOL_TYPE_TAG: 1801 case wasm::WASM_SYMBOL_TYPE_TABLE: 1802 return Sym.Info.ElementIndex; 1803 case wasm::WASM_SYMBOL_TYPE_DATA: { 1804 // The value of a data symbol is the segment offset, plus the symbol 1805 // offset within the segment. 1806 uint32_t SegmentIndex = Sym.Info.DataRef.Segment; 1807 const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data; 1808 if (Segment.Offset.Extended) { 1809 llvm_unreachable("extended init exprs not supported"); 1810 } else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) { 1811 return Segment.Offset.Inst.Value.Int32 + Sym.Info.DataRef.Offset; 1812 } else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) { 1813 return Segment.Offset.Inst.Value.Int64 + Sym.Info.DataRef.Offset; 1814 } else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_GLOBAL_GET) { 1815 return Sym.Info.DataRef.Offset; 1816 } else { 1817 llvm_unreachable("unknown init expr opcode"); 1818 } 1819 } 1820 case wasm::WASM_SYMBOL_TYPE_SECTION: 1821 return 0; 1822 } 1823 llvm_unreachable("invalid symbol type"); 1824 } 1825 1826 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const { 1827 return getWasmSymbolValue(getWasmSymbol(Symb)); 1828 } 1829 1830 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const { 1831 llvm_unreachable("not yet implemented"); 1832 return 0; 1833 } 1834 1835 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const { 1836 llvm_unreachable("not yet implemented"); 1837 return 0; 1838 } 1839 1840 Expected<SymbolRef::Type> 1841 WasmObjectFile::getSymbolType(DataRefImpl Symb) const { 1842 const WasmSymbol &Sym = getWasmSymbol(Symb); 1843 1844 switch (Sym.Info.Kind) { 1845 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1846 return SymbolRef::ST_Function; 1847 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1848 return SymbolRef::ST_Other; 1849 case wasm::WASM_SYMBOL_TYPE_DATA: 1850 return SymbolRef::ST_Data; 1851 case wasm::WASM_SYMBOL_TYPE_SECTION: 1852 return SymbolRef::ST_Debug; 1853 case wasm::WASM_SYMBOL_TYPE_TAG: 1854 return SymbolRef::ST_Other; 1855 case wasm::WASM_SYMBOL_TYPE_TABLE: 1856 return SymbolRef::ST_Other; 1857 } 1858 1859 llvm_unreachable("unknown WasmSymbol::SymbolType"); 1860 return SymbolRef::ST_Other; 1861 } 1862 1863 Expected<section_iterator> 1864 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const { 1865 const WasmSymbol &Sym = getWasmSymbol(Symb); 1866 if (Sym.isUndefined()) 1867 return section_end(); 1868 1869 DataRefImpl Ref; 1870 Ref.d.a = getSymbolSectionIdImpl(Sym); 1871 return section_iterator(SectionRef(Ref, this)); 1872 } 1873 1874 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const { 1875 const WasmSymbol &Sym = getWasmSymbol(Symb); 1876 return getSymbolSectionIdImpl(Sym); 1877 } 1878 1879 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const { 1880 switch (Sym.Info.Kind) { 1881 case wasm::WASM_SYMBOL_TYPE_FUNCTION: 1882 return CodeSection; 1883 case wasm::WASM_SYMBOL_TYPE_GLOBAL: 1884 return GlobalSection; 1885 case wasm::WASM_SYMBOL_TYPE_DATA: 1886 return DataSection; 1887 case wasm::WASM_SYMBOL_TYPE_SECTION: 1888 return Sym.Info.ElementIndex; 1889 case wasm::WASM_SYMBOL_TYPE_TAG: 1890 return TagSection; 1891 case wasm::WASM_SYMBOL_TYPE_TABLE: 1892 return TableSection; 1893 default: 1894 llvm_unreachable("unknown WasmSymbol::SymbolType"); 1895 } 1896 } 1897 1898 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; } 1899 1900 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const { 1901 const WasmSection &S = Sections[Sec.d.a]; 1902 if (S.Type == wasm::WASM_SEC_CUSTOM) 1903 return S.Name; 1904 if (S.Type > wasm::WASM_SEC_LAST_KNOWN) 1905 return createStringError(object_error::invalid_section_index, ""); 1906 return wasm::sectionTypeToString(S.Type); 1907 } 1908 1909 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; } 1910 1911 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const { 1912 return Sec.d.a; 1913 } 1914 1915 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const { 1916 const WasmSection &S = Sections[Sec.d.a]; 1917 return S.Content.size(); 1918 } 1919 1920 Expected<ArrayRef<uint8_t>> 1921 WasmObjectFile::getSectionContents(DataRefImpl Sec) const { 1922 const WasmSection &S = Sections[Sec.d.a]; 1923 // This will never fail since wasm sections can never be empty (user-sections 1924 // must have a name and non-user sections each have a defined structure). 1925 return S.Content; 1926 } 1927 1928 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const { 1929 return 1; 1930 } 1931 1932 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const { 1933 return false; 1934 } 1935 1936 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const { 1937 return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE; 1938 } 1939 1940 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const { 1941 return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA; 1942 } 1943 1944 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; } 1945 1946 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; } 1947 1948 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const { 1949 DataRefImpl RelocRef; 1950 RelocRef.d.a = Ref.d.a; 1951 RelocRef.d.b = 0; 1952 return relocation_iterator(RelocationRef(RelocRef, this)); 1953 } 1954 1955 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const { 1956 const WasmSection &Sec = getWasmSection(Ref); 1957 DataRefImpl RelocRef; 1958 RelocRef.d.a = Ref.d.a; 1959 RelocRef.d.b = Sec.Relocations.size(); 1960 return relocation_iterator(RelocationRef(RelocRef, this)); 1961 } 1962 1963 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; } 1964 1965 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const { 1966 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1967 return Rel.Offset; 1968 } 1969 1970 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const { 1971 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1972 if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB) 1973 return symbol_end(); 1974 DataRefImpl Sym; 1975 Sym.d.a = 1; 1976 Sym.d.b = Rel.Index; 1977 return symbol_iterator(SymbolRef(Sym, this)); 1978 } 1979 1980 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const { 1981 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1982 return Rel.Type; 1983 } 1984 1985 void WasmObjectFile::getRelocationTypeName( 1986 DataRefImpl Ref, SmallVectorImpl<char> &Result) const { 1987 const wasm::WasmRelocation &Rel = getWasmRelocation(Ref); 1988 StringRef Res = "Unknown"; 1989 1990 #define WASM_RELOC(name, value) \ 1991 case wasm::name: \ 1992 Res = #name; \ 1993 break; 1994 1995 switch (Rel.Type) { 1996 #include "llvm/BinaryFormat/WasmRelocs.def" 1997 } 1998 1999 #undef WASM_RELOC 2000 2001 Result.append(Res.begin(), Res.end()); 2002 } 2003 2004 section_iterator WasmObjectFile::section_begin() const { 2005 DataRefImpl Ref; 2006 Ref.d.a = 0; 2007 return section_iterator(SectionRef(Ref, this)); 2008 } 2009 2010 section_iterator WasmObjectFile::section_end() const { 2011 DataRefImpl Ref; 2012 Ref.d.a = Sections.size(); 2013 return section_iterator(SectionRef(Ref, this)); 2014 } 2015 2016 uint8_t WasmObjectFile::getBytesInAddress() const { 2017 return HasMemory64 ? 8 : 4; 2018 } 2019 2020 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; } 2021 2022 Triple::ArchType WasmObjectFile::getArch() const { 2023 return HasMemory64 ? Triple::wasm64 : Triple::wasm32; 2024 } 2025 2026 Expected<SubtargetFeatures> WasmObjectFile::getFeatures() const { 2027 return SubtargetFeatures(); 2028 } 2029 2030 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; } 2031 2032 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; } 2033 2034 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const { 2035 assert(Ref.d.a < Sections.size()); 2036 return Sections[Ref.d.a]; 2037 } 2038 2039 const WasmSection & 2040 WasmObjectFile::getWasmSection(const SectionRef &Section) const { 2041 return getWasmSection(Section.getRawDataRefImpl()); 2042 } 2043 2044 const wasm::WasmRelocation & 2045 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const { 2046 return getWasmRelocation(Ref.getRawDataRefImpl()); 2047 } 2048 2049 const wasm::WasmRelocation & 2050 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const { 2051 assert(Ref.d.a < Sections.size()); 2052 const WasmSection &Sec = Sections[Ref.d.a]; 2053 assert(Ref.d.b < Sec.Relocations.size()); 2054 return Sec.Relocations[Ref.d.b]; 2055 } 2056 2057 int WasmSectionOrderChecker::getSectionOrder(unsigned ID, 2058 StringRef CustomSectionName) { 2059 switch (ID) { 2060 case wasm::WASM_SEC_CUSTOM: 2061 return StringSwitch<unsigned>(CustomSectionName) 2062 .Case("dylink", WASM_SEC_ORDER_DYLINK) 2063 .Case("dylink.0", WASM_SEC_ORDER_DYLINK) 2064 .Case("linking", WASM_SEC_ORDER_LINKING) 2065 .StartsWith("reloc.", WASM_SEC_ORDER_RELOC) 2066 .Case("name", WASM_SEC_ORDER_NAME) 2067 .Case("producers", WASM_SEC_ORDER_PRODUCERS) 2068 .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES) 2069 .Default(WASM_SEC_ORDER_NONE); 2070 case wasm::WASM_SEC_TYPE: 2071 return WASM_SEC_ORDER_TYPE; 2072 case wasm::WASM_SEC_IMPORT: 2073 return WASM_SEC_ORDER_IMPORT; 2074 case wasm::WASM_SEC_FUNCTION: 2075 return WASM_SEC_ORDER_FUNCTION; 2076 case wasm::WASM_SEC_TABLE: 2077 return WASM_SEC_ORDER_TABLE; 2078 case wasm::WASM_SEC_MEMORY: 2079 return WASM_SEC_ORDER_MEMORY; 2080 case wasm::WASM_SEC_GLOBAL: 2081 return WASM_SEC_ORDER_GLOBAL; 2082 case wasm::WASM_SEC_EXPORT: 2083 return WASM_SEC_ORDER_EXPORT; 2084 case wasm::WASM_SEC_START: 2085 return WASM_SEC_ORDER_START; 2086 case wasm::WASM_SEC_ELEM: 2087 return WASM_SEC_ORDER_ELEM; 2088 case wasm::WASM_SEC_CODE: 2089 return WASM_SEC_ORDER_CODE; 2090 case wasm::WASM_SEC_DATA: 2091 return WASM_SEC_ORDER_DATA; 2092 case wasm::WASM_SEC_DATACOUNT: 2093 return WASM_SEC_ORDER_DATACOUNT; 2094 case wasm::WASM_SEC_TAG: 2095 return WASM_SEC_ORDER_TAG; 2096 default: 2097 return WASM_SEC_ORDER_NONE; 2098 } 2099 } 2100 2101 // Represents the edges in a directed graph where any node B reachable from node 2102 // A is not allowed to appear before A in the section ordering, but may appear 2103 // afterward. 2104 int WasmSectionOrderChecker::DisallowedPredecessors 2105 [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = { 2106 // WASM_SEC_ORDER_NONE 2107 {}, 2108 // WASM_SEC_ORDER_TYPE 2109 {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT}, 2110 // WASM_SEC_ORDER_IMPORT 2111 {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION}, 2112 // WASM_SEC_ORDER_FUNCTION 2113 {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE}, 2114 // WASM_SEC_ORDER_TABLE 2115 {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY}, 2116 // WASM_SEC_ORDER_MEMORY 2117 {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_TAG}, 2118 // WASM_SEC_ORDER_TAG 2119 {WASM_SEC_ORDER_TAG, WASM_SEC_ORDER_GLOBAL}, 2120 // WASM_SEC_ORDER_GLOBAL 2121 {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT}, 2122 // WASM_SEC_ORDER_EXPORT 2123 {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START}, 2124 // WASM_SEC_ORDER_START 2125 {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM}, 2126 // WASM_SEC_ORDER_ELEM 2127 {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT}, 2128 // WASM_SEC_ORDER_DATACOUNT 2129 {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE}, 2130 // WASM_SEC_ORDER_CODE 2131 {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA}, 2132 // WASM_SEC_ORDER_DATA 2133 {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING}, 2134 2135 // Custom Sections 2136 // WASM_SEC_ORDER_DYLINK 2137 {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE}, 2138 // WASM_SEC_ORDER_LINKING 2139 {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME}, 2140 // WASM_SEC_ORDER_RELOC (can be repeated) 2141 {}, 2142 // WASM_SEC_ORDER_NAME 2143 {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS}, 2144 // WASM_SEC_ORDER_PRODUCERS 2145 {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES}, 2146 // WASM_SEC_ORDER_TARGET_FEATURES 2147 {WASM_SEC_ORDER_TARGET_FEATURES}}; 2148 2149 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID, 2150 StringRef CustomSectionName) { 2151 int Order = getSectionOrder(ID, CustomSectionName); 2152 if (Order == WASM_SEC_ORDER_NONE) 2153 return true; 2154 2155 // Disallowed predecessors we need to check for 2156 SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList; 2157 2158 // Keep track of completed checks to avoid repeating work 2159 bool Checked[WASM_NUM_SEC_ORDERS] = {}; 2160 2161 int Curr = Order; 2162 while (true) { 2163 // Add new disallowed predecessors to work list 2164 for (size_t I = 0;; ++I) { 2165 int Next = DisallowedPredecessors[Curr][I]; 2166 if (Next == WASM_SEC_ORDER_NONE) 2167 break; 2168 if (Checked[Next]) 2169 continue; 2170 WorkList.push_back(Next); 2171 Checked[Next] = true; 2172 } 2173 2174 if (WorkList.empty()) 2175 break; 2176 2177 // Consider next disallowed predecessor 2178 Curr = WorkList.pop_back_val(); 2179 if (Seen[Curr]) 2180 return false; 2181 } 2182 2183 // Have not seen any disallowed predecessors 2184 Seen[Order] = true; 2185 return true; 2186 } 2187