xref: /llvm-project/llvm/lib/Object/WasmObjectFile.cpp (revision 7f409cd82b322038f08a984a07377758e76b0e4c)
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   while (Ctx.Ptr < Ctx.End) {
512     uint8_t Type = readUint8(Ctx);
513     uint32_t Size = readVaruint32(Ctx);
514     const uint8_t *SubSectionEnd = Ctx.Ptr + Size;
515     switch (Type) {
516     case wasm::WASM_NAMES_FUNCTION:
517     case wasm::WASM_NAMES_GLOBAL:
518     case wasm::WASM_NAMES_DATA_SEGMENT: {
519       uint32_t Count = readVaruint32(Ctx);
520       while (Count--) {
521         uint32_t Index = readVaruint32(Ctx);
522         StringRef Name = readString(Ctx);
523         wasm::NameType nameType = wasm::NameType::FUNCTION;
524         if (Type == wasm::WASM_NAMES_FUNCTION) {
525           if (!SeenFunctions.insert(Index).second)
526             return make_error<GenericBinaryError>(
527                 "function named more than once", object_error::parse_failed);
528           if (!isValidFunctionIndex(Index) || Name.empty())
529             return make_error<GenericBinaryError>("invalid function name entry",
530                                                   object_error::parse_failed);
531 
532           if (isDefinedFunctionIndex(Index))
533             getDefinedFunction(Index).DebugName = Name;
534         } else if (Type == wasm::WASM_NAMES_GLOBAL) {
535           nameType = wasm::NameType::GLOBAL;
536           if (!SeenGlobals.insert(Index).second)
537             return make_error<GenericBinaryError>("global named more than once",
538                                                   object_error::parse_failed);
539           if (!isValidGlobalIndex(Index) || Name.empty())
540             return make_error<GenericBinaryError>("invalid global name entry",
541                                                   object_error::parse_failed);
542         } else {
543           nameType = wasm::NameType::DATA_SEGMENT;
544           if (!SeenSegments.insert(Index).second)
545             return make_error<GenericBinaryError>(
546                 "segment named more than once", object_error::parse_failed);
547           if (Index > DataSegments.size())
548             return make_error<GenericBinaryError>("invalid data segment name entry",
549                                                   object_error::parse_failed);
550         }
551         DebugNames.push_back(wasm::WasmDebugName{nameType, Index, Name});
552       }
553       break;
554     }
555     // Ignore local names for now
556     case wasm::WASM_NAMES_LOCAL:
557     default:
558       Ctx.Ptr += Size;
559       break;
560     }
561     if (Ctx.Ptr != SubSectionEnd)
562       return make_error<GenericBinaryError>(
563           "name sub-section ended prematurely", object_error::parse_failed);
564   }
565 
566   if (Ctx.Ptr != Ctx.End)
567     return make_error<GenericBinaryError>("name section ended prematurely",
568                                           object_error::parse_failed);
569   return Error::success();
570 }
571 
572 Error WasmObjectFile::parseLinkingSection(ReadContext &Ctx) {
573   HasLinkingSection = true;
574 
575   LinkingData.Version = readVaruint32(Ctx);
576   if (LinkingData.Version != wasm::WasmMetadataVersion) {
577     return make_error<GenericBinaryError>(
578         "unexpected metadata version: " + Twine(LinkingData.Version) +
579             " (Expected: " + Twine(wasm::WasmMetadataVersion) + ")",
580         object_error::parse_failed);
581   }
582 
583   const uint8_t *OrigEnd = Ctx.End;
584   while (Ctx.Ptr < OrigEnd) {
585     Ctx.End = OrigEnd;
586     uint8_t Type = readUint8(Ctx);
587     uint32_t Size = readVaruint32(Ctx);
588     LLVM_DEBUG(dbgs() << "readSubsection type=" << int(Type) << " size=" << Size
589                       << "\n");
590     Ctx.End = Ctx.Ptr + Size;
591     switch (Type) {
592     case wasm::WASM_SYMBOL_TABLE:
593       if (Error Err = parseLinkingSectionSymtab(Ctx))
594         return Err;
595       break;
596     case wasm::WASM_SEGMENT_INFO: {
597       uint32_t Count = readVaruint32(Ctx);
598       if (Count > DataSegments.size())
599         return make_error<GenericBinaryError>("too many segment names",
600                                               object_error::parse_failed);
601       for (uint32_t I = 0; I < Count; I++) {
602         DataSegments[I].Data.Name = readString(Ctx);
603         DataSegments[I].Data.Alignment = readVaruint32(Ctx);
604         DataSegments[I].Data.LinkingFlags = readVaruint32(Ctx);
605       }
606       break;
607     }
608     case wasm::WASM_INIT_FUNCS: {
609       uint32_t Count = readVaruint32(Ctx);
610       LinkingData.InitFunctions.reserve(Count);
611       for (uint32_t I = 0; I < Count; I++) {
612         wasm::WasmInitFunc Init;
613         Init.Priority = readVaruint32(Ctx);
614         Init.Symbol = readVaruint32(Ctx);
615         if (!isValidFunctionSymbol(Init.Symbol))
616           return make_error<GenericBinaryError>("invalid function symbol: " +
617                                                     Twine(Init.Symbol),
618                                                 object_error::parse_failed);
619         LinkingData.InitFunctions.emplace_back(Init);
620       }
621       break;
622     }
623     case wasm::WASM_COMDAT_INFO:
624       if (Error Err = parseLinkingSectionComdat(Ctx))
625         return Err;
626       break;
627     default:
628       Ctx.Ptr += Size;
629       break;
630     }
631     if (Ctx.Ptr != Ctx.End)
632       return make_error<GenericBinaryError>(
633           "linking sub-section ended prematurely", object_error::parse_failed);
634   }
635   if (Ctx.Ptr != OrigEnd)
636     return make_error<GenericBinaryError>("linking section ended prematurely",
637                                           object_error::parse_failed);
638   return Error::success();
639 }
640 
641 Error WasmObjectFile::parseLinkingSectionSymtab(ReadContext &Ctx) {
642   uint32_t Count = readVaruint32(Ctx);
643   // Clear out any symbol information that was derived from the exports
644   // section.
645   LinkingData.SymbolTable.clear();
646   Symbols.clear();
647   LinkingData.SymbolTable.reserve(Count);
648   Symbols.reserve(Count);
649   StringSet<> SymbolNames;
650 
651   std::vector<wasm::WasmImport *> ImportedGlobals;
652   std::vector<wasm::WasmImport *> ImportedFunctions;
653   std::vector<wasm::WasmImport *> ImportedTags;
654   std::vector<wasm::WasmImport *> ImportedTables;
655   ImportedGlobals.reserve(Imports.size());
656   ImportedFunctions.reserve(Imports.size());
657   ImportedTags.reserve(Imports.size());
658   ImportedTables.reserve(Imports.size());
659   for (auto &I : Imports) {
660     if (I.Kind == wasm::WASM_EXTERNAL_FUNCTION)
661       ImportedFunctions.emplace_back(&I);
662     else if (I.Kind == wasm::WASM_EXTERNAL_GLOBAL)
663       ImportedGlobals.emplace_back(&I);
664     else if (I.Kind == wasm::WASM_EXTERNAL_TAG)
665       ImportedTags.emplace_back(&I);
666     else if (I.Kind == wasm::WASM_EXTERNAL_TABLE)
667       ImportedTables.emplace_back(&I);
668   }
669 
670   while (Count--) {
671     wasm::WasmSymbolInfo Info;
672     const wasm::WasmSignature *Signature = nullptr;
673     const wasm::WasmGlobalType *GlobalType = nullptr;
674     const wasm::WasmTableType *TableType = nullptr;
675 
676     Info.Kind = readUint8(Ctx);
677     Info.Flags = readVaruint32(Ctx);
678     bool IsDefined = (Info.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0;
679 
680     switch (Info.Kind) {
681     case wasm::WASM_SYMBOL_TYPE_FUNCTION:
682       Info.ElementIndex = readVaruint32(Ctx);
683       if (!isValidFunctionIndex(Info.ElementIndex) ||
684           IsDefined != isDefinedFunctionIndex(Info.ElementIndex))
685         return make_error<GenericBinaryError>("invalid function symbol index",
686                                               object_error::parse_failed);
687       if (IsDefined) {
688         Info.Name = readString(Ctx);
689         unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
690         wasm::WasmFunction &Function = Functions[FuncIndex];
691         Signature = &Signatures[Function.SigIndex];
692         if (Function.SymbolName.empty())
693           Function.SymbolName = Info.Name;
694       } else {
695         wasm::WasmImport &Import = *ImportedFunctions[Info.ElementIndex];
696         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
697           Info.Name = readString(Ctx);
698           Info.ImportName = Import.Field;
699         } else {
700           Info.Name = Import.Field;
701         }
702         Signature = &Signatures[Import.SigIndex];
703         Info.ImportModule = Import.Module;
704       }
705       break;
706 
707     case wasm::WASM_SYMBOL_TYPE_GLOBAL:
708       Info.ElementIndex = readVaruint32(Ctx);
709       if (!isValidGlobalIndex(Info.ElementIndex) ||
710           IsDefined != isDefinedGlobalIndex(Info.ElementIndex))
711         return make_error<GenericBinaryError>("invalid global symbol index",
712                                               object_error::parse_failed);
713       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
714                             wasm::WASM_SYMBOL_BINDING_WEAK)
715         return make_error<GenericBinaryError>("undefined weak global symbol",
716                                               object_error::parse_failed);
717       if (IsDefined) {
718         Info.Name = readString(Ctx);
719         unsigned GlobalIndex = Info.ElementIndex - NumImportedGlobals;
720         wasm::WasmGlobal &Global = Globals[GlobalIndex];
721         GlobalType = &Global.Type;
722         if (Global.SymbolName.empty())
723           Global.SymbolName = Info.Name;
724       } else {
725         wasm::WasmImport &Import = *ImportedGlobals[Info.ElementIndex];
726         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
727           Info.Name = readString(Ctx);
728           Info.ImportName = Import.Field;
729         } else {
730           Info.Name = Import.Field;
731         }
732         GlobalType = &Import.Global;
733         Info.ImportModule = Import.Module;
734       }
735       break;
736 
737     case wasm::WASM_SYMBOL_TYPE_TABLE:
738       Info.ElementIndex = readVaruint32(Ctx);
739       if (!isValidTableNumber(Info.ElementIndex) ||
740           IsDefined != isDefinedTableNumber(Info.ElementIndex))
741         return make_error<GenericBinaryError>("invalid table symbol index",
742                                               object_error::parse_failed);
743       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
744                             wasm::WASM_SYMBOL_BINDING_WEAK)
745         return make_error<GenericBinaryError>("undefined weak table symbol",
746                                               object_error::parse_failed);
747       if (IsDefined) {
748         Info.Name = readString(Ctx);
749         unsigned TableNumber = Info.ElementIndex - NumImportedTables;
750         wasm::WasmTable &Table = Tables[TableNumber];
751         TableType = &Table.Type;
752         if (Table.SymbolName.empty())
753           Table.SymbolName = Info.Name;
754       } else {
755         wasm::WasmImport &Import = *ImportedTables[Info.ElementIndex];
756         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
757           Info.Name = readString(Ctx);
758           Info.ImportName = Import.Field;
759         } else {
760           Info.Name = Import.Field;
761         }
762         TableType = &Import.Table;
763         Info.ImportModule = Import.Module;
764       }
765       break;
766 
767     case wasm::WASM_SYMBOL_TYPE_DATA:
768       Info.Name = readString(Ctx);
769       if (IsDefined) {
770         auto Index = readVaruint32(Ctx);
771         auto Offset = readVaruint64(Ctx);
772         auto Size = readVaruint64(Ctx);
773         if (!(Info.Flags & wasm::WASM_SYMBOL_ABSOLUTE)) {
774           if (static_cast<size_t>(Index) >= DataSegments.size())
775             return make_error<GenericBinaryError>(
776                 "invalid data segment index: " + Twine(Index),
777                 object_error::parse_failed);
778           size_t SegmentSize = DataSegments[Index].Data.Content.size();
779           if (Offset > SegmentSize)
780             return make_error<GenericBinaryError>(
781                 "invalid data symbol offset: `" + Info.Name +
782                     "` (offset: " + Twine(Offset) +
783                     " segment size: " + Twine(SegmentSize) + ")",
784                 object_error::parse_failed);
785         }
786         Info.DataRef = wasm::WasmDataReference{Index, Offset, Size};
787       }
788       break;
789 
790     case wasm::WASM_SYMBOL_TYPE_SECTION: {
791       if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
792           wasm::WASM_SYMBOL_BINDING_LOCAL)
793         return make_error<GenericBinaryError>(
794             "section symbols must have local binding",
795             object_error::parse_failed);
796       Info.ElementIndex = readVaruint32(Ctx);
797       // Use somewhat unique section name as symbol name.
798       StringRef SectionName = Sections[Info.ElementIndex].Name;
799       Info.Name = SectionName;
800       break;
801     }
802 
803     case wasm::WASM_SYMBOL_TYPE_TAG: {
804       Info.ElementIndex = readVaruint32(Ctx);
805       if (!isValidTagIndex(Info.ElementIndex) ||
806           IsDefined != isDefinedTagIndex(Info.ElementIndex))
807         return make_error<GenericBinaryError>("invalid tag symbol index",
808                                               object_error::parse_failed);
809       if (!IsDefined && (Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) ==
810                             wasm::WASM_SYMBOL_BINDING_WEAK)
811         return make_error<GenericBinaryError>("undefined weak global symbol",
812                                               object_error::parse_failed);
813       if (IsDefined) {
814         Info.Name = readString(Ctx);
815         unsigned TagIndex = Info.ElementIndex - NumImportedTags;
816         wasm::WasmTag &Tag = Tags[TagIndex];
817         Signature = &Signatures[Tag.SigIndex];
818         if (Tag.SymbolName.empty())
819           Tag.SymbolName = Info.Name;
820 
821       } else {
822         wasm::WasmImport &Import = *ImportedTags[Info.ElementIndex];
823         if ((Info.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0) {
824           Info.Name = readString(Ctx);
825           Info.ImportName = Import.Field;
826         } else {
827           Info.Name = Import.Field;
828         }
829         Signature = &Signatures[Import.SigIndex];
830         Info.ImportModule = Import.Module;
831       }
832       break;
833     }
834 
835     default:
836       return make_error<GenericBinaryError>("invalid symbol type: " +
837                                                 Twine(unsigned(Info.Kind)),
838                                             object_error::parse_failed);
839     }
840 
841     if ((Info.Flags & wasm::WASM_SYMBOL_BINDING_MASK) !=
842             wasm::WASM_SYMBOL_BINDING_LOCAL &&
843         !SymbolNames.insert(Info.Name).second)
844       return make_error<GenericBinaryError>("duplicate symbol name " +
845                                                 Twine(Info.Name),
846                                             object_error::parse_failed);
847     LinkingData.SymbolTable.emplace_back(Info);
848     Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType, TableType,
849                          Signature);
850     LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
851   }
852 
853   return Error::success();
854 }
855 
856 Error WasmObjectFile::parseLinkingSectionComdat(ReadContext &Ctx) {
857   uint32_t ComdatCount = readVaruint32(Ctx);
858   StringSet<> ComdatSet;
859   for (unsigned ComdatIndex = 0; ComdatIndex < ComdatCount; ++ComdatIndex) {
860     StringRef Name = readString(Ctx);
861     if (Name.empty() || !ComdatSet.insert(Name).second)
862       return make_error<GenericBinaryError>("bad/duplicate COMDAT name " +
863                                                 Twine(Name),
864                                             object_error::parse_failed);
865     LinkingData.Comdats.emplace_back(Name);
866     uint32_t Flags = readVaruint32(Ctx);
867     if (Flags != 0)
868       return make_error<GenericBinaryError>("unsupported COMDAT flags",
869                                             object_error::parse_failed);
870 
871     uint32_t EntryCount = readVaruint32(Ctx);
872     while (EntryCount--) {
873       unsigned Kind = readVaruint32(Ctx);
874       unsigned Index = readVaruint32(Ctx);
875       switch (Kind) {
876       default:
877         return make_error<GenericBinaryError>("invalid COMDAT entry type",
878                                               object_error::parse_failed);
879       case wasm::WASM_COMDAT_DATA:
880         if (Index >= DataSegments.size())
881           return make_error<GenericBinaryError>(
882               "COMDAT data index out of range", object_error::parse_failed);
883         if (DataSegments[Index].Data.Comdat != UINT32_MAX)
884           return make_error<GenericBinaryError>("data segment in two COMDATs",
885                                                 object_error::parse_failed);
886         DataSegments[Index].Data.Comdat = ComdatIndex;
887         break;
888       case wasm::WASM_COMDAT_FUNCTION:
889         if (!isDefinedFunctionIndex(Index))
890           return make_error<GenericBinaryError>(
891               "COMDAT function index out of range", object_error::parse_failed);
892         if (getDefinedFunction(Index).Comdat != UINT32_MAX)
893           return make_error<GenericBinaryError>("function in two COMDATs",
894                                                 object_error::parse_failed);
895         getDefinedFunction(Index).Comdat = ComdatIndex;
896         break;
897       case wasm::WASM_COMDAT_SECTION:
898         if (Index >= Sections.size())
899           return make_error<GenericBinaryError>(
900               "COMDAT section index out of range", object_error::parse_failed);
901         if (Sections[Index].Type != wasm::WASM_SEC_CUSTOM)
902           return make_error<GenericBinaryError>(
903               "non-custom section in a COMDAT", object_error::parse_failed);
904         Sections[Index].Comdat = ComdatIndex;
905         break;
906       }
907     }
908   }
909   return Error::success();
910 }
911 
912 Error WasmObjectFile::parseProducersSection(ReadContext &Ctx) {
913   llvm::SmallSet<StringRef, 3> FieldsSeen;
914   uint32_t Fields = readVaruint32(Ctx);
915   for (size_t I = 0; I < Fields; ++I) {
916     StringRef FieldName = readString(Ctx);
917     if (!FieldsSeen.insert(FieldName).second)
918       return make_error<GenericBinaryError>(
919           "producers section does not have unique fields",
920           object_error::parse_failed);
921     std::vector<std::pair<std::string, std::string>> *ProducerVec = nullptr;
922     if (FieldName == "language") {
923       ProducerVec = &ProducerInfo.Languages;
924     } else if (FieldName == "processed-by") {
925       ProducerVec = &ProducerInfo.Tools;
926     } else if (FieldName == "sdk") {
927       ProducerVec = &ProducerInfo.SDKs;
928     } else {
929       return make_error<GenericBinaryError>(
930           "producers section field is not named one of language, processed-by, "
931           "or sdk",
932           object_error::parse_failed);
933     }
934     uint32_t ValueCount = readVaruint32(Ctx);
935     llvm::SmallSet<StringRef, 8> ProducersSeen;
936     for (size_t J = 0; J < ValueCount; ++J) {
937       StringRef Name = readString(Ctx);
938       StringRef Version = readString(Ctx);
939       if (!ProducersSeen.insert(Name).second) {
940         return make_error<GenericBinaryError>(
941             "producers section contains repeated producer",
942             object_error::parse_failed);
943       }
944       ProducerVec->emplace_back(std::string(Name), std::string(Version));
945     }
946   }
947   if (Ctx.Ptr != Ctx.End)
948     return make_error<GenericBinaryError>("producers section ended prematurely",
949                                           object_error::parse_failed);
950   return Error::success();
951 }
952 
953 Error WasmObjectFile::parseTargetFeaturesSection(ReadContext &Ctx) {
954   llvm::SmallSet<std::string, 8> FeaturesSeen;
955   uint32_t FeatureCount = readVaruint32(Ctx);
956   for (size_t I = 0; I < FeatureCount; ++I) {
957     wasm::WasmFeatureEntry Feature;
958     Feature.Prefix = readUint8(Ctx);
959     switch (Feature.Prefix) {
960     case wasm::WASM_FEATURE_PREFIX_USED:
961     case wasm::WASM_FEATURE_PREFIX_REQUIRED:
962     case wasm::WASM_FEATURE_PREFIX_DISALLOWED:
963       break;
964     default:
965       return make_error<GenericBinaryError>("unknown feature policy prefix",
966                                             object_error::parse_failed);
967     }
968     Feature.Name = std::string(readString(Ctx));
969     if (!FeaturesSeen.insert(Feature.Name).second)
970       return make_error<GenericBinaryError>(
971           "target features section contains repeated feature \"" +
972               Feature.Name + "\"",
973           object_error::parse_failed);
974     TargetFeatures.push_back(Feature);
975   }
976   if (Ctx.Ptr != Ctx.End)
977     return make_error<GenericBinaryError>(
978         "target features section ended prematurely",
979         object_error::parse_failed);
980   return Error::success();
981 }
982 
983 Error WasmObjectFile::parseRelocSection(StringRef Name, ReadContext &Ctx) {
984   uint32_t SectionIndex = readVaruint32(Ctx);
985   if (SectionIndex >= Sections.size())
986     return make_error<GenericBinaryError>("invalid section index",
987                                           object_error::parse_failed);
988   WasmSection &Section = Sections[SectionIndex];
989   uint32_t RelocCount = readVaruint32(Ctx);
990   uint32_t EndOffset = Section.Content.size();
991   uint32_t PreviousOffset = 0;
992   while (RelocCount--) {
993     wasm::WasmRelocation Reloc = {};
994     uint32_t type = readVaruint32(Ctx);
995     Reloc.Type = type;
996     Reloc.Offset = readVaruint32(Ctx);
997     if (Reloc.Offset < PreviousOffset)
998       return make_error<GenericBinaryError>("relocations not in offset order",
999                                             object_error::parse_failed);
1000     PreviousOffset = Reloc.Offset;
1001     Reloc.Index = readVaruint32(Ctx);
1002     switch (type) {
1003     case wasm::R_WASM_FUNCTION_INDEX_LEB:
1004     case wasm::R_WASM_FUNCTION_INDEX_I32:
1005     case wasm::R_WASM_TABLE_INDEX_SLEB:
1006     case wasm::R_WASM_TABLE_INDEX_SLEB64:
1007     case wasm::R_WASM_TABLE_INDEX_I32:
1008     case wasm::R_WASM_TABLE_INDEX_I64:
1009     case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
1010     case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
1011       if (!isValidFunctionSymbol(Reloc.Index))
1012         return make_error<GenericBinaryError>(
1013             "invalid relocation function index", object_error::parse_failed);
1014       break;
1015     case wasm::R_WASM_TABLE_NUMBER_LEB:
1016       if (!isValidTableSymbol(Reloc.Index))
1017         return make_error<GenericBinaryError>("invalid relocation table index",
1018                                               object_error::parse_failed);
1019       break;
1020     case wasm::R_WASM_TYPE_INDEX_LEB:
1021       if (Reloc.Index >= Signatures.size())
1022         return make_error<GenericBinaryError>("invalid relocation type index",
1023                                               object_error::parse_failed);
1024       break;
1025     case wasm::R_WASM_GLOBAL_INDEX_LEB:
1026       // R_WASM_GLOBAL_INDEX_LEB are can be used against function and data
1027       // symbols to refer to their GOT entries.
1028       if (!isValidGlobalSymbol(Reloc.Index) &&
1029           !isValidDataSymbol(Reloc.Index) &&
1030           !isValidFunctionSymbol(Reloc.Index))
1031         return make_error<GenericBinaryError>("invalid relocation global index",
1032                                               object_error::parse_failed);
1033       break;
1034     case wasm::R_WASM_GLOBAL_INDEX_I32:
1035       if (!isValidGlobalSymbol(Reloc.Index))
1036         return make_error<GenericBinaryError>("invalid relocation global index",
1037                                               object_error::parse_failed);
1038       break;
1039     case wasm::R_WASM_TAG_INDEX_LEB:
1040       if (!isValidTagSymbol(Reloc.Index))
1041         return make_error<GenericBinaryError>("invalid relocation tag index",
1042                                               object_error::parse_failed);
1043       break;
1044     case wasm::R_WASM_MEMORY_ADDR_LEB:
1045     case wasm::R_WASM_MEMORY_ADDR_SLEB:
1046     case wasm::R_WASM_MEMORY_ADDR_I32:
1047     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
1048     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
1049     case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
1050       if (!isValidDataSymbol(Reloc.Index))
1051         return make_error<GenericBinaryError>("invalid relocation data index",
1052                                               object_error::parse_failed);
1053       Reloc.Addend = readVarint32(Ctx);
1054       break;
1055     case wasm::R_WASM_MEMORY_ADDR_LEB64:
1056     case wasm::R_WASM_MEMORY_ADDR_SLEB64:
1057     case wasm::R_WASM_MEMORY_ADDR_I64:
1058     case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
1059     case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
1060       if (!isValidDataSymbol(Reloc.Index))
1061         return make_error<GenericBinaryError>("invalid relocation data index",
1062                                               object_error::parse_failed);
1063       Reloc.Addend = readVarint64(Ctx);
1064       break;
1065     case wasm::R_WASM_FUNCTION_OFFSET_I32:
1066       if (!isValidFunctionSymbol(Reloc.Index))
1067         return make_error<GenericBinaryError>(
1068             "invalid relocation function index", object_error::parse_failed);
1069       Reloc.Addend = readVarint32(Ctx);
1070       break;
1071     case wasm::R_WASM_FUNCTION_OFFSET_I64:
1072       if (!isValidFunctionSymbol(Reloc.Index))
1073         return make_error<GenericBinaryError>(
1074             "invalid relocation function index", object_error::parse_failed);
1075       Reloc.Addend = readVarint64(Ctx);
1076       break;
1077     case wasm::R_WASM_SECTION_OFFSET_I32:
1078       if (!isValidSectionSymbol(Reloc.Index))
1079         return make_error<GenericBinaryError>(
1080             "invalid relocation section index", object_error::parse_failed);
1081       Reloc.Addend = readVarint32(Ctx);
1082       break;
1083     default:
1084       return make_error<GenericBinaryError>("invalid relocation type: " +
1085                                                 Twine(type),
1086                                             object_error::parse_failed);
1087     }
1088 
1089     // Relocations must fit inside the section, and must appear in order.  They
1090     // also shouldn't overlap a function/element boundary, but we don't bother
1091     // to check that.
1092     uint64_t Size = 5;
1093     if (Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LEB64 ||
1094         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_SLEB64 ||
1095         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_REL_SLEB64)
1096       Size = 10;
1097     if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I32 ||
1098         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I32 ||
1099         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_LOCREL_I32 ||
1100         Reloc.Type == wasm::R_WASM_SECTION_OFFSET_I32 ||
1101         Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
1102         Reloc.Type == wasm::R_WASM_FUNCTION_INDEX_I32 ||
1103         Reloc.Type == wasm::R_WASM_GLOBAL_INDEX_I32)
1104       Size = 4;
1105     if (Reloc.Type == wasm::R_WASM_TABLE_INDEX_I64 ||
1106         Reloc.Type == wasm::R_WASM_MEMORY_ADDR_I64 ||
1107         Reloc.Type == wasm::R_WASM_FUNCTION_OFFSET_I64)
1108       Size = 8;
1109     if (Reloc.Offset + Size > EndOffset)
1110       return make_error<GenericBinaryError>("invalid relocation offset",
1111                                             object_error::parse_failed);
1112 
1113     Section.Relocations.push_back(Reloc);
1114   }
1115   if (Ctx.Ptr != Ctx.End)
1116     return make_error<GenericBinaryError>("reloc section ended prematurely",
1117                                           object_error::parse_failed);
1118   return Error::success();
1119 }
1120 
1121 Error WasmObjectFile::parseCustomSection(WasmSection &Sec, ReadContext &Ctx) {
1122   if (Sec.Name == "dylink") {
1123     if (Error Err = parseDylinkSection(Ctx))
1124       return Err;
1125   } else if (Sec.Name == "dylink.0") {
1126     if (Error Err = parseDylink0Section(Ctx))
1127       return Err;
1128   } else if (Sec.Name == "name") {
1129     if (Error Err = parseNameSection(Ctx))
1130       return Err;
1131   } else if (Sec.Name == "linking") {
1132     if (Error Err = parseLinkingSection(Ctx))
1133       return Err;
1134   } else if (Sec.Name == "producers") {
1135     if (Error Err = parseProducersSection(Ctx))
1136       return Err;
1137   } else if (Sec.Name == "target_features") {
1138     if (Error Err = parseTargetFeaturesSection(Ctx))
1139       return Err;
1140   } else if (Sec.Name.starts_with("reloc.")) {
1141     if (Error Err = parseRelocSection(Sec.Name, Ctx))
1142       return Err;
1143   }
1144   return Error::success();
1145 }
1146 
1147 Error WasmObjectFile::parseTypeSection(ReadContext &Ctx) {
1148   auto parseFieldDef = [&]() {
1149     uint32_t TypeCode = readVaruint32((Ctx));
1150     /* Discard StorageType */ parseValType(Ctx, TypeCode);
1151     /* Discard Mutability */ readVaruint32(Ctx);
1152   };
1153 
1154   uint32_t Count = readVaruint32(Ctx);
1155   Signatures.reserve(Count);
1156   while (Count--) {
1157     wasm::WasmSignature Sig;
1158     uint8_t Form = readUint8(Ctx);
1159     if (Form == wasm::WASM_TYPE_REC) {
1160       // Rec groups expand the type index space (beyond what was declared at
1161       // the top of the section, and also consume one element in that space.
1162       uint32_t RecSize = readVaruint32(Ctx);
1163       if (RecSize == 0)
1164         return make_error<GenericBinaryError>("Rec group size cannot be 0",
1165                                               object_error::parse_failed);
1166       Signatures.reserve(Signatures.size() + RecSize);
1167       Count += RecSize;
1168       Sig.Kind = wasm::WasmSignature::Placeholder;
1169       Signatures.push_back(std::move(Sig));
1170       HasUnmodeledTypes = true;
1171       continue;
1172     }
1173     if (Form != wasm::WASM_TYPE_FUNC) {
1174       // Currently LLVM only models function types, and not other composite
1175       // types. Here we parse the type declarations just enough to skip past
1176       // them in the binary.
1177       if (Form == wasm::WASM_TYPE_SUB || Form == wasm::WASM_TYPE_SUB_FINAL) {
1178         uint32_t Supers = readVaruint32(Ctx);
1179         if (Supers > 0) {
1180           if (Supers != 1)
1181             return make_error<GenericBinaryError>(
1182                 "Invalid number of supertypes", object_error::parse_failed);
1183           /* Discard SuperIndex */ readVaruint32(Ctx);
1184         }
1185         Form = readVaruint32(Ctx);
1186       }
1187       if (Form == wasm::WASM_TYPE_STRUCT) {
1188         uint32_t FieldCount = readVaruint32(Ctx);
1189         while (FieldCount--) {
1190           parseFieldDef();
1191         }
1192       } else if (Form == wasm::WASM_TYPE_ARRAY) {
1193         parseFieldDef();
1194       } else {
1195         return make_error<GenericBinaryError>("bad form",
1196                                               object_error::parse_failed);
1197       }
1198       Sig.Kind = wasm::WasmSignature::Placeholder;
1199       Signatures.push_back(std::move(Sig));
1200       HasUnmodeledTypes = true;
1201       continue;
1202     }
1203 
1204     uint32_t ParamCount = readVaruint32(Ctx);
1205     Sig.Params.reserve(ParamCount);
1206     while (ParamCount--) {
1207       uint32_t ParamType = readUint8(Ctx);
1208       Sig.Params.push_back(parseValType(Ctx, ParamType));
1209       continue;
1210     }
1211     uint32_t ReturnCount = readVaruint32(Ctx);
1212     while (ReturnCount--) {
1213       uint32_t ReturnType = readUint8(Ctx);
1214       Sig.Returns.push_back(parseValType(Ctx, ReturnType));
1215     }
1216 
1217     Signatures.push_back(std::move(Sig));
1218   }
1219   if (Ctx.Ptr != Ctx.End)
1220     return make_error<GenericBinaryError>("type section ended prematurely",
1221                                           object_error::parse_failed);
1222   return Error::success();
1223 }
1224 
1225 Error WasmObjectFile::parseImportSection(ReadContext &Ctx) {
1226   uint32_t Count = readVaruint32(Ctx);
1227   uint32_t NumTypes = Signatures.size();
1228   Imports.reserve(Count);
1229   for (uint32_t I = 0; I < Count; I++) {
1230     wasm::WasmImport Im;
1231     Im.Module = readString(Ctx);
1232     Im.Field = readString(Ctx);
1233     Im.Kind = readUint8(Ctx);
1234     switch (Im.Kind) {
1235     case wasm::WASM_EXTERNAL_FUNCTION:
1236       NumImportedFunctions++;
1237       Im.SigIndex = readVaruint32(Ctx);
1238       if (Im.SigIndex >= NumTypes)
1239         return make_error<GenericBinaryError>("invalid function type",
1240                                               object_error::parse_failed);
1241       break;
1242     case wasm::WASM_EXTERNAL_GLOBAL:
1243       NumImportedGlobals++;
1244       Im.Global.Type = readUint8(Ctx);
1245       Im.Global.Mutable = readVaruint1(Ctx);
1246       break;
1247     case wasm::WASM_EXTERNAL_MEMORY:
1248       Im.Memory = readLimits(Ctx);
1249       if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
1250         HasMemory64 = true;
1251       break;
1252     case wasm::WASM_EXTERNAL_TABLE: {
1253       Im.Table = readTableType(Ctx);
1254       NumImportedTables++;
1255       auto ElemType = Im.Table.ElemType;
1256       if (ElemType != wasm::ValType::FUNCREF &&
1257           ElemType != wasm::ValType::EXTERNREF &&
1258           ElemType != wasm::ValType::OTHERREF)
1259         return make_error<GenericBinaryError>("invalid table element type",
1260                                               object_error::parse_failed);
1261       break;
1262     }
1263     case wasm::WASM_EXTERNAL_TAG:
1264       NumImportedTags++;
1265       if (readUint8(Ctx) != 0) // Reserved 'attribute' field
1266         return make_error<GenericBinaryError>("invalid attribute",
1267                                               object_error::parse_failed);
1268       Im.SigIndex = readVaruint32(Ctx);
1269       if (Im.SigIndex >= NumTypes)
1270         return make_error<GenericBinaryError>("invalid tag type",
1271                                               object_error::parse_failed);
1272       break;
1273     default:
1274       return make_error<GenericBinaryError>("unexpected import kind",
1275                                             object_error::parse_failed);
1276     }
1277     Imports.push_back(Im);
1278   }
1279   if (Ctx.Ptr != Ctx.End)
1280     return make_error<GenericBinaryError>("import section ended prematurely",
1281                                           object_error::parse_failed);
1282   return Error::success();
1283 }
1284 
1285 Error WasmObjectFile::parseFunctionSection(ReadContext &Ctx) {
1286   uint32_t Count = readVaruint32(Ctx);
1287   Functions.reserve(Count);
1288   uint32_t NumTypes = Signatures.size();
1289   while (Count--) {
1290     uint32_t Type = readVaruint32(Ctx);
1291     if (Type >= NumTypes)
1292       return make_error<GenericBinaryError>("invalid function type",
1293                                             object_error::parse_failed);
1294     wasm::WasmFunction F;
1295     F.SigIndex = Type;
1296     Functions.push_back(F);
1297   }
1298   if (Ctx.Ptr != Ctx.End)
1299     return make_error<GenericBinaryError>("function section ended prematurely",
1300                                           object_error::parse_failed);
1301   return Error::success();
1302 }
1303 
1304 Error WasmObjectFile::parseTableSection(ReadContext &Ctx) {
1305   TableSection = Sections.size();
1306   uint32_t Count = readVaruint32(Ctx);
1307   Tables.reserve(Count);
1308   while (Count--) {
1309     wasm::WasmTable T;
1310     T.Type = readTableType(Ctx);
1311     T.Index = NumImportedTables + Tables.size();
1312     Tables.push_back(T);
1313     auto ElemType = Tables.back().Type.ElemType;
1314     if (ElemType != wasm::ValType::FUNCREF &&
1315         ElemType != wasm::ValType::EXTERNREF &&
1316         ElemType != wasm::ValType::OTHERREF) {
1317       return make_error<GenericBinaryError>("invalid table element type",
1318                                             object_error::parse_failed);
1319     }
1320   }
1321   if (Ctx.Ptr != Ctx.End)
1322     return make_error<GenericBinaryError>("table section ended prematurely",
1323                                           object_error::parse_failed);
1324   return Error::success();
1325 }
1326 
1327 Error WasmObjectFile::parseMemorySection(ReadContext &Ctx) {
1328   uint32_t Count = readVaruint32(Ctx);
1329   Memories.reserve(Count);
1330   while (Count--) {
1331     auto Limits = readLimits(Ctx);
1332     if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
1333       HasMemory64 = true;
1334     Memories.push_back(Limits);
1335   }
1336   if (Ctx.Ptr != Ctx.End)
1337     return make_error<GenericBinaryError>("memory section ended prematurely",
1338                                           object_error::parse_failed);
1339   return Error::success();
1340 }
1341 
1342 Error WasmObjectFile::parseTagSection(ReadContext &Ctx) {
1343   TagSection = Sections.size();
1344   uint32_t Count = readVaruint32(Ctx);
1345   Tags.reserve(Count);
1346   uint32_t NumTypes = Signatures.size();
1347   while (Count--) {
1348     if (readUint8(Ctx) != 0) // Reserved 'attribute' field
1349       return make_error<GenericBinaryError>("invalid attribute",
1350                                             object_error::parse_failed);
1351     uint32_t Type = readVaruint32(Ctx);
1352     if (Type >= NumTypes)
1353       return make_error<GenericBinaryError>("invalid tag type",
1354                                             object_error::parse_failed);
1355     wasm::WasmTag Tag;
1356     Tag.Index = NumImportedTags + Tags.size();
1357     Tag.SigIndex = Type;
1358     Signatures[Type].Kind = wasm::WasmSignature::Tag;
1359     Tags.push_back(Tag);
1360   }
1361 
1362   if (Ctx.Ptr != Ctx.End)
1363     return make_error<GenericBinaryError>("tag section ended prematurely",
1364                                           object_error::parse_failed);
1365   return Error::success();
1366 }
1367 
1368 Error WasmObjectFile::parseGlobalSection(ReadContext &Ctx) {
1369   GlobalSection = Sections.size();
1370   uint32_t Count = readVaruint32(Ctx);
1371   Globals.reserve(Count);
1372   while (Count--) {
1373     wasm::WasmGlobal Global;
1374     Global.Index = NumImportedGlobals + Globals.size();
1375     auto GlobalOpcode = readVaruint32(Ctx);
1376     auto GlobalType = parseValType(Ctx, GlobalOpcode);
1377     // assert(GlobalType <= std::numeric_limits<wasm::ValType>::max());
1378     Global.Type.Type = (uint8_t)GlobalType;
1379     Global.Type.Mutable = readVaruint1(Ctx);
1380     if (Error Err = readInitExpr(Global.InitExpr, Ctx))
1381       return Err;
1382     Globals.push_back(Global);
1383   }
1384   if (Ctx.Ptr != Ctx.End)
1385     return make_error<GenericBinaryError>("global section ended prematurely",
1386                                           object_error::parse_failed);
1387   return Error::success();
1388 }
1389 
1390 Error WasmObjectFile::parseExportSection(ReadContext &Ctx) {
1391   uint32_t Count = readVaruint32(Ctx);
1392   Exports.reserve(Count);
1393   LinkingData.SymbolTable.reserve(Count);
1394   Symbols.reserve(Count);
1395   for (uint32_t I = 0; I < Count; I++) {
1396     wasm::WasmExport Ex;
1397     Ex.Name = readString(Ctx);
1398     Ex.Kind = readUint8(Ctx);
1399     Ex.Index = readVaruint32(Ctx);
1400     const wasm::WasmSignature *Signature = nullptr;
1401     const wasm::WasmGlobalType *GlobalType = nullptr;
1402     const wasm::WasmTableType *TableType = nullptr;
1403     wasm::WasmSymbolInfo Info;
1404     Info.Name = Ex.Name;
1405     Info.Flags = 0;
1406     switch (Ex.Kind) {
1407     case wasm::WASM_EXTERNAL_FUNCTION: {
1408       if (!isDefinedFunctionIndex(Ex.Index))
1409         return make_error<GenericBinaryError>("invalid function export",
1410                                               object_error::parse_failed);
1411       getDefinedFunction(Ex.Index).ExportName = Ex.Name;
1412       Info.Kind = wasm::WASM_SYMBOL_TYPE_FUNCTION;
1413       Info.ElementIndex = Ex.Index;
1414       unsigned FuncIndex = Info.ElementIndex - NumImportedFunctions;
1415       wasm::WasmFunction &Function = Functions[FuncIndex];
1416       Signature = &Signatures[Function.SigIndex];
1417       break;
1418     }
1419     case wasm::WASM_EXTERNAL_GLOBAL: {
1420       if (!isValidGlobalIndex(Ex.Index))
1421         return make_error<GenericBinaryError>("invalid global export",
1422                                               object_error::parse_failed);
1423       Info.Kind = wasm::WASM_SYMBOL_TYPE_DATA;
1424       uint64_t Offset = 0;
1425       if (isDefinedGlobalIndex(Ex.Index)) {
1426         auto Global = getDefinedGlobal(Ex.Index);
1427         if (!Global.InitExpr.Extended) {
1428           auto Inst = Global.InitExpr.Inst;
1429           if (Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) {
1430             Offset = Inst.Value.Int32;
1431           } else if (Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) {
1432             Offset = Inst.Value.Int64;
1433           }
1434         }
1435       }
1436       Info.DataRef = wasm::WasmDataReference{0, Offset, 0};
1437       break;
1438     }
1439     case wasm::WASM_EXTERNAL_TAG:
1440       if (!isValidTagIndex(Ex.Index))
1441         return make_error<GenericBinaryError>("invalid tag export",
1442                                               object_error::parse_failed);
1443       Info.Kind = wasm::WASM_SYMBOL_TYPE_TAG;
1444       Info.ElementIndex = Ex.Index;
1445       break;
1446     case wasm::WASM_EXTERNAL_MEMORY:
1447       break;
1448     case wasm::WASM_EXTERNAL_TABLE:
1449       Info.Kind = wasm::WASM_SYMBOL_TYPE_TABLE;
1450       Info.ElementIndex = Ex.Index;
1451       break;
1452     default:
1453       return make_error<GenericBinaryError>("unexpected export kind",
1454                                             object_error::parse_failed);
1455     }
1456     Exports.push_back(Ex);
1457     if (Ex.Kind != wasm::WASM_EXTERNAL_MEMORY) {
1458       LinkingData.SymbolTable.emplace_back(Info);
1459       Symbols.emplace_back(LinkingData.SymbolTable.back(), GlobalType,
1460                            TableType, Signature);
1461       LLVM_DEBUG(dbgs() << "Adding symbol: " << Symbols.back() << "\n");
1462     }
1463   }
1464   if (Ctx.Ptr != Ctx.End)
1465     return make_error<GenericBinaryError>("export section ended prematurely",
1466                                           object_error::parse_failed);
1467   return Error::success();
1468 }
1469 
1470 bool WasmObjectFile::isValidFunctionIndex(uint32_t Index) const {
1471   return Index < NumImportedFunctions + Functions.size();
1472 }
1473 
1474 bool WasmObjectFile::isDefinedFunctionIndex(uint32_t Index) const {
1475   return Index >= NumImportedFunctions && isValidFunctionIndex(Index);
1476 }
1477 
1478 bool WasmObjectFile::isValidGlobalIndex(uint32_t Index) const {
1479   return Index < NumImportedGlobals + Globals.size();
1480 }
1481 
1482 bool WasmObjectFile::isValidTableNumber(uint32_t Index) const {
1483   return Index < NumImportedTables + Tables.size();
1484 }
1485 
1486 bool WasmObjectFile::isDefinedGlobalIndex(uint32_t Index) const {
1487   return Index >= NumImportedGlobals && isValidGlobalIndex(Index);
1488 }
1489 
1490 bool WasmObjectFile::isDefinedTableNumber(uint32_t Index) const {
1491   return Index >= NumImportedTables && isValidTableNumber(Index);
1492 }
1493 
1494 bool WasmObjectFile::isValidTagIndex(uint32_t Index) const {
1495   return Index < NumImportedTags + Tags.size();
1496 }
1497 
1498 bool WasmObjectFile::isDefinedTagIndex(uint32_t Index) const {
1499   return Index >= NumImportedTags && isValidTagIndex(Index);
1500 }
1501 
1502 bool WasmObjectFile::isValidFunctionSymbol(uint32_t Index) const {
1503   return Index < Symbols.size() && Symbols[Index].isTypeFunction();
1504 }
1505 
1506 bool WasmObjectFile::isValidTableSymbol(uint32_t Index) const {
1507   return Index < Symbols.size() && Symbols[Index].isTypeTable();
1508 }
1509 
1510 bool WasmObjectFile::isValidGlobalSymbol(uint32_t Index) const {
1511   return Index < Symbols.size() && Symbols[Index].isTypeGlobal();
1512 }
1513 
1514 bool WasmObjectFile::isValidTagSymbol(uint32_t Index) const {
1515   return Index < Symbols.size() && Symbols[Index].isTypeTag();
1516 }
1517 
1518 bool WasmObjectFile::isValidDataSymbol(uint32_t Index) const {
1519   return Index < Symbols.size() && Symbols[Index].isTypeData();
1520 }
1521 
1522 bool WasmObjectFile::isValidSectionSymbol(uint32_t Index) const {
1523   return Index < Symbols.size() && Symbols[Index].isTypeSection();
1524 }
1525 
1526 wasm::WasmFunction &WasmObjectFile::getDefinedFunction(uint32_t Index) {
1527   assert(isDefinedFunctionIndex(Index));
1528   return Functions[Index - NumImportedFunctions];
1529 }
1530 
1531 const wasm::WasmFunction &
1532 WasmObjectFile::getDefinedFunction(uint32_t Index) const {
1533   assert(isDefinedFunctionIndex(Index));
1534   return Functions[Index - NumImportedFunctions];
1535 }
1536 
1537 wasm::WasmGlobal &WasmObjectFile::getDefinedGlobal(uint32_t Index) {
1538   assert(isDefinedGlobalIndex(Index));
1539   return Globals[Index - NumImportedGlobals];
1540 }
1541 
1542 wasm::WasmTag &WasmObjectFile::getDefinedTag(uint32_t Index) {
1543   assert(isDefinedTagIndex(Index));
1544   return Tags[Index - NumImportedTags];
1545 }
1546 
1547 Error WasmObjectFile::parseStartSection(ReadContext &Ctx) {
1548   StartFunction = readVaruint32(Ctx);
1549   if (!isValidFunctionIndex(StartFunction))
1550     return make_error<GenericBinaryError>("invalid start function",
1551                                           object_error::parse_failed);
1552   return Error::success();
1553 }
1554 
1555 Error WasmObjectFile::parseCodeSection(ReadContext &Ctx) {
1556   CodeSection = Sections.size();
1557   uint32_t FunctionCount = readVaruint32(Ctx);
1558   if (FunctionCount != Functions.size()) {
1559     return make_error<GenericBinaryError>("invalid function count",
1560                                           object_error::parse_failed);
1561   }
1562 
1563   for (uint32_t i = 0; i < FunctionCount; i++) {
1564     wasm::WasmFunction& Function = Functions[i];
1565     const uint8_t *FunctionStart = Ctx.Ptr;
1566     uint32_t Size = readVaruint32(Ctx);
1567     const uint8_t *FunctionEnd = Ctx.Ptr + Size;
1568 
1569     Function.CodeOffset = Ctx.Ptr - FunctionStart;
1570     Function.Index = NumImportedFunctions + i;
1571     Function.CodeSectionOffset = FunctionStart - Ctx.Start;
1572     Function.Size = FunctionEnd - FunctionStart;
1573 
1574     uint32_t NumLocalDecls = readVaruint32(Ctx);
1575     Function.Locals.reserve(NumLocalDecls);
1576     while (NumLocalDecls--) {
1577       wasm::WasmLocalDecl Decl;
1578       Decl.Count = readVaruint32(Ctx);
1579       Decl.Type = readUint8(Ctx);
1580       Function.Locals.push_back(Decl);
1581     }
1582 
1583     uint32_t BodySize = FunctionEnd - Ctx.Ptr;
1584     // Ensure that Function is within Ctx's buffer.
1585     if (Ctx.Ptr + BodySize > Ctx.End) {
1586       return make_error<GenericBinaryError>("Function extends beyond buffer",
1587                                             object_error::parse_failed);
1588     }
1589     Function.Body = ArrayRef<uint8_t>(Ctx.Ptr, BodySize);
1590     // This will be set later when reading in the linking metadata section.
1591     Function.Comdat = UINT32_MAX;
1592     Ctx.Ptr += BodySize;
1593     assert(Ctx.Ptr == FunctionEnd);
1594   }
1595   if (Ctx.Ptr != Ctx.End)
1596     return make_error<GenericBinaryError>("code section ended prematurely",
1597                                           object_error::parse_failed);
1598   return Error::success();
1599 }
1600 
1601 Error WasmObjectFile::parseElemSection(ReadContext &Ctx) {
1602   uint32_t Count = readVaruint32(Ctx);
1603   ElemSegments.reserve(Count);
1604   while (Count--) {
1605     wasm::WasmElemSegment Segment;
1606     Segment.Flags = readVaruint32(Ctx);
1607 
1608     uint32_t SupportedFlags = wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER |
1609                               wasm::WASM_ELEM_SEGMENT_IS_PASSIVE |
1610                               wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS;
1611     if (Segment.Flags & ~SupportedFlags)
1612       return make_error<GenericBinaryError>(
1613           "Unsupported flags for element segment", object_error::parse_failed);
1614 
1615     bool IsPassive = (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_PASSIVE) != 0;
1616     bool IsDeclarative =
1617         IsPassive && (Segment.Flags & wasm::WASM_ELEM_SEGMENT_IS_DECLARATIVE);
1618     bool HasTableNumber =
1619         !IsPassive &&
1620         (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER);
1621     bool HasInitExprs =
1622         (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS);
1623     bool HasElemKind =
1624         (Segment.Flags & wasm::WASM_ELEM_SEGMENT_MASK_HAS_ELEM_KIND) &&
1625         !HasInitExprs;
1626 
1627     if (HasTableNumber)
1628       Segment.TableNumber = readVaruint32(Ctx);
1629     else
1630       Segment.TableNumber = 0;
1631 
1632     if (!isValidTableNumber(Segment.TableNumber))
1633       return make_error<GenericBinaryError>("invalid TableNumber",
1634                                             object_error::parse_failed);
1635 
1636     if (IsPassive || IsDeclarative) {
1637       Segment.Offset.Extended = false;
1638       Segment.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;
1639       Segment.Offset.Inst.Value.Int32 = 0;
1640     } else {
1641       if (Error Err = readInitExpr(Segment.Offset, Ctx))
1642         return Err;
1643     }
1644 
1645     if (HasElemKind) {
1646       auto ElemKind = readVaruint32(Ctx);
1647       if (Segment.Flags & wasm::WASM_ELEM_SEGMENT_HAS_INIT_EXPRS) {
1648         Segment.ElemKind = parseValType(Ctx, ElemKind);
1649         if (Segment.ElemKind != wasm::ValType::FUNCREF &&
1650             Segment.ElemKind != wasm::ValType::EXTERNREF &&
1651             Segment.ElemKind != wasm::ValType::OTHERREF) {
1652           return make_error<GenericBinaryError>("invalid elem type",
1653                                                 object_error::parse_failed);
1654         }
1655       } else {
1656         if (ElemKind != 0)
1657           return make_error<GenericBinaryError>("invalid elem type",
1658                                                 object_error::parse_failed);
1659         Segment.ElemKind = wasm::ValType::FUNCREF;
1660       }
1661     } else if (HasInitExprs) {
1662       auto ElemType = parseValType(Ctx, readVaruint32(Ctx));
1663       Segment.ElemKind = ElemType;
1664     } else {
1665       Segment.ElemKind = wasm::ValType::FUNCREF;
1666     }
1667 
1668     uint32_t NumElems = readVaruint32(Ctx);
1669 
1670     if (HasInitExprs) {
1671       while (NumElems--) {
1672         wasm::WasmInitExpr Expr;
1673         if (Error Err = readInitExpr(Expr, Ctx))
1674           return Err;
1675       }
1676     } else {
1677       while (NumElems--) {
1678         Segment.Functions.push_back(readVaruint32(Ctx));
1679       }
1680     }
1681     ElemSegments.push_back(Segment);
1682   }
1683   if (Ctx.Ptr != Ctx.End)
1684     return make_error<GenericBinaryError>("elem section ended prematurely",
1685                                           object_error::parse_failed);
1686   return Error::success();
1687 }
1688 
1689 Error WasmObjectFile::parseDataSection(ReadContext &Ctx) {
1690   DataSection = Sections.size();
1691   uint32_t Count = readVaruint32(Ctx);
1692   if (DataCount && Count != *DataCount)
1693     return make_error<GenericBinaryError>(
1694         "number of data segments does not match DataCount section");
1695   DataSegments.reserve(Count);
1696   while (Count--) {
1697     WasmSegment Segment;
1698     Segment.Data.InitFlags = readVaruint32(Ctx);
1699     Segment.Data.MemoryIndex =
1700         (Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_HAS_MEMINDEX)
1701             ? readVaruint32(Ctx)
1702             : 0;
1703     if ((Segment.Data.InitFlags & wasm::WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
1704       if (Error Err = readInitExpr(Segment.Data.Offset, Ctx))
1705         return Err;
1706     } else {
1707       Segment.Data.Offset.Extended = false;
1708       Segment.Data.Offset.Inst.Opcode = wasm::WASM_OPCODE_I32_CONST;
1709       Segment.Data.Offset.Inst.Value.Int32 = 0;
1710     }
1711     uint32_t Size = readVaruint32(Ctx);
1712     if (Size > (size_t)(Ctx.End - Ctx.Ptr))
1713       return make_error<GenericBinaryError>("invalid segment size",
1714                                             object_error::parse_failed);
1715     Segment.Data.Content = ArrayRef<uint8_t>(Ctx.Ptr, Size);
1716     // The rest of these Data fields are set later, when reading in the linking
1717     // metadata section.
1718     Segment.Data.Alignment = 0;
1719     Segment.Data.LinkingFlags = 0;
1720     Segment.Data.Comdat = UINT32_MAX;
1721     Segment.SectionOffset = Ctx.Ptr - Ctx.Start;
1722     Ctx.Ptr += Size;
1723     DataSegments.push_back(Segment);
1724   }
1725   if (Ctx.Ptr != Ctx.End)
1726     return make_error<GenericBinaryError>("data section ended prematurely",
1727                                           object_error::parse_failed);
1728   return Error::success();
1729 }
1730 
1731 Error WasmObjectFile::parseDataCountSection(ReadContext &Ctx) {
1732   DataCount = readVaruint32(Ctx);
1733   return Error::success();
1734 }
1735 
1736 const wasm::WasmObjectHeader &WasmObjectFile::getHeader() const {
1737   return Header;
1738 }
1739 
1740 void WasmObjectFile::moveSymbolNext(DataRefImpl &Symb) const { Symb.d.b++; }
1741 
1742 Expected<uint32_t> WasmObjectFile::getSymbolFlags(DataRefImpl Symb) const {
1743   uint32_t Result = SymbolRef::SF_None;
1744   const WasmSymbol &Sym = getWasmSymbol(Symb);
1745 
1746   LLVM_DEBUG(dbgs() << "getSymbolFlags: ptr=" << &Sym << " " << Sym << "\n");
1747   if (Sym.isBindingWeak())
1748     Result |= SymbolRef::SF_Weak;
1749   if (!Sym.isBindingLocal())
1750     Result |= SymbolRef::SF_Global;
1751   if (Sym.isHidden())
1752     Result |= SymbolRef::SF_Hidden;
1753   if (!Sym.isDefined())
1754     Result |= SymbolRef::SF_Undefined;
1755   if (Sym.isTypeFunction())
1756     Result |= SymbolRef::SF_Executable;
1757   return Result;
1758 }
1759 
1760 basic_symbol_iterator WasmObjectFile::symbol_begin() const {
1761   DataRefImpl Ref;
1762   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1763   Ref.d.b = 0; // Symbol index
1764   return BasicSymbolRef(Ref, this);
1765 }
1766 
1767 basic_symbol_iterator WasmObjectFile::symbol_end() const {
1768   DataRefImpl Ref;
1769   Ref.d.a = 1; // Arbitrary non-zero value so that Ref.p is non-null
1770   Ref.d.b = Symbols.size(); // Symbol index
1771   return BasicSymbolRef(Ref, this);
1772 }
1773 
1774 const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const {
1775   return Symbols[Symb.d.b];
1776 }
1777 
1778 const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const {
1779   return getWasmSymbol(Symb.getRawDataRefImpl());
1780 }
1781 
1782 Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const {
1783   return getWasmSymbol(Symb).Info.Name;
1784 }
1785 
1786 Expected<uint64_t> WasmObjectFile::getSymbolAddress(DataRefImpl Symb) const {
1787   auto &Sym = getWasmSymbol(Symb);
1788   if (Sym.Info.Kind == wasm::WASM_SYMBOL_TYPE_FUNCTION &&
1789       isDefinedFunctionIndex(Sym.Info.ElementIndex)) {
1790     // For object files, use the section offset. The linker relies on this.
1791     // For linked files, use the file offset. This behavior matches the way
1792     // browsers print stack traces and is useful for binary size analysis.
1793     // (see https://webassembly.github.io/spec/web-api/index.html#conventions)
1794     uint32_t Adjustment = isRelocatableObject() || isSharedObject()
1795                               ? 0
1796                               : Sections[CodeSection].Offset;
1797     return getDefinedFunction(Sym.Info.ElementIndex).CodeSectionOffset +
1798            Adjustment;
1799   }
1800   return getSymbolValue(Symb);
1801 }
1802 
1803 uint64_t WasmObjectFile::getWasmSymbolValue(const WasmSymbol &Sym) const {
1804   switch (Sym.Info.Kind) {
1805   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1806   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1807   case wasm::WASM_SYMBOL_TYPE_TAG:
1808   case wasm::WASM_SYMBOL_TYPE_TABLE:
1809     return Sym.Info.ElementIndex;
1810   case wasm::WASM_SYMBOL_TYPE_DATA: {
1811     // The value of a data symbol is the segment offset, plus the symbol
1812     // offset within the segment.
1813     uint32_t SegmentIndex = Sym.Info.DataRef.Segment;
1814     const wasm::WasmDataSegment &Segment = DataSegments[SegmentIndex].Data;
1815     if (Segment.Offset.Extended) {
1816       llvm_unreachable("extended init exprs not supported");
1817     } else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I32_CONST) {
1818       return Segment.Offset.Inst.Value.Int32 + Sym.Info.DataRef.Offset;
1819     } else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_I64_CONST) {
1820       return Segment.Offset.Inst.Value.Int64 + Sym.Info.DataRef.Offset;
1821     } else if (Segment.Offset.Inst.Opcode == wasm::WASM_OPCODE_GLOBAL_GET) {
1822       return Sym.Info.DataRef.Offset;
1823     } else {
1824       llvm_unreachable("unknown init expr opcode");
1825     }
1826   }
1827   case wasm::WASM_SYMBOL_TYPE_SECTION:
1828     return 0;
1829   }
1830   llvm_unreachable("invalid symbol type");
1831 }
1832 
1833 uint64_t WasmObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
1834   return getWasmSymbolValue(getWasmSymbol(Symb));
1835 }
1836 
1837 uint32_t WasmObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
1838   llvm_unreachable("not yet implemented");
1839   return 0;
1840 }
1841 
1842 uint64_t WasmObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
1843   llvm_unreachable("not yet implemented");
1844   return 0;
1845 }
1846 
1847 Expected<SymbolRef::Type>
1848 WasmObjectFile::getSymbolType(DataRefImpl Symb) const {
1849   const WasmSymbol &Sym = getWasmSymbol(Symb);
1850 
1851   switch (Sym.Info.Kind) {
1852   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1853     return SymbolRef::ST_Function;
1854   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1855     return SymbolRef::ST_Other;
1856   case wasm::WASM_SYMBOL_TYPE_DATA:
1857     return SymbolRef::ST_Data;
1858   case wasm::WASM_SYMBOL_TYPE_SECTION:
1859     return SymbolRef::ST_Debug;
1860   case wasm::WASM_SYMBOL_TYPE_TAG:
1861     return SymbolRef::ST_Other;
1862   case wasm::WASM_SYMBOL_TYPE_TABLE:
1863     return SymbolRef::ST_Other;
1864   }
1865 
1866   llvm_unreachable("unknown WasmSymbol::SymbolType");
1867   return SymbolRef::ST_Other;
1868 }
1869 
1870 Expected<section_iterator>
1871 WasmObjectFile::getSymbolSection(DataRefImpl Symb) const {
1872   const WasmSymbol &Sym = getWasmSymbol(Symb);
1873   if (Sym.isUndefined())
1874     return section_end();
1875 
1876   DataRefImpl Ref;
1877   Ref.d.a = getSymbolSectionIdImpl(Sym);
1878   return section_iterator(SectionRef(Ref, this));
1879 }
1880 
1881 uint32_t WasmObjectFile::getSymbolSectionId(SymbolRef Symb) const {
1882   const WasmSymbol &Sym = getWasmSymbol(Symb);
1883   return getSymbolSectionIdImpl(Sym);
1884 }
1885 
1886 uint32_t WasmObjectFile::getSymbolSectionIdImpl(const WasmSymbol &Sym) const {
1887   switch (Sym.Info.Kind) {
1888   case wasm::WASM_SYMBOL_TYPE_FUNCTION:
1889     return CodeSection;
1890   case wasm::WASM_SYMBOL_TYPE_GLOBAL:
1891     return GlobalSection;
1892   case wasm::WASM_SYMBOL_TYPE_DATA:
1893     return DataSection;
1894   case wasm::WASM_SYMBOL_TYPE_SECTION:
1895     return Sym.Info.ElementIndex;
1896   case wasm::WASM_SYMBOL_TYPE_TAG:
1897     return TagSection;
1898   case wasm::WASM_SYMBOL_TYPE_TABLE:
1899     return TableSection;
1900   default:
1901     llvm_unreachable("unknown WasmSymbol::SymbolType");
1902   }
1903 }
1904 
1905 void WasmObjectFile::moveSectionNext(DataRefImpl &Sec) const { Sec.d.a++; }
1906 
1907 Expected<StringRef> WasmObjectFile::getSectionName(DataRefImpl Sec) const {
1908   const WasmSection &S = Sections[Sec.d.a];
1909   if (S.Type == wasm::WASM_SEC_CUSTOM)
1910     return S.Name;
1911   if (S.Type > wasm::WASM_SEC_LAST_KNOWN)
1912     return createStringError(object_error::invalid_section_index, "");
1913   return wasm::sectionTypeToString(S.Type);
1914 }
1915 
1916 uint64_t WasmObjectFile::getSectionAddress(DataRefImpl Sec) const { return 0; }
1917 
1918 uint64_t WasmObjectFile::getSectionIndex(DataRefImpl Sec) const {
1919   return Sec.d.a;
1920 }
1921 
1922 uint64_t WasmObjectFile::getSectionSize(DataRefImpl Sec) const {
1923   const WasmSection &S = Sections[Sec.d.a];
1924   return S.Content.size();
1925 }
1926 
1927 Expected<ArrayRef<uint8_t>>
1928 WasmObjectFile::getSectionContents(DataRefImpl Sec) const {
1929   const WasmSection &S = Sections[Sec.d.a];
1930   // This will never fail since wasm sections can never be empty (user-sections
1931   // must have a name and non-user sections each have a defined structure).
1932   return S.Content;
1933 }
1934 
1935 uint64_t WasmObjectFile::getSectionAlignment(DataRefImpl Sec) const {
1936   return 1;
1937 }
1938 
1939 bool WasmObjectFile::isSectionCompressed(DataRefImpl Sec) const {
1940   return false;
1941 }
1942 
1943 bool WasmObjectFile::isSectionText(DataRefImpl Sec) const {
1944   return getWasmSection(Sec).Type == wasm::WASM_SEC_CODE;
1945 }
1946 
1947 bool WasmObjectFile::isSectionData(DataRefImpl Sec) const {
1948   return getWasmSection(Sec).Type == wasm::WASM_SEC_DATA;
1949 }
1950 
1951 bool WasmObjectFile::isSectionBSS(DataRefImpl Sec) const { return false; }
1952 
1953 bool WasmObjectFile::isSectionVirtual(DataRefImpl Sec) const { return false; }
1954 
1955 relocation_iterator WasmObjectFile::section_rel_begin(DataRefImpl Ref) const {
1956   DataRefImpl RelocRef;
1957   RelocRef.d.a = Ref.d.a;
1958   RelocRef.d.b = 0;
1959   return relocation_iterator(RelocationRef(RelocRef, this));
1960 }
1961 
1962 relocation_iterator WasmObjectFile::section_rel_end(DataRefImpl Ref) const {
1963   const WasmSection &Sec = getWasmSection(Ref);
1964   DataRefImpl RelocRef;
1965   RelocRef.d.a = Ref.d.a;
1966   RelocRef.d.b = Sec.Relocations.size();
1967   return relocation_iterator(RelocationRef(RelocRef, this));
1968 }
1969 
1970 void WasmObjectFile::moveRelocationNext(DataRefImpl &Rel) const { Rel.d.b++; }
1971 
1972 uint64_t WasmObjectFile::getRelocationOffset(DataRefImpl Ref) const {
1973   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1974   return Rel.Offset;
1975 }
1976 
1977 symbol_iterator WasmObjectFile::getRelocationSymbol(DataRefImpl Ref) const {
1978   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1979   if (Rel.Type == wasm::R_WASM_TYPE_INDEX_LEB)
1980     return symbol_end();
1981   DataRefImpl Sym;
1982   Sym.d.a = 1;
1983   Sym.d.b = Rel.Index;
1984   return symbol_iterator(SymbolRef(Sym, this));
1985 }
1986 
1987 uint64_t WasmObjectFile::getRelocationType(DataRefImpl Ref) const {
1988   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1989   return Rel.Type;
1990 }
1991 
1992 void WasmObjectFile::getRelocationTypeName(
1993     DataRefImpl Ref, SmallVectorImpl<char> &Result) const {
1994   const wasm::WasmRelocation &Rel = getWasmRelocation(Ref);
1995   StringRef Res = "Unknown";
1996 
1997 #define WASM_RELOC(name, value)                                                \
1998   case wasm::name:                                                             \
1999     Res = #name;                                                               \
2000     break;
2001 
2002   switch (Rel.Type) {
2003 #include "llvm/BinaryFormat/WasmRelocs.def"
2004   }
2005 
2006 #undef WASM_RELOC
2007 
2008   Result.append(Res.begin(), Res.end());
2009 }
2010 
2011 section_iterator WasmObjectFile::section_begin() const {
2012   DataRefImpl Ref;
2013   Ref.d.a = 0;
2014   return section_iterator(SectionRef(Ref, this));
2015 }
2016 
2017 section_iterator WasmObjectFile::section_end() const {
2018   DataRefImpl Ref;
2019   Ref.d.a = Sections.size();
2020   return section_iterator(SectionRef(Ref, this));
2021 }
2022 
2023 uint8_t WasmObjectFile::getBytesInAddress() const {
2024   return HasMemory64 ? 8 : 4;
2025 }
2026 
2027 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
2028 
2029 Triple::ArchType WasmObjectFile::getArch() const {
2030   return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
2031 }
2032 
2033 Expected<SubtargetFeatures> WasmObjectFile::getFeatures() const {
2034   return SubtargetFeatures();
2035 }
2036 
2037 bool WasmObjectFile::isRelocatableObject() const { return HasLinkingSection; }
2038 
2039 bool WasmObjectFile::isSharedObject() const { return HasDylinkSection; }
2040 
2041 const WasmSection &WasmObjectFile::getWasmSection(DataRefImpl Ref) const {
2042   assert(Ref.d.a < Sections.size());
2043   return Sections[Ref.d.a];
2044 }
2045 
2046 const WasmSection &
2047 WasmObjectFile::getWasmSection(const SectionRef &Section) const {
2048   return getWasmSection(Section.getRawDataRefImpl());
2049 }
2050 
2051 const wasm::WasmRelocation &
2052 WasmObjectFile::getWasmRelocation(const RelocationRef &Ref) const {
2053   return getWasmRelocation(Ref.getRawDataRefImpl());
2054 }
2055 
2056 const wasm::WasmRelocation &
2057 WasmObjectFile::getWasmRelocation(DataRefImpl Ref) const {
2058   assert(Ref.d.a < Sections.size());
2059   const WasmSection &Sec = Sections[Ref.d.a];
2060   assert(Ref.d.b < Sec.Relocations.size());
2061   return Sec.Relocations[Ref.d.b];
2062 }
2063 
2064 int WasmSectionOrderChecker::getSectionOrder(unsigned ID,
2065                                              StringRef CustomSectionName) {
2066   switch (ID) {
2067   case wasm::WASM_SEC_CUSTOM:
2068     return StringSwitch<unsigned>(CustomSectionName)
2069         .Case("dylink", WASM_SEC_ORDER_DYLINK)
2070         .Case("dylink.0", WASM_SEC_ORDER_DYLINK)
2071         .Case("linking", WASM_SEC_ORDER_LINKING)
2072         .StartsWith("reloc.", WASM_SEC_ORDER_RELOC)
2073         .Case("name", WASM_SEC_ORDER_NAME)
2074         .Case("producers", WASM_SEC_ORDER_PRODUCERS)
2075         .Case("target_features", WASM_SEC_ORDER_TARGET_FEATURES)
2076         .Default(WASM_SEC_ORDER_NONE);
2077   case wasm::WASM_SEC_TYPE:
2078     return WASM_SEC_ORDER_TYPE;
2079   case wasm::WASM_SEC_IMPORT:
2080     return WASM_SEC_ORDER_IMPORT;
2081   case wasm::WASM_SEC_FUNCTION:
2082     return WASM_SEC_ORDER_FUNCTION;
2083   case wasm::WASM_SEC_TABLE:
2084     return WASM_SEC_ORDER_TABLE;
2085   case wasm::WASM_SEC_MEMORY:
2086     return WASM_SEC_ORDER_MEMORY;
2087   case wasm::WASM_SEC_GLOBAL:
2088     return WASM_SEC_ORDER_GLOBAL;
2089   case wasm::WASM_SEC_EXPORT:
2090     return WASM_SEC_ORDER_EXPORT;
2091   case wasm::WASM_SEC_START:
2092     return WASM_SEC_ORDER_START;
2093   case wasm::WASM_SEC_ELEM:
2094     return WASM_SEC_ORDER_ELEM;
2095   case wasm::WASM_SEC_CODE:
2096     return WASM_SEC_ORDER_CODE;
2097   case wasm::WASM_SEC_DATA:
2098     return WASM_SEC_ORDER_DATA;
2099   case wasm::WASM_SEC_DATACOUNT:
2100     return WASM_SEC_ORDER_DATACOUNT;
2101   case wasm::WASM_SEC_TAG:
2102     return WASM_SEC_ORDER_TAG;
2103   default:
2104     return WASM_SEC_ORDER_NONE;
2105   }
2106 }
2107 
2108 // Represents the edges in a directed graph where any node B reachable from node
2109 // A is not allowed to appear before A in the section ordering, but may appear
2110 // afterward.
2111 int WasmSectionOrderChecker::DisallowedPredecessors
2112     [WASM_NUM_SEC_ORDERS][WASM_NUM_SEC_ORDERS] = {
2113         // WASM_SEC_ORDER_NONE
2114         {},
2115         // WASM_SEC_ORDER_TYPE
2116         {WASM_SEC_ORDER_TYPE, WASM_SEC_ORDER_IMPORT},
2117         // WASM_SEC_ORDER_IMPORT
2118         {WASM_SEC_ORDER_IMPORT, WASM_SEC_ORDER_FUNCTION},
2119         // WASM_SEC_ORDER_FUNCTION
2120         {WASM_SEC_ORDER_FUNCTION, WASM_SEC_ORDER_TABLE},
2121         // WASM_SEC_ORDER_TABLE
2122         {WASM_SEC_ORDER_TABLE, WASM_SEC_ORDER_MEMORY},
2123         // WASM_SEC_ORDER_MEMORY
2124         {WASM_SEC_ORDER_MEMORY, WASM_SEC_ORDER_TAG},
2125         // WASM_SEC_ORDER_TAG
2126         {WASM_SEC_ORDER_TAG, WASM_SEC_ORDER_GLOBAL},
2127         // WASM_SEC_ORDER_GLOBAL
2128         {WASM_SEC_ORDER_GLOBAL, WASM_SEC_ORDER_EXPORT},
2129         // WASM_SEC_ORDER_EXPORT
2130         {WASM_SEC_ORDER_EXPORT, WASM_SEC_ORDER_START},
2131         // WASM_SEC_ORDER_START
2132         {WASM_SEC_ORDER_START, WASM_SEC_ORDER_ELEM},
2133         // WASM_SEC_ORDER_ELEM
2134         {WASM_SEC_ORDER_ELEM, WASM_SEC_ORDER_DATACOUNT},
2135         // WASM_SEC_ORDER_DATACOUNT
2136         {WASM_SEC_ORDER_DATACOUNT, WASM_SEC_ORDER_CODE},
2137         // WASM_SEC_ORDER_CODE
2138         {WASM_SEC_ORDER_CODE, WASM_SEC_ORDER_DATA},
2139         // WASM_SEC_ORDER_DATA
2140         {WASM_SEC_ORDER_DATA, WASM_SEC_ORDER_LINKING},
2141 
2142         // Custom Sections
2143         // WASM_SEC_ORDER_DYLINK
2144         {WASM_SEC_ORDER_DYLINK, WASM_SEC_ORDER_TYPE},
2145         // WASM_SEC_ORDER_LINKING
2146         {WASM_SEC_ORDER_LINKING, WASM_SEC_ORDER_RELOC, WASM_SEC_ORDER_NAME},
2147         // WASM_SEC_ORDER_RELOC (can be repeated)
2148         {},
2149         // WASM_SEC_ORDER_NAME
2150         {WASM_SEC_ORDER_NAME, WASM_SEC_ORDER_PRODUCERS},
2151         // WASM_SEC_ORDER_PRODUCERS
2152         {WASM_SEC_ORDER_PRODUCERS, WASM_SEC_ORDER_TARGET_FEATURES},
2153         // WASM_SEC_ORDER_TARGET_FEATURES
2154         {WASM_SEC_ORDER_TARGET_FEATURES}};
2155 
2156 bool WasmSectionOrderChecker::isValidSectionOrder(unsigned ID,
2157                                                   StringRef CustomSectionName) {
2158   int Order = getSectionOrder(ID, CustomSectionName);
2159   if (Order == WASM_SEC_ORDER_NONE)
2160     return true;
2161 
2162   // Disallowed predecessors we need to check for
2163   SmallVector<int, WASM_NUM_SEC_ORDERS> WorkList;
2164 
2165   // Keep track of completed checks to avoid repeating work
2166   bool Checked[WASM_NUM_SEC_ORDERS] = {};
2167 
2168   int Curr = Order;
2169   while (true) {
2170     // Add new disallowed predecessors to work list
2171     for (size_t I = 0;; ++I) {
2172       int Next = DisallowedPredecessors[Curr][I];
2173       if (Next == WASM_SEC_ORDER_NONE)
2174         break;
2175       if (Checked[Next])
2176         continue;
2177       WorkList.push_back(Next);
2178       Checked[Next] = true;
2179     }
2180 
2181     if (WorkList.empty())
2182       break;
2183 
2184     // Consider next disallowed predecessor
2185     Curr = WorkList.pop_back_val();
2186     if (Seen[Curr])
2187       return false;
2188   }
2189 
2190   // Have not seen any disallowed predecessors
2191   Seen[Order] = true;
2192   return true;
2193 }
2194