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