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