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