1 //===- WasmObjectFile.cpp - Wasm object file implementation ---------------===//
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
7 //===----------------------------------------------------------------------===//
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"
32 #include <system_error>
34 #define DEBUG_TYPE "wasm-object"
37 using namespace object
;
39 void WasmSymbol::print(raw_ostream
&Out
) const {
40 Out
<< "Name=" << Info
.Name
41 << ", Kind=" << toString(wasm::WasmSymbolType(Info
.Kind
))
42 << ", Flags=" << Info
.Flags
;
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
;
52 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
53 LLVM_DUMP_METHOD
void WasmSymbol::dump() const { print(dbgs()); }
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
);
61 return std::move(Err
);
63 return std::move(ObjectFile
);
66 #define VARINT7_MAX ((1 << 7) - 1)
67 #define VARINT7_MIN (-(1 << 7))
68 #define VARUINT7_MAX (1 << 7)
69 #define VARUINT1_MAX (1)
71 static uint8_t readUint8(WasmObjectFile::ReadContext
&Ctx
) {
72 if (Ctx
.Ptr
== Ctx
.End
)
73 report_fatal_error("EOF while reading uint8");
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
);
85 static int32_t readFloat32(WasmObjectFile::ReadContext
&Ctx
) {
86 if (Ctx
.Ptr
+ 4 > Ctx
.End
)
87 report_fatal_error("EOF while reading float64");
89 memcpy(&Result
, Ctx
.Ptr
, sizeof(Result
));
90 Ctx
.Ptr
+= sizeof(Result
);
94 static int64_t readFloat64(WasmObjectFile::ReadContext
&Ctx
) {
95 if (Ctx
.Ptr
+ 8 > Ctx
.End
)
96 report_fatal_error("EOF while reading float64");
98 memcpy(&Result
, Ctx
.Ptr
, sizeof(Result
));
99 Ctx
.Ptr
+= sizeof(Result
);
103 static uint64_t readULEB128(WasmObjectFile::ReadContext
&Ctx
) {
105 const char *Error
= nullptr;
106 uint64_t Result
= decodeULEB128(Ctx
.Ptr
, &Count
, Ctx
.End
, &Error
);
108 report_fatal_error(Error
);
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");
118 StringRef(reinterpret_cast<const char *>(Ctx
.Ptr
), StringLen
);
119 Ctx
.Ptr
+= StringLen
;
123 static int64_t readLEB128(WasmObjectFile::ReadContext
&Ctx
) {
125 const char *Error
= nullptr;
126 uint64_t Result
= decodeSLEB128(Ctx
.Ptr
, &Count
, Ctx
.End
, &Error
);
128 report_fatal_error(Error
);
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");
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");
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");
154 static int64_t readVarint64(WasmObjectFile::ReadContext
&Ctx
) {
155 return readLEB128(Ctx
);
158 static uint8_t readOpcode(WasmObjectFile::ReadContext
&Ctx
) {
159 return readUint8(Ctx
);
162 static Error
readInitExpr(wasm::WasmInitExpr
&Expr
,
163 WasmObjectFile::ReadContext
&Ctx
) {
164 Expr
.Opcode
= readOpcode(Ctx
);
166 switch (Expr
.Opcode
) {
167 case wasm::WASM_OPCODE_I32_CONST
:
168 Expr
.Value
.Int32
= readVarint32(Ctx
);
170 case wasm::WASM_OPCODE_I64_CONST
:
171 Expr
.Value
.Int64
= readVarint64(Ctx
);
173 case wasm::WASM_OPCODE_F32_CONST
:
174 Expr
.Value
.Float32
= readFloat32(Ctx
);
176 case wasm::WASM_OPCODE_F64_CONST
:
177 Expr
.Value
.Float64
= readFloat64(Ctx
);
179 case wasm::WASM_OPCODE_GLOBAL_GET
:
180 Expr
.Value
.Global
= readULEB128(Ctx
);
183 return make_error
<GenericBinaryError
>("Invalid opcode in init_expr",
184 object_error::parse_failed
);
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
);
192 return Error::success();
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
);
204 static wasm::WasmTable
readTable(WasmObjectFile::ReadContext
&Ctx
) {
205 wasm::WasmTable Table
;
206 Table
.ElemType
= readUint8(Ctx
);
207 Table
.Limits
= readLimits(Ctx
);
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
);
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
;
229 Section
.Name
= readString(SectionCtx
);
231 uint32_t SectionNameSize
= SectionCtx
.Ptr
- SectionCtx
.Start
;
232 Ctx
.Ptr
+= SectionNameSize
;
233 Size
-= SectionNameSize
;
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
);
242 Section
.Content
= ArrayRef
<uint8_t>(Ctx
.Ptr
, Size
);
244 return Error::success();
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)) {
253 make_error
<StringError
>("Bad magic number", object_error::parse_failed
);
258 Ctx
.Start
= getData().bytes_begin();
259 Ctx
.Ptr
= Ctx
.Start
+ 4;
260 Ctx
.End
= Ctx
.Start
+ getData().size();
262 if (Ctx
.Ptr
+ 4 > Ctx
.End
) {
263 Err
= make_error
<StringError
>("Missing version number",
264 object_error::parse_failed
);
268 Header
.Version
= readUint32(Ctx
);
269 if (Header
.Version
!= wasm::WasmVersion
) {
270 Err
= make_error
<StringError
>("Bad version number",
271 object_error::parse_failed
);
276 WasmSectionOrderChecker Checker
;
277 while (Ctx
.Ptr
< Ctx
.End
) {
278 if ((Err
= readSection(Sec
, Ctx
, Checker
)))
280 if ((Err
= parseSection(Sec
)))
283 Sections
.push_back(Sec
);
287 Error
WasmObjectFile::parseSection(WasmSection
&Sec
) {
289 Ctx
.Start
= Sec
.Content
.data();
290 Ctx
.End
= Ctx
.Start
+ Sec
.Content
.size();
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_GLOBAL
:
306 return parseGlobalSection(Ctx
);
307 case wasm::WASM_SEC_EVENT
:
308 return parseEventSection(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
);
322 return make_error
<GenericBinaryError
>(
323 "Invalid section type: " + Twine(Sec
.Type
), object_error::parse_failed
);
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
);
336 DylinkInfo
.Needed
.push_back(readString(Ctx
));
338 if (Ctx
.Ptr
!= Ctx
.End
)
339 return make_error
<GenericBinaryError
>("dylink section ended prematurely",
340 object_error::parse_failed
);
341 return Error::success();
344 Error
WasmObjectFile::parseNameSection(ReadContext
&Ctx
) {
345 llvm::DenseSet
<uint64_t> Seen
;
346 if (Functions
.size() != FunctionTypes
.size()) {
347 return make_error
<GenericBinaryError
>("Names must come after code section",
348 object_error::parse_failed
);
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
;
356 case wasm::WASM_NAMES_FUNCTION
: {
357 uint32_t Count
= readVaruint32(Ctx
);
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
;
373 // Ignore local names for now
374 case wasm::WASM_NAMES_LOCAL
:
379 if (Ctx
.Ptr
!= SubSectionEnd
)
380 return make_error
<GenericBinaryError
>(
381 "Name sub-section ended prematurely", object_error::parse_failed
);
384 if (Ctx
.Ptr
!= Ctx
.End
)
385 return make_error
<GenericBinaryError
>("Name section ended prematurely",
386 object_error::parse_failed
);
387 return Error::success();
390 Error
WasmObjectFile::parseLinkingSection(ReadContext
&Ctx
) {
391 HasLinkingSection
= true;
392 if (Functions
.size() != FunctionTypes
.size()) {
393 return make_error
<GenericBinaryError
>(
394 "Linking data must come after code section",
395 object_error::parse_failed
);
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
);
406 const uint8_t *OrigEnd
= Ctx
.End
;
407 while (Ctx
.Ptr
< OrigEnd
) {
409 uint8_t Type
= readUint8(Ctx
);
410 uint32_t Size
= readVaruint32(Ctx
);
411 LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type
) << " size=" << Size
413 Ctx
.End
= Ctx
.Ptr
+ Size
;
415 case wasm::WASM_SYMBOL_TABLE
:
416 if (Error Err
= parseLinkingSectionSymtab(Ctx
))
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
);
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: " +
441 object_error::parse_failed
);
442 LinkingData
.InitFunctions
.emplace_back(Init
);
446 case wasm::WASM_COMDAT_INFO
:
447 if (Error Err
= parseLinkingSectionComdat(Ctx
))
454 if (Ctx
.Ptr
!= Ctx
.End
)
455 return make_error
<GenericBinaryError
>(
456 "Linking sub-section ended prematurely", object_error::parse_failed
);
458 if (Ctx
.Ptr
!= OrigEnd
)
459 return make_error
<GenericBinaryError
>("Linking section ended prematurely",
460 object_error::parse_failed
);
461 return Error::success();
464 Error
WasmObjectFile::parseLinkingSectionSymtab(ReadContext
&Ctx
) {
465 uint32_t Count
= readVaruint32(Ctx
);
466 LinkingData
.SymbolTable
.reserve(Count
);
467 Symbols
.reserve(Count
);
468 StringSet
<> SymbolNames
;
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
);
486 wasm::WasmSymbolInfo Info
;
487 const wasm::WasmSignature
*Signature
= nullptr;
488 const wasm::WasmGlobalType
*GlobalType
= nullptr;
489 const wasm::WasmEventType
*EventType
= nullptr;
491 Info
.Kind
= readUint8(Ctx
);
492 Info
.Flags
= readVaruint32(Ctx
);
493 bool IsDefined
= (Info
.Flags
& wasm::WASM_SYMBOL_UNDEFINED
) == 0;
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
);
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
;
510 wasm::WasmImport
&Import
= *ImportedFunctions
[Info
.ElementIndex
];
511 if ((Info
.Flags
& wasm::WASM_SYMBOL_EXPLICIT_NAME
) != 0)
512 Info
.Name
= readString(Ctx
);
514 Info
.Name
= Import
.Field
;
515 Signature
= &Signatures
[Import
.SigIndex
];
516 Info
.ImportName
= Import
.Field
;
517 Info
.ImportModule
= Import
.Module
;
521 case wasm::WASM_SYMBOL_TYPE_GLOBAL
:
522 Info
.ElementIndex
= readVaruint32(Ctx
);
523 if (!isValidGlobalIndex(Info
.ElementIndex
) ||
524 IsDefined
!= isDefinedGlobalIndex(Info
.ElementIndex
))
525 return make_error
<GenericBinaryError
>("invalid global symbol index",
526 object_error::parse_failed
);
527 if (!IsDefined
&& (Info
.Flags
& wasm::WASM_SYMBOL_BINDING_MASK
) ==
528 wasm::WASM_SYMBOL_BINDING_WEAK
)
529 return make_error
<GenericBinaryError
>("undefined weak global symbol",
530 object_error::parse_failed
);
532 Info
.Name
= readString(Ctx
);
533 unsigned GlobalIndex
= Info
.ElementIndex
- NumImportedGlobals
;
534 wasm::WasmGlobal
&Global
= Globals
[GlobalIndex
];
535 GlobalType
= &Global
.Type
;
536 if (Global
.SymbolName
.empty())
537 Global
.SymbolName
= Info
.Name
;
539 wasm::WasmImport
&Import
= *ImportedGlobals
[Info
.ElementIndex
];
540 if ((Info
.Flags
& wasm::WASM_SYMBOL_EXPLICIT_NAME
) != 0)
541 Info
.Name
= readString(Ctx
);
543 Info
.Name
= Import
.Field
;
544 GlobalType
= &Import
.Global
;
545 Info
.ImportName
= Import
.Field
;
546 Info
.ImportModule
= Import
.Module
;
550 case wasm::WASM_SYMBOL_TYPE_DATA
:
551 Info
.Name
= readString(Ctx
);
553 uint32_t Index
= readVaruint32(Ctx
);
554 if (Index
>= DataSegments
.size())
555 return make_error
<GenericBinaryError
>("invalid data symbol index",
556 object_error::parse_failed
);
557 uint32_t Offset
= readVaruint32(Ctx
);
558 uint32_t Size
= readVaruint32(Ctx
);
559 if (Offset
+ Size
> DataSegments
[Index
].Data
.Content
.size())
560 return make_error
<GenericBinaryError
>("invalid data symbol offset",
561 object_error::parse_failed
);
562 Info
.DataRef
= wasm::WasmDataReference
{Index
, Offset
, Size
};
566 case wasm::WASM_SYMBOL_TYPE_SECTION
: {
567 if ((Info
.Flags
& wasm::WASM_SYMBOL_BINDING_MASK
) !=
568 wasm::WASM_SYMBOL_BINDING_LOCAL
)
569 return make_error
<GenericBinaryError
>(
570 "Section symbols must have local binding",
571 object_error::parse_failed
);
572 Info
.ElementIndex
= readVaruint32(Ctx
);
573 // Use somewhat unique section name as symbol name.
574 StringRef SectionName
= Sections
[Info
.ElementIndex
].Name
;
575 Info
.Name
= SectionName
;
579 case wasm::WASM_SYMBOL_TYPE_EVENT
: {
580 Info
.ElementIndex
= readVaruint32(Ctx
);
581 if (!isValidEventIndex(Info
.ElementIndex
) ||
582 IsDefined
!= isDefinedEventIndex(Info
.ElementIndex
))
583 return make_error
<GenericBinaryError
>("invalid event symbol index",
584 object_error::parse_failed
);
585 if (!IsDefined
&& (Info
.Flags
& wasm::WASM_SYMBOL_BINDING_MASK
) ==
586 wasm::WASM_SYMBOL_BINDING_WEAK
)
587 return make_error
<GenericBinaryError
>("undefined weak global symbol",
588 object_error::parse_failed
);
590 Info
.Name
= readString(Ctx
);
591 unsigned EventIndex
= Info
.ElementIndex
- NumImportedEvents
;
592 wasm::WasmEvent
&Event
= Events
[EventIndex
];
593 Signature
= &Signatures
[Event
.Type
.SigIndex
];
594 EventType
= &Event
.Type
;
595 if (Event
.SymbolName
.empty())
596 Event
.SymbolName
= Info
.Name
;
599 wasm::WasmImport
&Import
= *ImportedEvents
[Info
.ElementIndex
];
600 if ((Info
.Flags
& wasm::WASM_SYMBOL_EXPLICIT_NAME
) != 0)
601 Info
.Name
= readString(Ctx
);
603 Info
.Name
= Import
.Field
;
604 EventType
= &Import
.Event
;
605 Signature
= &Signatures
[EventType
->SigIndex
];
606 Info
.ImportName
= Import
.Field
;
607 Info
.ImportModule
= Import
.Module
;
613 return make_error
<GenericBinaryError
>("Invalid symbol type",
614 object_error::parse_failed
);
617 if ((Info
.Flags
& wasm::WASM_SYMBOL_BINDING_MASK
) !=
618 wasm::WASM_SYMBOL_BINDING_LOCAL
&&
619 !SymbolNames
.insert(Info
.Name
).second
)
620 return make_error
<GenericBinaryError
>("Duplicate symbol name " +
622 object_error::parse_failed
);
623 LinkingData
.SymbolTable
.emplace_back(Info
);
624 Symbols
.emplace_back(LinkingData
.SymbolTable
.back(), GlobalType
, EventType
,
626 LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols
.back() << "\n");
629 return Error::success();
632 Error
WasmObjectFile::parseLinkingSectionComdat(ReadContext
&Ctx
) {
633 uint32_t ComdatCount
= readVaruint32(Ctx
);
634 StringSet
<> ComdatSet
;
635 for (unsigned ComdatIndex
= 0; ComdatIndex
< ComdatCount
; ++ComdatIndex
) {
636 StringRef Name
= readString(Ctx
);
637 if (Name
.empty() || !ComdatSet
.insert(Name
).second
)
638 return make_error
<GenericBinaryError
>("Bad/duplicate COMDAT name " +
640 object_error::parse_failed
);
641 LinkingData
.Comdats
.emplace_back(Name
);
642 uint32_t Flags
= readVaruint32(Ctx
);
644 return make_error
<GenericBinaryError
>("Unsupported COMDAT flags",
645 object_error::parse_failed
);
647 uint32_t EntryCount
= readVaruint32(Ctx
);
648 while (EntryCount
--) {
649 unsigned Kind
= readVaruint32(Ctx
);
650 unsigned Index
= readVaruint32(Ctx
);
653 return make_error
<GenericBinaryError
>("Invalid COMDAT entry type",
654 object_error::parse_failed
);
655 case wasm::WASM_COMDAT_DATA
:
656 if (Index
>= DataSegments
.size())
657 return make_error
<GenericBinaryError
>(
658 "COMDAT data index out of range", object_error::parse_failed
);
659 if (DataSegments
[Index
].Data
.Comdat
!= UINT32_MAX
)
660 return make_error
<GenericBinaryError
>("Data segment in two COMDATs",
661 object_error::parse_failed
);
662 DataSegments
[Index
].Data
.Comdat
= ComdatIndex
;
664 case wasm::WASM_COMDAT_FUNCTION
:
665 if (!isDefinedFunctionIndex(Index
))
666 return make_error
<GenericBinaryError
>(
667 "COMDAT function index out of range", object_error::parse_failed
);
668 if (getDefinedFunction(Index
).Comdat
!= UINT32_MAX
)
669 return make_error
<GenericBinaryError
>("Function in two COMDATs",
670 object_error::parse_failed
);
671 getDefinedFunction(Index
).Comdat
= ComdatIndex
;
676 return Error::success();
679 Error
WasmObjectFile::parseProducersSection(ReadContext
&Ctx
) {
680 llvm::SmallSet
<StringRef
, 3> FieldsSeen
;
681 uint32_t Fields
= readVaruint32(Ctx
);
682 for (size_t I
= 0; I
< Fields
; ++I
) {
683 StringRef FieldName
= readString(Ctx
);
684 if (!FieldsSeen
.insert(FieldName
).second
)
685 return make_error
<GenericBinaryError
>(
686 "Producers section does not have unique fields",
687 object_error::parse_failed
);
688 std::vector
<std::pair
<std::string
, std::string
>> *ProducerVec
= nullptr;
689 if (FieldName
== "language") {
690 ProducerVec
= &ProducerInfo
.Languages
;
691 } else if (FieldName
== "processed-by") {
692 ProducerVec
= &ProducerInfo
.Tools
;
693 } else if (FieldName
== "sdk") {
694 ProducerVec
= &ProducerInfo
.SDKs
;
696 return make_error
<GenericBinaryError
>(
697 "Producers section field is not named one of language, processed-by, "
699 object_error::parse_failed
);
701 uint32_t ValueCount
= readVaruint32(Ctx
);
702 llvm::SmallSet
<StringRef
, 8> ProducersSeen
;
703 for (size_t J
= 0; J
< ValueCount
; ++J
) {
704 StringRef Name
= readString(Ctx
);
705 StringRef Version
= readString(Ctx
);
706 if (!ProducersSeen
.insert(Name
).second
) {
707 return make_error
<GenericBinaryError
>(
708 "Producers section contains repeated producer",
709 object_error::parse_failed
);
711 ProducerVec
->emplace_back(Name
, Version
);
714 if (Ctx
.Ptr
!= Ctx
.End
)
715 return make_error
<GenericBinaryError
>("Producers section ended prematurely",
716 object_error::parse_failed
);
717 return Error::success();
720 Error
WasmObjectFile::parseTargetFeaturesSection(ReadContext
&Ctx
) {
721 llvm::SmallSet
<std::string
, 8> FeaturesSeen
;
722 uint32_t FeatureCount
= readVaruint32(Ctx
);
723 for (size_t I
= 0; I
< FeatureCount
; ++I
) {
724 wasm::WasmFeatureEntry Feature
;
725 Feature
.Prefix
= readUint8(Ctx
);
726 switch (Feature
.Prefix
) {
727 case wasm::WASM_FEATURE_PREFIX_USED
:
728 case wasm::WASM_FEATURE_PREFIX_REQUIRED
:
729 case wasm::WASM_FEATURE_PREFIX_DISALLOWED
:
732 return make_error
<GenericBinaryError
>("Unknown feature policy prefix",
733 object_error::parse_failed
);
735 Feature
.Name
= readString(Ctx
);
736 if (!FeaturesSeen
.insert(Feature
.Name
).second
)
737 return make_error
<GenericBinaryError
>(
738 "Target features section contains repeated feature \"" +
740 object_error::parse_failed
);
741 TargetFeatures
.push_back(Feature
);
743 if (Ctx
.Ptr
!= Ctx
.End
)
744 return make_error
<GenericBinaryError
>(
745 "Target features section ended prematurely",
746 object_error::parse_failed
);
747 return Error::success();
750 Error
WasmObjectFile::parseRelocSection(StringRef Name
, ReadContext
&Ctx
) {
751 uint32_t SectionIndex
= readVaruint32(Ctx
);
752 if (SectionIndex
>= Sections
.size())
753 return make_error
<GenericBinaryError
>("Invalid section index",
754 object_error::parse_failed
);
755 WasmSection
&Section
= Sections
[SectionIndex
];
756 uint32_t RelocCount
= readVaruint32(Ctx
);
757 uint32_t EndOffset
= Section
.Content
.size();
758 uint32_t PreviousOffset
= 0;
759 while (RelocCount
--) {
760 wasm::WasmRelocation Reloc
= {};
761 Reloc
.Type
= readVaruint32(Ctx
);
762 Reloc
.Offset
= readVaruint32(Ctx
);
763 if (Reloc
.Offset
< PreviousOffset
)
764 return make_error
<GenericBinaryError
>("Relocations not in offset order",
765 object_error::parse_failed
);
766 PreviousOffset
= Reloc
.Offset
;
767 Reloc
.Index
= readVaruint32(Ctx
);
768 switch (Reloc
.Type
) {
769 case wasm::R_WASM_FUNCTION_INDEX_LEB
:
770 case wasm::R_WASM_TABLE_INDEX_SLEB
:
771 case wasm::R_WASM_TABLE_INDEX_I32
:
772 case wasm::R_WASM_TABLE_INDEX_REL_SLEB
:
773 if (!isValidFunctionSymbol(Reloc
.Index
))
774 return make_error
<GenericBinaryError
>("Bad relocation function index",
775 object_error::parse_failed
);
777 case wasm::R_WASM_TYPE_INDEX_LEB
:
778 if (Reloc
.Index
>= Signatures
.size())
779 return make_error
<GenericBinaryError
>("Bad relocation type index",
780 object_error::parse_failed
);
782 case wasm::R_WASM_GLOBAL_INDEX_LEB
:
783 // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data
784 // symbols to refer to their GOT entries.
785 if (!isValidGlobalSymbol(Reloc
.Index
) &&
786 !isValidDataSymbol(Reloc
.Index
) &&
787 !isValidFunctionSymbol(Reloc
.Index
))
788 return make_error
<GenericBinaryError
>("Bad relocation global index",
789 object_error::parse_failed
);
791 case wasm::R_WASM_EVENT_INDEX_LEB
:
792 if (!isValidEventSymbol(Reloc
.Index
))
793 return make_error
<GenericBinaryError
>("Bad relocation event index",
794 object_error::parse_failed
);
796 case wasm::R_WASM_MEMORY_ADDR_LEB
:
797 case wasm::R_WASM_MEMORY_ADDR_SLEB
:
798 case wasm::R_WASM_MEMORY_ADDR_I32
:
799 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB
:
800 if (!isValidDataSymbol(Reloc
.Index
))
801 return make_error
<GenericBinaryError
>("Bad relocation data index",
802 object_error::parse_failed
);
803 Reloc
.Addend
= readVarint32(Ctx
);
805 case wasm::R_WASM_FUNCTION_OFFSET_I32
:
806 if (!isValidFunctionSymbol(Reloc
.Index
))
807 return make_error
<GenericBinaryError
>("Bad relocation function index",
808 object_error::parse_failed
);
809 Reloc
.Addend
= readVarint32(Ctx
);
811 case wasm::R_WASM_SECTION_OFFSET_I32
:
812 if (!isValidSectionSymbol(Reloc
.Index
))
813 return make_error
<GenericBinaryError
>("Bad relocation section index",
814 object_error::parse_failed
);
815 Reloc
.Addend
= readVarint32(Ctx
);
818 return make_error
<GenericBinaryError
>("Bad relocation type: " +
820 object_error::parse_failed
);
823 // Relocations must fit inside the section, and must appear in order. They
824 // also shouldn't overlap a function/element boundary, but we don't bother
827 if (Reloc
.Type
== wasm::R_WASM_TABLE_INDEX_I32
||
828 Reloc
.Type
== wasm::R_WASM_MEMORY_ADDR_I32
||
829 Reloc
.Type
== wasm::R_WASM_SECTION_OFFSET_I32
||
830 Reloc
.Type
== wasm::R_WASM_FUNCTION_OFFSET_I32
)
832 if (Reloc
.Offset
+ Size
> EndOffset
)
833 return make_error
<GenericBinaryError
>("Bad relocation offset",
834 object_error::parse_failed
);
836 Section
.Relocations
.push_back(Reloc
);
838 if (Ctx
.Ptr
!= Ctx
.End
)
839 return make_error
<GenericBinaryError
>("Reloc section ended prematurely",
840 object_error::parse_failed
);
841 return Error::success();
844 Error
WasmObjectFile::parseCustomSection(WasmSection
&Sec
, ReadContext
&Ctx
) {
845 if (Sec
.Name
== "dylink") {
846 if (Error Err
= parseDylinkSection(Ctx
))
848 } else if (Sec
.Name
== "name") {
849 if (Error Err
= parseNameSection(Ctx
))
851 } else if (Sec
.Name
== "linking") {
852 if (Error Err
= parseLinkingSection(Ctx
))
854 } else if (Sec
.Name
== "producers") {
855 if (Error Err
= parseProducersSection(Ctx
))
857 } else if (Sec
.Name
== "target_features") {
858 if (Error Err
= parseTargetFeaturesSection(Ctx
))
860 } else if (Sec
.Name
.startswith("reloc.")) {
861 if (Error Err
= parseRelocSection(Sec
.Name
, Ctx
))
864 return Error::success();
867 Error
WasmObjectFile::parseTypeSection(ReadContext
&Ctx
) {
868 uint32_t Count
= readVaruint32(Ctx
);
869 Signatures
.reserve(Count
);
871 wasm::WasmSignature Sig
;
872 uint8_t Form
= readUint8(Ctx
);
873 if (Form
!= wasm::WASM_TYPE_FUNC
) {
874 return make_error
<GenericBinaryError
>("Invalid signature type",
875 object_error::parse_failed
);
877 uint32_t ParamCount
= readVaruint32(Ctx
);
878 Sig
.Params
.reserve(ParamCount
);
879 while (ParamCount
--) {
880 uint32_t ParamType
= readUint8(Ctx
);
881 Sig
.Params
.push_back(wasm::ValType(ParamType
));
883 uint32_t ReturnCount
= readVaruint32(Ctx
);
884 while (ReturnCount
--) {
885 uint32_t ReturnType
= readUint8(Ctx
);
886 Sig
.Returns
.push_back(wasm::ValType(ReturnType
));
888 Signatures
.push_back(std::move(Sig
));
890 if (Ctx
.Ptr
!= Ctx
.End
)
891 return make_error
<GenericBinaryError
>("Type section ended prematurely",
892 object_error::parse_failed
);
893 return Error::success();
896 Error
WasmObjectFile::parseImportSection(ReadContext
&Ctx
) {
897 uint32_t Count
= readVaruint32(Ctx
);
898 Imports
.reserve(Count
);
899 for (uint32_t I
= 0; I
< Count
; I
++) {
901 Im
.Module
= readString(Ctx
);
902 Im
.Field
= readString(Ctx
);
903 Im
.Kind
= readUint8(Ctx
);
905 case wasm::WASM_EXTERNAL_FUNCTION
:
906 NumImportedFunctions
++;
907 Im
.SigIndex
= readVaruint32(Ctx
);
909 case wasm::WASM_EXTERNAL_GLOBAL
:
910 NumImportedGlobals
++;
911 Im
.Global
.Type
= readUint8(Ctx
);
912 Im
.Global
.Mutable
= readVaruint1(Ctx
);
914 case wasm::WASM_EXTERNAL_MEMORY
:
915 Im
.Memory
= readLimits(Ctx
);
917 case wasm::WASM_EXTERNAL_TABLE
:
918 Im
.Table
= readTable(Ctx
);
919 if (Im
.Table
.ElemType
!= wasm::WASM_TYPE_FUNCREF
)
920 return make_error
<GenericBinaryError
>("Invalid table element type",
921 object_error::parse_failed
);
923 case wasm::WASM_EXTERNAL_EVENT
:
925 Im
.Event
.Attribute
= readVarint32(Ctx
);
926 Im
.Event
.SigIndex
= readVarint32(Ctx
);
929 return make_error
<GenericBinaryError
>("Unexpected import kind",
930 object_error::parse_failed
);
932 Imports
.push_back(Im
);
934 if (Ctx
.Ptr
!= Ctx
.End
)
935 return make_error
<GenericBinaryError
>("Import section ended prematurely",
936 object_error::parse_failed
);
937 return Error::success();
940 Error
WasmObjectFile::parseFunctionSection(ReadContext
&Ctx
) {
941 uint32_t Count
= readVaruint32(Ctx
);
942 FunctionTypes
.reserve(Count
);
943 uint32_t NumTypes
= Signatures
.size();
945 uint32_t Type
= readVaruint32(Ctx
);
946 if (Type
>= NumTypes
)
947 return make_error
<GenericBinaryError
>("Invalid function type",
948 object_error::parse_failed
);
949 FunctionTypes
.push_back(Type
);
951 if (Ctx
.Ptr
!= Ctx
.End
)
952 return make_error
<GenericBinaryError
>("Function section ended prematurely",
953 object_error::parse_failed
);
954 return Error::success();
957 Error
WasmObjectFile::parseTableSection(ReadContext
&Ctx
) {
958 uint32_t Count
= readVaruint32(Ctx
);
959 Tables
.reserve(Count
);
961 Tables
.push_back(readTable(Ctx
));
962 if (Tables
.back().ElemType
!= wasm::WASM_TYPE_FUNCREF
) {
963 return make_error
<GenericBinaryError
>("Invalid table element type",
964 object_error::parse_failed
);
967 if (Ctx
.Ptr
!= Ctx
.End
)
968 return make_error
<GenericBinaryError
>("Table section ended prematurely",
969 object_error::parse_failed
);
970 return Error::success();
973 Error
WasmObjectFile::parseMemorySection(ReadContext
&Ctx
) {
974 uint32_t Count
= readVaruint32(Ctx
);
975 Memories
.reserve(Count
);
977 Memories
.push_back(readLimits(Ctx
));
979 if (Ctx
.Ptr
!= Ctx
.End
)
980 return make_error
<GenericBinaryError
>("Memory section ended prematurely",
981 object_error::parse_failed
);
982 return Error::success();
985 Error
WasmObjectFile::parseGlobalSection(ReadContext
&Ctx
) {
986 GlobalSection
= Sections
.size();
987 uint32_t Count
= readVaruint32(Ctx
);
988 Globals
.reserve(Count
);
990 wasm::WasmGlobal Global
;
991 Global
.Index
= NumImportedGlobals
+ Globals
.size();
992 Global
.Type
.Type
= readUint8(Ctx
);
993 Global
.Type
.Mutable
= readVaruint1(Ctx
);
994 if (Error Err
= readInitExpr(Global
.InitExpr
, Ctx
))
996 Globals
.push_back(Global
);
998 if (Ctx
.Ptr
!= Ctx
.End
)
999 return make_error
<GenericBinaryError
>("Global section ended prematurely",
1000 object_error::parse_failed
);
1001 return Error::success();
1004 Error
WasmObjectFile::parseEventSection(ReadContext
&Ctx
) {
1005 EventSection
= Sections
.size();
1006 uint32_t Count
= readVarint32(Ctx
);
1007 Events
.reserve(Count
);
1009 wasm::WasmEvent Event
;
1010 Event
.Index
= NumImportedEvents
+ Events
.size();
1011 Event
.Type
.Attribute
= readVaruint32(Ctx
);
1012 Event
.Type
.SigIndex
= readVarint32(Ctx
);
1013 Events
.push_back(Event
);
1016 if (Ctx
.Ptr
!= Ctx
.End
)
1017 return make_error
<GenericBinaryError
>("Event section ended prematurely",
1018 object_error::parse_failed
);
1019 return Error::success();
1022 Error
WasmObjectFile::parseExportSection(ReadContext
&Ctx
) {
1023 uint32_t Count
= readVaruint32(Ctx
);
1024 Exports
.reserve(Count
);
1025 for (uint32_t I
= 0; I
< Count
; I
++) {
1026 wasm::WasmExport Ex
;
1027 Ex
.Name
= readString(Ctx
);
1028 Ex
.Kind
= readUint8(Ctx
);
1029 Ex
.Index
= readVaruint32(Ctx
);
1031 case wasm::WASM_EXTERNAL_FUNCTION
:
1032 if (!isValidFunctionIndex(Ex
.Index
))
1033 return make_error
<GenericBinaryError
>("Invalid function export",
1034 object_error::parse_failed
);
1036 case wasm::WASM_EXTERNAL_GLOBAL
:
1037 if (!isValidGlobalIndex(Ex
.Index
))
1038 return make_error
<GenericBinaryError
>("Invalid global export",
1039 object_error::parse_failed
);
1041 case wasm::WASM_EXTERNAL_EVENT
:
1042 if (!isValidEventIndex(Ex
.Index
))
1043 return make_error
<GenericBinaryError
>("Invalid event export",
1044 object_error::parse_failed
);
1046 case wasm::WASM_EXTERNAL_MEMORY
:
1047 case wasm::WASM_EXTERNAL_TABLE
:
1050 return make_error
<GenericBinaryError
>("Unexpected export kind",
1051 object_error::parse_failed
);
1053 Exports
.push_back(Ex
);
1055 if (Ctx
.Ptr
!= Ctx
.End
)
1056 return make_error
<GenericBinaryError
>("Export section ended prematurely",
1057 object_error::parse_failed
);
1058 return Error::success();
1061 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index
) const {
1062 return Index
< NumImportedFunctions
+ FunctionTypes
.size();
1065 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index
) const {
1066 return Index
>= NumImportedFunctions
&& isValidFunctionIndex(Index
);
1069 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index
) const {
1070 return Index
< NumImportedGlobals
+ Globals
.size();
1073 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index
) const {
1074 return Index
>= NumImportedGlobals
&& isValidGlobalIndex(Index
);
1077 bool WasmObjectFile::isValidEventIndex(uint32_t Index
) const {
1078 return Index
< NumImportedEvents
+ Events
.size();
1081 bool WasmObjectFile::isDefinedEventIndex(uint32_t Index
) const {
1082 return Index
>= NumImportedEvents
&& isValidEventIndex(Index
);
1085 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index
) const {
1086 return Index
< Symbols
.size() && Symbols
[Index
].isTypeFunction();
1089 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index
) const {
1090 return Index
< Symbols
.size() && Symbols
[Index
].isTypeGlobal();
1093 bool WasmObjectFile::isValidEventSymbol(uint32_t Index
) const {
1094 return Index
< Symbols
.size() && Symbols
[Index
].isTypeEvent();
1097 bool WasmObjectFile::isValidDataSymbol(uint32_t Index
) const {
1098 return Index
< Symbols
.size() && Symbols
[Index
].isTypeData();
1101 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index
) const {
1102 return Index
< Symbols
.size() && Symbols
[Index
].isTypeSection();
1105 wasm::WasmFunction
&WasmObjectFile::getDefinedFunction(uint32_t Index
) {
1106 assert(isDefinedFunctionIndex(Index
));
1107 return Functions
[Index
- NumImportedFunctions
];
1110 const wasm::WasmFunction
&
1111 WasmObjectFile::getDefinedFunction(uint32_t Index
) const {
1112 assert(isDefinedFunctionIndex(Index
));
1113 return Functions
[Index
- NumImportedFunctions
];
1116 wasm::WasmGlobal
&WasmObjectFile::getDefinedGlobal(uint32_t Index
) {
1117 assert(isDefinedGlobalIndex(Index
));
1118 return Globals
[Index
- NumImportedGlobals
];
1121 wasm::WasmEvent
&WasmObjectFile::getDefinedEvent(uint32_t Index
) {
1122 assert(isDefinedEventIndex(Index
));
1123 return Events
[Index
- NumImportedEvents
];
1126 Error
WasmObjectFile::parseStartSection(ReadContext
&Ctx
) {
1127 StartFunction
= readVaruint32(Ctx
);
1128 if (!isValidFunctionIndex(StartFunction
))
1129 return make_error
<GenericBinaryError
>("Invalid start function",
1130 object_error::parse_failed
);
1131 return Error::success();
1134 Error
WasmObjectFile::parseCodeSection(ReadContext
&Ctx
) {
1135 CodeSection
= Sections
.size();
1136 uint32_t FunctionCount
= readVaruint32(Ctx
);
1137 if (FunctionCount
!= FunctionTypes
.size()) {
1138 return make_error
<GenericBinaryError
>("Invalid function count",
1139 object_error::parse_failed
);
1142 while (FunctionCount
--) {
1143 wasm::WasmFunction Function
;
1144 const uint8_t *FunctionStart
= Ctx
.Ptr
;
1145 uint32_t Size
= readVaruint32(Ctx
);
1146 const uint8_t *FunctionEnd
= Ctx
.Ptr
+ Size
;
1148 Function
.CodeOffset
= Ctx
.Ptr
- FunctionStart
;
1149 Function
.Index
= NumImportedFunctions
+ Functions
.size();
1150 Function
.CodeSectionOffset
= FunctionStart
- Ctx
.Start
;
1151 Function
.Size
= FunctionEnd
- FunctionStart
;
1153 uint32_t NumLocalDecls
= readVaruint32(Ctx
);
1154 Function
.Locals
.reserve(NumLocalDecls
);
1155 while (NumLocalDecls
--) {
1156 wasm::WasmLocalDecl Decl
;
1157 Decl
.Count
= readVaruint32(Ctx
);
1158 Decl
.Type
= readUint8(Ctx
);
1159 Function
.Locals
.push_back(Decl
);
1162 uint32_t BodySize
= FunctionEnd
- Ctx
.Ptr
;
1163 Function
.Body
= ArrayRef
<uint8_t>(Ctx
.Ptr
, BodySize
);
1164 // This will be set later when reading in the linking metadata section.
1165 Function
.Comdat
= UINT32_MAX
;
1166 Ctx
.Ptr
+= BodySize
;
1167 assert(Ctx
.Ptr
== FunctionEnd
);
1168 Functions
.push_back(Function
);
1170 if (Ctx
.Ptr
!= Ctx
.End
)
1171 return make_error
<GenericBinaryError
>("Code section ended prematurely",
1172 object_error::parse_failed
);
1173 return Error::success();
1176 Error
WasmObjectFile::parseElemSection(ReadContext
&Ctx
) {
1177 uint32_t Count
= readVaruint32(Ctx
);
1178 ElemSegments
.reserve(Count
);
1180 wasm::WasmElemSegment Segment
;
1181 Segment
.TableIndex
= readVaruint32(Ctx
);
1182 if (Segment
.TableIndex
!= 0) {
1183 return make_error
<GenericBinaryError
>("Invalid TableIndex",
1184 object_error::parse_failed
);
1186 if (Error Err
= readInitExpr(Segment
.Offset
, Ctx
))
1188 uint32_t NumElems
= readVaruint32(Ctx
);
1189 while (NumElems
--) {
1190 Segment
.Functions
.push_back(readVaruint32(Ctx
));
1192 ElemSegments
.push_back(Segment
);
1194 if (Ctx
.Ptr
!= Ctx
.End
)
1195 return make_error
<GenericBinaryError
>("Elem section ended prematurely",
1196 object_error::parse_failed
);
1197 return Error::success();
1200 Error
WasmObjectFile::parseDataSection(ReadContext
&Ctx
) {
1201 DataSection
= Sections
.size();
1202 uint32_t Count
= readVaruint32(Ctx
);
1203 if (DataCount
&& Count
!= DataCount
.getValue())
1204 return make_error
<GenericBinaryError
>(
1205 "Number of data segments does not match DataCount section");
1206 DataSegments
.reserve(Count
);
1208 WasmSegment Segment
;
1209 Segment
.Data
.InitFlags
= readVaruint32(Ctx
);
1210 Segment
.Data
.MemoryIndex
= (Segment
.Data
.InitFlags
& wasm::WASM_SEGMENT_HAS_MEMINDEX
)
1211 ? readVaruint32(Ctx
) : 0;
1212 if ((Segment
.Data
.InitFlags
& wasm::WASM_SEGMENT_IS_PASSIVE
) == 0) {
1213 if (Error Err
= readInitExpr(Segment
.Data
.Offset
, Ctx
))
1216 Segment
.Data
.Offset
.Opcode
= wasm::WASM_OPCODE_I32_CONST
;
1217 Segment
.Data
.Offset
.Value
.Int32
= 0;
1219 uint32_t Size
= readVaruint32(Ctx
);
1220 if (Size
> (size_t)(Ctx
.End
- Ctx
.Ptr
))
1221 return make_error
<GenericBinaryError
>("Invalid segment size",
1222 object_error::parse_failed
);
1223 Segment
.Data
.Content
= ArrayRef
<uint8_t>(Ctx
.Ptr
, Size
);
1224 // The rest of these Data fields are set later, when reading in the linking
1225 // metadata section.
1226 Segment
.Data
.Alignment
= 0;
1227 Segment
.Data
.LinkerFlags
= 0;
1228 Segment
.Data
.Comdat
= UINT32_MAX
;
1229 Segment
.SectionOffset
= Ctx
.Ptr
- Ctx
.Start
;
1231 DataSegments
.push_back(Segment
);
1233 if (Ctx
.Ptr
!= Ctx
.End
)
1234 return make_error
<GenericBinaryError
>("Data section ended prematurely",
1235 object_error::parse_failed
);
1236 return Error::success();
1239 Error
WasmObjectFile::parseDataCountSection(ReadContext
&Ctx
) {
1240 DataCount
= readVaruint32(Ctx
);
1241 return Error::success();
1244 const wasm::WasmObjectHeader
&WasmObjectFile::getHeader() const {
1248 void WasmObjectFile::moveSymbolNext(DataRefImpl
&Symb
) const { Symb
.d
.b
++; }
1250 uint32_t WasmObjectFile::getSymbolFlags(DataRefImpl Symb
) const {
1251 uint32_t Result
= SymbolRef::SF_None
;
1252 const WasmSymbol
&Sym
= getWasmSymbol(Symb
);
1254 LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym
<< " " << Sym
<< "\n");
1255 if (Sym
.isBindingWeak())
1256 Result
|= SymbolRef::SF_Weak
;
1257 if (!Sym
.isBindingLocal())
1258 Result
|= SymbolRef::SF_Global
;
1260 Result
|= SymbolRef::SF_Hidden
;
1261 if (!Sym
.isDefined())
1262 Result
|= SymbolRef::SF_Undefined
;
1263 if (Sym
.isTypeFunction())
1264 Result
|= SymbolRef::SF_Executable
;
1268 basic_symbol_iterator
WasmObjectFile::symbol_begin() const {
1270 Ref
.d
.a
= 1; // Arbitrary non-zero value so that Ref.p is non-null
1271 Ref
.d
.b
= 0; // Symbol index
1272 return BasicSymbolRef(Ref
, this);
1275 basic_symbol_iterator
WasmObjectFile::symbol_end() const {
1277 Ref
.d
.a
= 1; // Arbitrary non-zero value so that Ref.p is non-null
1278 Ref
.d
.b
= Symbols
.size(); // Symbol index
1279 return BasicSymbolRef(Ref
, this);
1282 const WasmSymbol
&WasmObjectFile::getWasmSymbol(const DataRefImpl
&Symb
) const {
1283 return Symbols
[Symb
.d
.b
];
1286 const WasmSymbol
&WasmObjectFile::getWasmSymbol(const SymbolRef
&Symb
) const {
1287 return getWasmSymbol(Symb
.getRawDataRefImpl());
1290 Expected
<StringRef
> WasmObjectFile::getSymbolName(DataRefImpl Symb
) const {
1291 return getWasmSymbol(Symb
).Info
.Name
;
1294 Expected
<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb
) const {
1295 auto &Sym
= getWasmSymbol(Symb
);
1296 if (Sym
.Info
.Kind
== wasm::WASM_SYMBOL_TYPE_FUNCTION
&&
1297 isDefinedFunctionIndex(Sym
.Info
.ElementIndex
))
1298 return getDefinedFunction(Sym
.Info
.ElementIndex
).CodeSectionOffset
;
1300 return getSymbolValue(Symb
);
1303 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol
&Sym
) const {
1304 switch (Sym
.Info
.Kind
) {
1305 case wasm::WASM_SYMBOL_TYPE_FUNCTION
:
1306 case wasm::WASM_SYMBOL_TYPE_GLOBAL
:
1307 case wasm::WASM_SYMBOL_TYPE_EVENT
:
1308 return Sym
.Info
.ElementIndex
;
1309 case wasm::WASM_SYMBOL_TYPE_DATA
: {
1310 // The value of a data symbol is the segment offset, plus the symbol
1311 // offset within the segment.
1312 uint32_t SegmentIndex
= Sym
.Info
.DataRef
.Segment
;
1313 const wasm::WasmDataSegment
&Segment
= DataSegments
[SegmentIndex
].Data
;
1314 assert(Segment
.Offset
.Opcode
== wasm::WASM_OPCODE_I32_CONST
);
1315 return Segment
.Offset
.Value
.Int32
+ Sym
.Info
.DataRef
.Offset
;
1317 case wasm::WASM_SYMBOL_TYPE_SECTION
:
1320 llvm_unreachable("invalid symbol type");
1323 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb
) const {
1324 return getWasmSymbolValue(getWasmSymbol(Symb
));
1327 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb
) const {
1328 llvm_unreachable("not yet implemented");
1332 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb
) const {
1333 llvm_unreachable("not yet implemented");
1337 Expected
<SymbolRef::Type
>
1338 WasmObjectFile::getSymbolType(DataRefImpl Symb
) const {
1339 const WasmSymbol
&Sym
= getWasmSymbol(Symb
);
1341 switch (Sym
.Info
.Kind
) {
1342 case wasm::WASM_SYMBOL_TYPE_FUNCTION
:
1343 return SymbolRef::ST_Function
;
1344 case wasm::WASM_SYMBOL_TYPE_GLOBAL
:
1345 return SymbolRef::ST_Other
;
1346 case wasm::WASM_SYMBOL_TYPE_DATA
:
1347 return SymbolRef::ST_Data
;
1348 case wasm::WASM_SYMBOL_TYPE_SECTION
:
1349 return SymbolRef::ST_Debug
;
1350 case wasm::WASM_SYMBOL_TYPE_EVENT
:
1351 return SymbolRef::ST_Other
;
1354 llvm_unreachable("Unknown WasmSymbol::SymbolType");
1355 return SymbolRef::ST_Other
;
1358 Expected
<section_iterator
>
1359 WasmObjectFile::getSymbolSection(DataRefImpl Symb
) const {
1360 const WasmSymbol
&Sym
= getWasmSymbol(Symb
);
1361 if (Sym
.isUndefined())
1362 return section_end();
1365 switch (Sym
.Info
.Kind
) {
1366 case wasm::WASM_SYMBOL_TYPE_FUNCTION
:
1367 Ref
.d
.a
= CodeSection
;
1369 case wasm::WASM_SYMBOL_TYPE_GLOBAL
:
1370 Ref
.d
.a
= GlobalSection
;
1372 case wasm::WASM_SYMBOL_TYPE_DATA
:
1373 Ref
.d
.a
= DataSection
;
1375 case wasm::WASM_SYMBOL_TYPE_SECTION
:
1376 Ref
.d
.a
= Sym
.Info
.ElementIndex
;
1378 case wasm::WASM_SYMBOL_TYPE_EVENT
:
1379 Ref
.d
.a
= EventSection
;
1382 llvm_unreachable("Unknown WasmSymbol::SymbolType");
1384 return section_iterator(SectionRef(Ref
, this));
1387 void WasmObjectFile::moveSectionNext(DataRefImpl
&Sec
) const { Sec
.d
.a
++; }
1389 Expected
<StringRef
> WasmObjectFile::getSectionName(DataRefImpl Sec
) const {
1390 const WasmSection
&S
= Sections
[Sec
.d
.a
];
1392 case wasm::WASM_SEC_##X: \
1408 case wasm::WASM_SEC_CUSTOM
:
1411 return createStringError(object_error::invalid_section_index
, "");
1416 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec
) const { return 0; }
1418 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec
) const {
1422 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec
) const {
1423 const WasmSection
&S
= Sections
[Sec
.d
.a
];
1424 return S
.Content
.size();
1427 Expected
<ArrayRef
<uint8_t>>
1428 WasmObjectFile::getSectionContents(DataRefImpl Sec
) const {
1429 const WasmSection
&S
= Sections
[Sec
.d
.a
];
1430 // This will never fail since wasm sections can never be empty (user-sections
1431 // must have a name and non-user sections each have a defined structure).
1435 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec
) const {
1439 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec
) const {
1443 bool WasmObjectFile::isSectionText(DataRefImpl Sec
) const {
1444 return getWasmSection(Sec
).Type
== wasm::WASM_SEC_CODE
;
1447 bool WasmObjectFile::isSectionData(DataRefImpl Sec
) const {
1448 return getWasmSection(Sec
).Type
== wasm::WASM_SEC_DATA
;
1451 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec
) const { return false; }
1453 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec
) const { return false; }
1455 bool WasmObjectFile::isSectionBitcode(DataRefImpl Sec
) const { return false; }
1457 relocation_iterator
WasmObjectFile::section_rel_begin(DataRefImpl Ref
) const {
1458 DataRefImpl RelocRef
;
1459 RelocRef
.d
.a
= Ref
.d
.a
;
1461 return relocation_iterator(RelocationRef(RelocRef
, this));
1464 relocation_iterator
WasmObjectFile::section_rel_end(DataRefImpl Ref
) const {
1465 const WasmSection
&Sec
= getWasmSection(Ref
);
1466 DataRefImpl RelocRef
;
1467 RelocRef
.d
.a
= Ref
.d
.a
;
1468 RelocRef
.d
.b
= Sec
.Relocations
.size();
1469 return relocation_iterator(RelocationRef(RelocRef
, this));
1472 void WasmObjectFile::moveRelocationNext(DataRefImpl
&Rel
) const { Rel
.d
.b
++; }
1474 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref
) const {
1475 const wasm::WasmRelocation
&Rel
= getWasmRelocation(Ref
);
1479 symbol_iterator
WasmObjectFile::getRelocationSymbol(DataRefImpl Ref
) const {
1480 const wasm::WasmRelocation
&Rel
= getWasmRelocation(Ref
);
1481 if (Rel
.Type
== wasm::R_WASM_TYPE_INDEX_LEB
)
1482 return symbol_end();
1485 Sym
.d
.b
= Rel
.Index
;
1486 return symbol_iterator(SymbolRef(Sym
, this));
1489 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref
) const {
1490 const wasm::WasmRelocation
&Rel
= getWasmRelocation(Ref
);
1494 void WasmObjectFile::getRelocationTypeName(
1495 DataRefImpl Ref
, SmallVectorImpl
<char> &Result
) const {
1496 const wasm::WasmRelocation
&Rel
= getWasmRelocation(Ref
);
1497 StringRef Res
= "Unknown";
1499 #define WASM_RELOC(name, value) \
1505 #include "llvm/BinaryFormat/WasmRelocs.def"
1510 Result
.append(Res
.begin(), Res
.end());
1513 section_iterator
WasmObjectFile::section_begin() const {
1516 return section_iterator(SectionRef(Ref
, this));
1519 section_iterator
WasmObjectFile::section_end() const {
1521 Ref
.d
.a
= Sections
.size();
1522 return section_iterator(SectionRef(Ref
, this));
1525 uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
1527 StringRef
WasmObjectFile::getFileFormatName() const { return "WASM"; }
1529 Triple::ArchType
WasmObjectFile::getArch() const { return Triple::wasm32
; }
1531 SubtargetFeatures
WasmObjectFile::getFeatures() const {
1532 return SubtargetFeatures();
1535 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection
; }
1537 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection
; }
1539 const WasmSection
&WasmObjectFile::getWasmSection(DataRefImpl Ref
) const {
1540 assert(Ref
.d
.a
< Sections
.size());
1541 return Sections
[Ref
.d
.a
];
1545 WasmObjectFile::getWasmSection(const SectionRef
&Section
) const {
1546 return getWasmSection(Section
.getRawDataRefImpl());
1549 const wasm::WasmRelocation
&
1550 WasmObjectFile::getWasmRelocation(const RelocationRef
&Ref
) const {
1551 return getWasmRelocation(Ref
.getRawDataRefImpl());
1554 const wasm::WasmRelocation
&
1555 WasmObjectFile::getWasmRelocation(DataRefImpl Ref
) const {
1556 assert(Ref
.d
.a
< Sections
.size());
1557 const WasmSection
&Sec
= Sections
[Ref
.d
.a
];
1558 assert(Ref
.d
.b
< Sec
.Relocations
.size());
1559 return Sec
.Relocations
[Ref
.d
.b
];
1562 int WasmSectionOrderChecker::getSectionOrder(unsigned ID
,
1563 StringRef CustomSectionName
) {
1565 case wasm::WASM_SEC_CUSTOM
:
1566 return StringSwitch
<unsigned>(CustomSectionName
)
1567 .Case("dylink", WASM_SEC_ORDER_DYLINK
)
1568 .Case("linking", WASM_SEC_ORDER_LINKING
)
1569 .StartsWith("reloc.", WASM_SEC_ORDER_RELOC
)
1570 .Case("name", WASM_SEC_ORDER_NAME
)
1571 .Case("producers", WASM_SEC_ORDER_PRODUCERS
)
1572 .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES
)
1573 .Default(WASM_SEC_ORDER_NONE
);
1574 case wasm::WASM_SEC_TYPE
:
1575 return WASM_SEC_ORDER_TYPE
;
1576 case wasm::WASM_SEC_IMPORT
:
1577 return WASM_SEC_ORDER_IMPORT
;
1578 case wasm::WASM_SEC_FUNCTION
:
1579 return WASM_SEC_ORDER_FUNCTION
;
1580 case wasm::WASM_SEC_TABLE
:
1581 return WASM_SEC_ORDER_TABLE
;
1582 case wasm::WASM_SEC_MEMORY
:
1583 return WASM_SEC_ORDER_MEMORY
;
1584 case wasm::WASM_SEC_GLOBAL
:
1585 return WASM_SEC_ORDER_GLOBAL
;
1586 case wasm::WASM_SEC_EXPORT
:
1587 return WASM_SEC_ORDER_EXPORT
;
1588 case wasm::WASM_SEC_START
:
1589 return WASM_SEC_ORDER_START
;
1590 case wasm::WASM_SEC_ELEM
:
1591 return WASM_SEC_ORDER_ELEM
;
1592 case wasm::WASM_SEC_CODE
:
1593 return WASM_SEC_ORDER_CODE
;
1594 case wasm::WASM_SEC_DATA
:
1595 return WASM_SEC_ORDER_DATA
;
1596 case wasm::WASM_SEC_DATACOUNT
:
1597 return WASM_SEC_ORDER_DATACOUNT
;
1598 case wasm::WASM_SEC_EVENT
:
1599 return WASM_SEC_ORDER_EVENT
;
1601 return WASM_SEC_ORDER_NONE
;
1605 // Represents the edges in a directed graph where any node B reachable from node
1606 // A is not allowed to appear before A in the section ordering, but may appear
1608 int WasmSectionOrderChecker::DisallowedPredecessors
[WASM_NUM_SEC_ORDERS
][WASM_NUM_SEC_ORDERS
] = {
1609 {}, // WASM_SEC_ORDER_NONE
1610 {WASM_SEC_ORDER_TYPE
, WASM_SEC_ORDER_IMPORT
}, // WASM_SEC_ORDER_TYPE,
1611 {WASM_SEC_ORDER_IMPORT
, WASM_SEC_ORDER_FUNCTION
}, // WASM_SEC_ORDER_IMPORT,
1612 {WASM_SEC_ORDER_FUNCTION
, WASM_SEC_ORDER_TABLE
}, // WASM_SEC_ORDER_FUNCTION,
1613 {WASM_SEC_ORDER_TABLE
, WASM_SEC_ORDER_MEMORY
}, // WASM_SEC_ORDER_TABLE,
1614 {WASM_SEC_ORDER_MEMORY
, WASM_SEC_ORDER_GLOBAL
}, // WASM_SEC_ORDER_MEMORY,
1615 {WASM_SEC_ORDER_GLOBAL
, WASM_SEC_ORDER_EVENT
}, // WASM_SEC_ORDER_GLOBAL,
1616 {WASM_SEC_ORDER_EVENT
, WASM_SEC_ORDER_EXPORT
}, // WASM_SEC_ORDER_EVENT,
1617 {WASM_SEC_ORDER_EXPORT
, WASM_SEC_ORDER_START
}, // WASM_SEC_ORDER_EXPORT,
1618 {WASM_SEC_ORDER_START
, WASM_SEC_ORDER_ELEM
}, // WASM_SEC_ORDER_START,
1619 {WASM_SEC_ORDER_ELEM
, WASM_SEC_ORDER_DATACOUNT
}, // WASM_SEC_ORDER_ELEM,
1620 {WASM_SEC_ORDER_DATACOUNT
, WASM_SEC_ORDER_CODE
}, // WASM_SEC_ORDER_DATACOUNT,
1621 {WASM_SEC_ORDER_CODE
, WASM_SEC_ORDER_DATA
}, // WASM_SEC_ORDER_CODE,
1622 {WASM_SEC_ORDER_DATA
, WASM_SEC_ORDER_LINKING
}, // WASM_SEC_ORDER_DATA,
1625 {WASM_SEC_ORDER_DYLINK
, WASM_SEC_ORDER_TYPE
}, // WASM_SEC_ORDER_DYLINK,
1626 {WASM_SEC_ORDER_LINKING
, WASM_SEC_ORDER_RELOC
, WASM_SEC_ORDER_NAME
}, // WASM_SEC_ORDER_LINKING,
1627 {}, // WASM_SEC_ORDER_RELOC (can be repeated),
1628 {WASM_SEC_ORDER_NAME
, WASM_SEC_ORDER_PRODUCERS
}, // WASM_SEC_ORDER_NAME,
1629 {WASM_SEC_ORDER_PRODUCERS
, WASM_SEC_ORDER_TARGET_FEATURES
}, // WASM_SEC_ORDER_PRODUCERS,
1630 {WASM_SEC_ORDER_TARGET_FEATURES
} // WASM_SEC_ORDER_TARGET_FEATURES
1633 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID
,
1634 StringRef CustomSectionName
) {
1635 int Order
= getSectionOrder(ID
, CustomSectionName
);
1636 if (Order
== WASM_SEC_ORDER_NONE
)
1639 // Disallowed predecessors we need to check for
1640 SmallVector
<int, WASM_NUM_SEC_ORDERS
> WorkList
;
1642 // Keep track of completed checks to avoid repeating work
1643 bool Checked
[WASM_NUM_SEC_ORDERS
] = {};
1647 // Add new disallowed predecessors to work list
1648 for (size_t I
= 0;; ++I
) {
1649 int Next
= DisallowedPredecessors
[Curr
][I
];
1650 if (Next
== WASM_SEC_ORDER_NONE
)
1654 WorkList
.push_back(Next
);
1655 Checked
[Next
] = true;
1658 if (WorkList
.empty())
1661 // Consider next disallowed predecessor
1662 Curr
= WorkList
.pop_back_val();
1667 // Have not seen any disallowed predecessors