1 //===- InputFiles.cpp -----------------------------------------------------===//
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 "InputFiles.h"
10 #include "Config.h"
11 #include "InputChunks.h"
12 #include "InputEvent.h"
13 #include "InputGlobal.h"
14 #include "SymbolTable.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "lld/Common/Reproduce.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/Object/Wasm.h"
20 #include "llvm/Support/TarWriter.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 #define DEBUG_TYPE "lld"
24 
25 using namespace lld;
26 using namespace lld::wasm;
27 
28 using namespace llvm;
29 using namespace llvm::object;
30 using namespace llvm::wasm;
31 
32 std::unique_ptr<llvm::TarWriter> lld::wasm::Tar;
33 
34 Optional<MemoryBufferRef> lld::wasm::readFile(StringRef Path) {
35   log("Loading: " + Path);
36 
37   auto MBOrErr = MemoryBuffer::getFile(Path);
38   if (auto EC = MBOrErr.getError()) {
39     error("cannot open " + Path + ": " + EC.message());
40     return None;
41   }
42   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
43   MemoryBufferRef MBRef = MB->getMemBufferRef();
44   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
45 
46   if (Tar)
47     Tar->append(relativeToRoot(Path), MBRef.getBuffer());
48   return MBRef;
49 }
50 
51 InputFile *lld::wasm::createObjectFile(MemoryBufferRef MB,
52                                        StringRef ArchiveName) {
53   file_magic Magic = identify_magic(MB.getBuffer());
54   if (Magic == file_magic::wasm_object) {
55     std::unique_ptr<Binary> Bin =
56         CHECK(createBinary(MB), MB.getBufferIdentifier());
57     auto *Obj = cast<WasmObjectFile>(Bin.get());
58     if (Obj->isSharedObject())
59       return make<SharedFile>(MB);
60     return make<ObjFile>(MB, ArchiveName);
61   }
62 
63   if (Magic == file_magic::bitcode)
64     return make<BitcodeFile>(MB, ArchiveName);
65 
66   fatal("unknown file type: " + MB.getBufferIdentifier());
67 }
68 
69 void ObjFile::dumpInfo() const {
70   log("info for: " + toString(this) +
71       "\n              Symbols : " + Twine(Symbols.size()) +
72       "\n     Function Imports : " + Twine(WasmObj->getNumImportedFunctions()) +
73       "\n       Global Imports : " + Twine(WasmObj->getNumImportedGlobals()) +
74       "\n        Event Imports : " + Twine(WasmObj->getNumImportedEvents()));
75 }
76 
77 // Relocations contain either symbol or type indices.  This function takes a
78 // relocation and returns relocated index (i.e. translates from the input
79 // symbol/type space to the output symbol/type space).
80 uint32_t ObjFile::calcNewIndex(const WasmRelocation &Reloc) const {
81   if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
82     assert(TypeIsUsed[Reloc.Index]);
83     return TypeMap[Reloc.Index];
84   }
85   const Symbol *Sym = Symbols[Reloc.Index];
86   if (auto *SS = dyn_cast<SectionSymbol>(Sym))
87     Sym = SS->getOutputSectionSymbol();
88   return Sym->getOutputSymbolIndex();
89 }
90 
91 // Relocations can contain addend for combined sections. This function takes a
92 // relocation and returns updated addend by offset in the output section.
93 uint32_t ObjFile::calcNewAddend(const WasmRelocation &Reloc) const {
94   switch (Reloc.Type) {
95   case R_WASM_MEMORY_ADDR_LEB:
96   case R_WASM_MEMORY_ADDR_SLEB:
97   case R_WASM_MEMORY_ADDR_REL_SLEB:
98   case R_WASM_MEMORY_ADDR_I32:
99   case R_WASM_FUNCTION_OFFSET_I32:
100     return Reloc.Addend;
101   case R_WASM_SECTION_OFFSET_I32:
102     return getSectionSymbol(Reloc.Index)->Section->OutputOffset + Reloc.Addend;
103   default:
104     llvm_unreachable("unexpected relocation type");
105   }
106 }
107 
108 // Calculate the value we expect to find at the relocation location.
109 // This is used as a sanity check before applying a relocation to a given
110 // location.  It is useful for catching bugs in the compiler and linker.
111 uint32_t ObjFile::calcExpectedValue(const WasmRelocation &Reloc) const {
112   switch (Reloc.Type) {
113   case R_WASM_TABLE_INDEX_I32:
114   case R_WASM_TABLE_INDEX_SLEB:
115   case R_WASM_TABLE_INDEX_REL_SLEB: {
116     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
117     return TableEntries[Sym.Info.ElementIndex];
118   }
119   case R_WASM_MEMORY_ADDR_SLEB:
120   case R_WASM_MEMORY_ADDR_I32:
121   case R_WASM_MEMORY_ADDR_LEB:
122   case R_WASM_MEMORY_ADDR_REL_SLEB: {
123     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
124     if (Sym.isUndefined())
125       return 0;
126     const WasmSegment &Segment =
127         WasmObj->dataSegments()[Sym.Info.DataRef.Segment];
128     return Segment.Data.Offset.Value.Int32 + Sym.Info.DataRef.Offset +
129            Reloc.Addend;
130   }
131   case R_WASM_FUNCTION_OFFSET_I32: {
132     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
133     InputFunction *F =
134         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
135     return F->getFunctionInputOffset() + F->getFunctionCodeOffset() +
136            Reloc.Addend;
137   }
138   case R_WASM_SECTION_OFFSET_I32:
139     return Reloc.Addend;
140   case R_WASM_TYPE_INDEX_LEB:
141     return Reloc.Index;
142   case R_WASM_FUNCTION_INDEX_LEB:
143   case R_WASM_GLOBAL_INDEX_LEB:
144   case R_WASM_EVENT_INDEX_LEB: {
145     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
146     return Sym.Info.ElementIndex;
147   }
148   default:
149     llvm_unreachable("unknown relocation type");
150   }
151 }
152 
153 // Translate from the relocation's index into the final linked output value.
154 uint32_t ObjFile::calcNewValue(const WasmRelocation &Reloc) const {
155   const Symbol* Sym = nullptr;
156   if (Reloc.Type != R_WASM_TYPE_INDEX_LEB) {
157     Sym = Symbols[Reloc.Index];
158 
159     // We can end up with relocations against non-live symbols.  For example
160     // in debug sections.
161     if ((isa<FunctionSymbol>(Sym) || isa<DataSymbol>(Sym)) && !Sym->isLive())
162       return 0;
163 
164     // Special handling for undefined data symbols.  Most relocations against
165     // such symbols cannot be resolved.
166     if (isa<DataSymbol>(Sym) && Sym->isUndefined()) {
167       if (Sym->isWeak() || Config->Relocatable)
168         return 0;
169       // R_WASM_MEMORY_ADDR_I32 relocations in PIC code are turned into runtime
170       // fixups in __wasm_apply_relocs
171       if (Config->Pic && Reloc.Type == R_WASM_MEMORY_ADDR_I32)
172         return 0;
173       if (Reloc.Type != R_WASM_GLOBAL_INDEX_LEB) {
174         llvm_unreachable(
175           ("invalid relocation against undefined data symbol: " + toString(*Sym))
176               .c_str());
177       }
178     }
179   }
180 
181   switch (Reloc.Type) {
182   case R_WASM_TABLE_INDEX_I32:
183   case R_WASM_TABLE_INDEX_SLEB:
184   case R_WASM_TABLE_INDEX_REL_SLEB:
185     if (Config->Pic && !getFunctionSymbol(Reloc.Index)->hasTableIndex())
186       return 0;
187     return getFunctionSymbol(Reloc.Index)->getTableIndex();
188   case R_WASM_MEMORY_ADDR_SLEB:
189   case R_WASM_MEMORY_ADDR_I32:
190   case R_WASM_MEMORY_ADDR_LEB:
191   case R_WASM_MEMORY_ADDR_REL_SLEB:
192     return cast<DefinedData>(Sym)->getVirtualAddress() + Reloc.Addend;
193   case R_WASM_TYPE_INDEX_LEB:
194     return TypeMap[Reloc.Index];
195   case R_WASM_FUNCTION_INDEX_LEB:
196     return getFunctionSymbol(Reloc.Index)->getFunctionIndex();
197   case R_WASM_GLOBAL_INDEX_LEB:
198     if (auto GS = dyn_cast<GlobalSymbol>(Sym))
199       return GS->getGlobalIndex();
200     return Sym->getGOTIndex();
201   case R_WASM_EVENT_INDEX_LEB:
202     return getEventSymbol(Reloc.Index)->getEventIndex();
203   case R_WASM_FUNCTION_OFFSET_I32: {
204     auto *F = cast<DefinedFunction>(Sym);
205     return F->Function->OutputOffset + F->Function->getFunctionCodeOffset() +
206            Reloc.Addend;
207   }
208   case R_WASM_SECTION_OFFSET_I32:
209     return getSectionSymbol(Reloc.Index)->Section->OutputOffset + Reloc.Addend;
210   default:
211     llvm_unreachable("unknown relocation type");
212   }
213 }
214 
215 template <class T>
216 static void setRelocs(const std::vector<T *> &Chunks,
217                       const WasmSection *Section) {
218   if (!Section)
219     return;
220 
221   ArrayRef<WasmRelocation> Relocs = Section->Relocations;
222   assert(std::is_sorted(Relocs.begin(), Relocs.end(),
223                         [](const WasmRelocation &R1, const WasmRelocation &R2) {
224                           return R1.Offset < R2.Offset;
225                         }));
226   assert(std::is_sorted(
227       Chunks.begin(), Chunks.end(), [](InputChunk *C1, InputChunk *C2) {
228         return C1->getInputSectionOffset() < C2->getInputSectionOffset();
229       }));
230 
231   auto RelocsNext = Relocs.begin();
232   auto RelocsEnd = Relocs.end();
233   auto RelocLess = [](const WasmRelocation &R, uint32_t Val) {
234     return R.Offset < Val;
235   };
236   for (InputChunk *C : Chunks) {
237     auto RelocsStart = std::lower_bound(RelocsNext, RelocsEnd,
238                                         C->getInputSectionOffset(), RelocLess);
239     RelocsNext = std::lower_bound(
240         RelocsStart, RelocsEnd, C->getInputSectionOffset() + C->getInputSize(),
241         RelocLess);
242     C->setRelocations(ArrayRef<WasmRelocation>(RelocsStart, RelocsNext));
243   }
244 }
245 
246 void ObjFile::parse(bool IgnoreComdats) {
247   // Parse a memory buffer as a wasm file.
248   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
249   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), toString(this));
250 
251   auto *Obj = dyn_cast<WasmObjectFile>(Bin.get());
252   if (!Obj)
253     fatal(toString(this) + ": not a wasm file");
254   if (!Obj->isRelocatableObject())
255     fatal(toString(this) + ": not a relocatable wasm file");
256 
257   Bin.release();
258   WasmObj.reset(Obj);
259 
260   // Build up a map of function indices to table indices for use when
261   // verifying the existing table index relocations
262   uint32_t TotalFunctions =
263       WasmObj->getNumImportedFunctions() + WasmObj->functions().size();
264   TableEntries.resize(TotalFunctions);
265   for (const WasmElemSegment &Seg : WasmObj->elements()) {
266     if (Seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
267       fatal(toString(this) + ": invalid table elements");
268     uint32_t Offset = Seg.Offset.Value.Int32;
269     for (uint32_t Index = 0; Index < Seg.Functions.size(); Index++) {
270 
271       uint32_t FunctionIndex = Seg.Functions[Index];
272       TableEntries[FunctionIndex] = Offset + Index;
273     }
274   }
275 
276   uint32_t SectionIndex = 0;
277 
278   // Bool for each symbol, true if called directly.  This allows us to implement
279   // a weaker form of signature checking where undefined functions that are not
280   // called directly (i.e. only address taken) don't have to match the defined
281   // function's signature.  We cannot do this for directly called functions
282   // because those signatures are checked at validation times.
283   // See https://bugs.llvm.org/show_bug.cgi?id=40412
284   std::vector<bool> IsCalledDirectly(WasmObj->getNumberOfSymbols(), false);
285   for (const SectionRef &Sec : WasmObj->sections()) {
286     const WasmSection &Section = WasmObj->getWasmSection(Sec);
287     // Wasm objects can have at most one code and one data section.
288     if (Section.Type == WASM_SEC_CODE) {
289       assert(!CodeSection);
290       CodeSection = &Section;
291     } else if (Section.Type == WASM_SEC_DATA) {
292       assert(!DataSection);
293       DataSection = &Section;
294     } else if (Section.Type == WASM_SEC_CUSTOM) {
295       CustomSections.emplace_back(make<InputSection>(Section, this));
296       CustomSections.back()->setRelocations(Section.Relocations);
297       CustomSectionsByIndex[SectionIndex] = CustomSections.back();
298     }
299     SectionIndex++;
300     // Scans relocations to dermine determine if a function symbol is called
301     // directly
302     for (const WasmRelocation &Reloc : Section.Relocations)
303       if (Reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
304         IsCalledDirectly[Reloc.Index] = true;
305   }
306 
307   TypeMap.resize(getWasmObj()->types().size());
308   TypeIsUsed.resize(getWasmObj()->types().size(), false);
309 
310   ArrayRef<StringRef> Comdats = WasmObj->linkingData().Comdats;
311   for (StringRef Comdat : Comdats) {
312     bool IsNew = IgnoreComdats || Symtab->addComdat(Comdat);
313     KeptComdats.push_back(IsNew);
314   }
315 
316   // Populate `Segments`.
317   for (const WasmSegment &S : WasmObj->dataSegments()) {
318     auto* Seg = make<InputSegment>(S, this);
319     Seg->Discarded = isExcludedByComdat(Seg);
320     Segments.emplace_back(Seg);
321   }
322   setRelocs(Segments, DataSection);
323 
324   // Populate `Functions`.
325   ArrayRef<WasmFunction> Funcs = WasmObj->functions();
326   ArrayRef<uint32_t> FuncTypes = WasmObj->functionTypes();
327   ArrayRef<WasmSignature> Types = WasmObj->types();
328   Functions.reserve(Funcs.size());
329 
330   for (size_t I = 0, E = Funcs.size(); I != E; ++I) {
331     auto* Func = make<InputFunction>(Types[FuncTypes[I]], &Funcs[I], this);
332     Func->Discarded = isExcludedByComdat(Func);
333     Functions.emplace_back(Func);
334   }
335   setRelocs(Functions, CodeSection);
336 
337   // Populate `Globals`.
338   for (const WasmGlobal &G : WasmObj->globals())
339     Globals.emplace_back(make<InputGlobal>(G, this));
340 
341   // Populate `Events`.
342   for (const WasmEvent &E : WasmObj->events())
343     Events.emplace_back(make<InputEvent>(Types[E.Type.SigIndex], E, this));
344 
345   // Populate `Symbols` based on the WasmSymbols in the object.
346   Symbols.reserve(WasmObj->getNumberOfSymbols());
347   for (const SymbolRef &Sym : WasmObj->symbols()) {
348     const WasmSymbol &WasmSym = WasmObj->getWasmSymbol(Sym.getRawDataRefImpl());
349     if (WasmSym.isDefined()) {
350       // createDefined may fail if the symbol is comdat excluded in which case
351       // we fall back to creating an undefined symbol
352       if (Symbol *D = createDefined(WasmSym)) {
353         Symbols.push_back(D);
354         continue;
355       }
356     }
357     size_t Idx = Symbols.size();
358     Symbols.push_back(createUndefined(WasmSym, IsCalledDirectly[Idx]));
359   }
360 }
361 
362 bool ObjFile::isExcludedByComdat(InputChunk *Chunk) const {
363   uint32_t C = Chunk->getComdat();
364   if (C == UINT32_MAX)
365     return false;
366   return !KeptComdats[C];
367 }
368 
369 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t Index) const {
370   return cast<FunctionSymbol>(Symbols[Index]);
371 }
372 
373 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t Index) const {
374   return cast<GlobalSymbol>(Symbols[Index]);
375 }
376 
377 EventSymbol *ObjFile::getEventSymbol(uint32_t Index) const {
378   return cast<EventSymbol>(Symbols[Index]);
379 }
380 
381 SectionSymbol *ObjFile::getSectionSymbol(uint32_t Index) const {
382   return cast<SectionSymbol>(Symbols[Index]);
383 }
384 
385 DataSymbol *ObjFile::getDataSymbol(uint32_t Index) const {
386   return cast<DataSymbol>(Symbols[Index]);
387 }
388 
389 Symbol *ObjFile::createDefined(const WasmSymbol &Sym) {
390   StringRef Name = Sym.Info.Name;
391   uint32_t Flags = Sym.Info.Flags;
392 
393   switch (Sym.Info.Kind) {
394   case WASM_SYMBOL_TYPE_FUNCTION: {
395     InputFunction *Func =
396         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
397     if (Func->Discarded)
398       return nullptr;
399     if (Sym.isBindingLocal())
400       return make<DefinedFunction>(Name, Flags, this, Func);
401     return Symtab->addDefinedFunction(Name, Flags, this, Func);
402   }
403   case WASM_SYMBOL_TYPE_DATA: {
404     InputSegment *Seg = Segments[Sym.Info.DataRef.Segment];
405     if (Seg->Discarded)
406       return nullptr;
407 
408     uint32_t Offset = Sym.Info.DataRef.Offset;
409     uint32_t Size = Sym.Info.DataRef.Size;
410 
411     if (Sym.isBindingLocal())
412       return make<DefinedData>(Name, Flags, this, Seg, Offset, Size);
413     return Symtab->addDefinedData(Name, Flags, this, Seg, Offset, Size);
414   }
415   case WASM_SYMBOL_TYPE_GLOBAL: {
416     InputGlobal *Global =
417         Globals[Sym.Info.ElementIndex - WasmObj->getNumImportedGlobals()];
418     if (Sym.isBindingLocal())
419       return make<DefinedGlobal>(Name, Flags, this, Global);
420     return Symtab->addDefinedGlobal(Name, Flags, this, Global);
421   }
422   case WASM_SYMBOL_TYPE_SECTION: {
423     InputSection *Section = CustomSectionsByIndex[Sym.Info.ElementIndex];
424     assert(Sym.isBindingLocal());
425     return make<SectionSymbol>(Flags, Section, this);
426   }
427   case WASM_SYMBOL_TYPE_EVENT: {
428     InputEvent *Event =
429         Events[Sym.Info.ElementIndex - WasmObj->getNumImportedEvents()];
430     if (Sym.isBindingLocal())
431       return make<DefinedEvent>(Name, Flags, this, Event);
432     return Symtab->addDefinedEvent(Name, Flags, this, Event);
433   }
434   }
435   llvm_unreachable("unknown symbol kind");
436 }
437 
438 Symbol *ObjFile::createUndefined(const WasmSymbol &Sym, bool IsCalledDirectly) {
439   StringRef Name = Sym.Info.Name;
440   uint32_t Flags = Sym.Info.Flags;
441 
442   switch (Sym.Info.Kind) {
443   case WASM_SYMBOL_TYPE_FUNCTION:
444     if (Sym.isBindingLocal())
445       return make<UndefinedFunction>(Name, Sym.Info.ImportName,
446                                      Sym.Info.ImportModule, Flags, this,
447                                      Sym.Signature, IsCalledDirectly);
448     return Symtab->addUndefinedFunction(Name, Sym.Info.ImportName,
449                                         Sym.Info.ImportModule, Flags, this,
450                                         Sym.Signature, IsCalledDirectly);
451   case WASM_SYMBOL_TYPE_DATA:
452     if (Sym.isBindingLocal())
453       return make<UndefinedData>(Name, Flags, this);
454     return Symtab->addUndefinedData(Name, Flags, this);
455   case WASM_SYMBOL_TYPE_GLOBAL:
456     if (Sym.isBindingLocal())
457       return make<UndefinedGlobal>(Name, Sym.Info.ImportName,
458                                    Sym.Info.ImportModule, Flags, this,
459                                    Sym.GlobalType);
460     return Symtab->addUndefinedGlobal(Name, Sym.Info.ImportName,
461                                       Sym.Info.ImportModule, Flags, this,
462                                       Sym.GlobalType);
463   case WASM_SYMBOL_TYPE_SECTION:
464     llvm_unreachable("section symbols cannot be undefined");
465   }
466   llvm_unreachable("unknown symbol kind");
467 }
468 
469 void ArchiveFile::parse() {
470   // Parse a MemoryBufferRef as an archive file.
471   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
472   File = CHECK(Archive::create(MB), toString(this));
473 
474   // Read the symbol table to construct Lazy symbols.
475   int Count = 0;
476   for (const Archive::Symbol &Sym : File->symbols()) {
477     Symtab->addLazy(this, &Sym);
478     ++Count;
479   }
480   LLVM_DEBUG(dbgs() << "Read " << Count << " symbols\n");
481 }
482 
483 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
484   const Archive::Child &C =
485       CHECK(Sym->getMember(),
486             "could not get the member for symbol " + Sym->getName());
487 
488   // Don't try to load the same member twice (this can happen when members
489   // mutually reference each other).
490   if (!Seen.insert(C.getChildOffset()).second)
491     return;
492 
493   LLVM_DEBUG(dbgs() << "loading lazy: " << Sym->getName() << "\n");
494   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
495 
496   MemoryBufferRef MB =
497       CHECK(C.getMemoryBufferRef(),
498             "could not get the buffer for the member defining symbol " +
499                 Sym->getName());
500 
501   InputFile *Obj = createObjectFile(MB, getName());
502   Symtab->addFile(Obj);
503 }
504 
505 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
506   switch (GvVisibility) {
507   case GlobalValue::DefaultVisibility:
508     return WASM_SYMBOL_VISIBILITY_DEFAULT;
509   case GlobalValue::HiddenVisibility:
510   case GlobalValue::ProtectedVisibility:
511     return WASM_SYMBOL_VISIBILITY_HIDDEN;
512   }
513   llvm_unreachable("unknown visibility");
514 }
515 
516 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
517                                    const lto::InputFile::Symbol &ObjSym,
518                                    BitcodeFile &F) {
519   StringRef Name = Saver.save(ObjSym.getName());
520 
521   uint32_t Flags = ObjSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
522   Flags |= mapVisibility(ObjSym.getVisibility());
523 
524   int C = ObjSym.getComdatIndex();
525   bool ExcludedByComdat = C != -1 && !KeptComdats[C];
526 
527   if (ObjSym.isUndefined() || ExcludedByComdat) {
528     if (ObjSym.isExecutable())
529       return Symtab->addUndefinedFunction(Name, Name, DefaultModule, Flags, &F,
530                                           nullptr, true);
531     return Symtab->addUndefinedData(Name, Flags, &F);
532   }
533 
534   if (ObjSym.isExecutable())
535     return Symtab->addDefinedFunction(Name, Flags, &F, nullptr);
536   return Symtab->addDefinedData(Name, Flags, &F, nullptr, 0, 0);
537 }
538 
539 void BitcodeFile::parse() {
540   Obj = check(lto::InputFile::create(MemoryBufferRef(
541       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier()))));
542   Triple T(Obj->getTargetTriple());
543   if (T.getArch() != Triple::wasm32) {
544     error(toString(MB.getBufferIdentifier()) + ": machine type must be wasm32");
545     return;
546   }
547   std::vector<bool> KeptComdats;
548   for (StringRef S : Obj->getComdatTable())
549     KeptComdats.push_back(Symtab->addComdat(S));
550 
551   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
552     Symbols.push_back(createBitcodeSymbol(KeptComdats, ObjSym, *this));
553 }
554 
555 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
556 std::string lld::toString(const wasm::InputFile *File) {
557   if (!File)
558     return "<internal>";
559 
560   if (File->ArchiveName.empty())
561     return File->getName();
562 
563   return (File->ArchiveName + "(" + File->getName() + ")").str();
564 }
565