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