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