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 llvm;
26 using namespace llvm::object;
27 using namespace llvm::wasm;
28 
29 namespace lld {
30 
31 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
32 std::string toString(const wasm::InputFile *file) {
33   if (!file)
34     return "<internal>";
35 
36   if (file->archiveName.empty())
37     return std::string(file->getName());
38 
39   return (file->archiveName + "(" + file->getName() + ")").str();
40 }
41 
42 namespace wasm {
43 std::unique_ptr<llvm::TarWriter> tar;
44 
45 Optional<MemoryBufferRef> readFile(StringRef path) {
46   log("Loading: " + path);
47 
48   auto mbOrErr = MemoryBuffer::getFile(path);
49   if (auto ec = mbOrErr.getError()) {
50     error("cannot open " + path + ": " + ec.message());
51     return None;
52   }
53   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
54   MemoryBufferRef mbref = mb->getMemBufferRef();
55   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
56 
57   if (tar)
58     tar->append(relativeToRoot(path), mbref.getBuffer());
59   return mbref;
60 }
61 
62 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName) {
63   file_magic magic = identify_magic(mb.getBuffer());
64   if (magic == file_magic::wasm_object) {
65     std::unique_ptr<Binary> bin =
66         CHECK(createBinary(mb), mb.getBufferIdentifier());
67     auto *obj = cast<WasmObjectFile>(bin.get());
68     if (obj->isSharedObject())
69       return make<SharedFile>(mb);
70     return make<ObjFile>(mb, archiveName);
71   }
72 
73   if (magic == file_magic::bitcode)
74     return make<BitcodeFile>(mb, archiveName);
75 
76   fatal("unknown file type: " + mb.getBufferIdentifier());
77 }
78 
79 void ObjFile::dumpInfo() const {
80   log("info for: " + toString(this) +
81       "\n              Symbols : " + Twine(symbols.size()) +
82       "\n     Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) +
83       "\n       Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) +
84       "\n        Event Imports : " + Twine(wasmObj->getNumImportedEvents()));
85 }
86 
87 // Relocations contain either symbol or type indices.  This function takes a
88 // relocation and returns relocated index (i.e. translates from the input
89 // symbol/type space to the output symbol/type space).
90 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
91   if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
92     assert(typeIsUsed[reloc.Index]);
93     return typeMap[reloc.Index];
94   }
95   const Symbol *sym = symbols[reloc.Index];
96   if (auto *ss = dyn_cast<SectionSymbol>(sym))
97     sym = ss->getOutputSectionSymbol();
98   return sym->getOutputSymbolIndex();
99 }
100 
101 // Relocations can contain addend for combined sections. This function takes a
102 // relocation and returns updated addend by offset in the output section.
103 uint64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
104   switch (reloc.Type) {
105   case R_WASM_MEMORY_ADDR_LEB:
106   case R_WASM_MEMORY_ADDR_LEB64:
107   case R_WASM_MEMORY_ADDR_SLEB64:
108   case R_WASM_MEMORY_ADDR_SLEB:
109   case R_WASM_MEMORY_ADDR_REL_SLEB:
110   case R_WASM_MEMORY_ADDR_REL_SLEB64:
111   case R_WASM_MEMORY_ADDR_I32:
112   case R_WASM_MEMORY_ADDR_I64:
113   case R_WASM_FUNCTION_OFFSET_I32:
114     return reloc.Addend;
115   case R_WASM_SECTION_OFFSET_I32:
116     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
117   default:
118     llvm_unreachable("unexpected relocation type");
119   }
120 }
121 
122 // Calculate the value we expect to find at the relocation location.
123 // This is used as a sanity check before applying a relocation to a given
124 // location.  It is useful for catching bugs in the compiler and linker.
125 uint64_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const {
126   switch (reloc.Type) {
127   case R_WASM_TABLE_INDEX_I32:
128   case R_WASM_TABLE_INDEX_I64:
129   case R_WASM_TABLE_INDEX_SLEB:
130   case R_WASM_TABLE_INDEX_SLEB64: {
131     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
132     return tableEntries[sym.Info.ElementIndex];
133   }
134   case R_WASM_TABLE_INDEX_REL_SLEB: {
135     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
136     return tableEntriesRel[sym.Info.ElementIndex];
137   }
138   case R_WASM_MEMORY_ADDR_LEB:
139   case R_WASM_MEMORY_ADDR_LEB64:
140   case R_WASM_MEMORY_ADDR_SLEB:
141   case R_WASM_MEMORY_ADDR_SLEB64:
142   case R_WASM_MEMORY_ADDR_REL_SLEB:
143   case R_WASM_MEMORY_ADDR_REL_SLEB64:
144   case R_WASM_MEMORY_ADDR_I32:
145   case R_WASM_MEMORY_ADDR_I64: {
146     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
147     if (sym.isUndefined())
148       return 0;
149     const WasmSegment &segment =
150         wasmObj->dataSegments()[sym.Info.DataRef.Segment];
151     if (segment.Data.Offset.Opcode == WASM_OPCODE_I32_CONST)
152       return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset +
153              reloc.Addend;
154     else if (segment.Data.Offset.Opcode == WASM_OPCODE_I64_CONST)
155       return segment.Data.Offset.Value.Int64 + sym.Info.DataRef.Offset +
156              reloc.Addend;
157     else
158       llvm_unreachable("unknown init expr opcode");
159   }
160   case R_WASM_FUNCTION_OFFSET_I32: {
161     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
162     InputFunction *f =
163         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
164     return f->getFunctionInputOffset() + f->getFunctionCodeOffset() +
165            reloc.Addend;
166   }
167   case R_WASM_SECTION_OFFSET_I32:
168     return reloc.Addend;
169   case R_WASM_TYPE_INDEX_LEB:
170     return reloc.Index;
171   case R_WASM_FUNCTION_INDEX_LEB:
172   case R_WASM_GLOBAL_INDEX_LEB:
173   case R_WASM_GLOBAL_INDEX_I32:
174   case R_WASM_EVENT_INDEX_LEB: {
175     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
176     return sym.Info.ElementIndex;
177   }
178   default:
179     llvm_unreachable("unknown relocation type");
180   }
181 }
182 
183 // Translate from the relocation's index into the final linked output value.
184 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc) const {
185   const Symbol* sym = nullptr;
186   if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
187     sym = symbols[reloc.Index];
188 
189     // We can end up with relocations against non-live symbols.  For example
190     // in debug sections. We return reloc.Addend because always returning zero
191     // causes the generation of spurious range-list terminators in the
192     // .debug_ranges section.
193     if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive())
194       return reloc.Addend;
195   }
196 
197   switch (reloc.Type) {
198   case R_WASM_TABLE_INDEX_I32:
199   case R_WASM_TABLE_INDEX_I64:
200   case R_WASM_TABLE_INDEX_SLEB:
201   case R_WASM_TABLE_INDEX_SLEB64:
202   case R_WASM_TABLE_INDEX_REL_SLEB: {
203     if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
204       return 0;
205     uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
206     if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB)
207       index -= config->tableBase;
208     return index;
209 
210   }
211   case R_WASM_MEMORY_ADDR_LEB:
212   case R_WASM_MEMORY_ADDR_LEB64:
213   case R_WASM_MEMORY_ADDR_SLEB:
214   case R_WASM_MEMORY_ADDR_SLEB64:
215   case R_WASM_MEMORY_ADDR_REL_SLEB:
216   case R_WASM_MEMORY_ADDR_REL_SLEB64:
217   case R_WASM_MEMORY_ADDR_I32:
218   case R_WASM_MEMORY_ADDR_I64:
219     if (isa<UndefinedData>(sym) || sym->isUndefWeak())
220       return 0;
221     return cast<DefinedData>(sym)->getVirtualAddress() + reloc.Addend;
222   case R_WASM_TYPE_INDEX_LEB:
223     return typeMap[reloc.Index];
224   case R_WASM_FUNCTION_INDEX_LEB:
225     return getFunctionSymbol(reloc.Index)->getFunctionIndex();
226   case R_WASM_GLOBAL_INDEX_LEB:
227   case R_WASM_GLOBAL_INDEX_I32:
228     if (auto gs = dyn_cast<GlobalSymbol>(sym))
229       return gs->getGlobalIndex();
230     return sym->getGOTIndex();
231   case R_WASM_EVENT_INDEX_LEB:
232     return getEventSymbol(reloc.Index)->getEventIndex();
233   case R_WASM_FUNCTION_OFFSET_I32: {
234     auto *f = cast<DefinedFunction>(sym);
235     return f->function->outputOffset +
236            (f->function->getFunctionCodeOffset() + reloc.Addend);
237   }
238   case R_WASM_SECTION_OFFSET_I32:
239     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
240   default:
241     llvm_unreachable("unknown relocation type");
242   }
243 }
244 
245 template <class T>
246 static void setRelocs(const std::vector<T *> &chunks,
247                       const WasmSection *section) {
248   if (!section)
249     return;
250 
251   ArrayRef<WasmRelocation> relocs = section->Relocations;
252   assert(llvm::is_sorted(
253       relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
254         return r1.Offset < r2.Offset;
255       }));
256   assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
257     return c1->getInputSectionOffset() < c2->getInputSectionOffset();
258   }));
259 
260   auto relocsNext = relocs.begin();
261   auto relocsEnd = relocs.end();
262   auto relocLess = [](const WasmRelocation &r, uint32_t val) {
263     return r.Offset < val;
264   };
265   for (InputChunk *c : chunks) {
266     auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
267                                         c->getInputSectionOffset(), relocLess);
268     relocsNext = std::lower_bound(
269         relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
270         relocLess);
271     c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
272   }
273 }
274 
275 void ObjFile::parse(bool ignoreComdats) {
276   // Parse a memory buffer as a wasm file.
277   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
278   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
279 
280   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
281   if (!obj)
282     fatal(toString(this) + ": not a wasm file");
283   if (!obj->isRelocatableObject())
284     fatal(toString(this) + ": not a relocatable wasm file");
285 
286   bin.release();
287   wasmObj.reset(obj);
288 
289   // Build up a map of function indices to table indices for use when
290   // verifying the existing table index relocations
291   uint32_t totalFunctions =
292       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
293   tableEntriesRel.resize(totalFunctions);
294   tableEntries.resize(totalFunctions);
295   for (const WasmElemSegment &seg : wasmObj->elements()) {
296     int64_t offset;
297     if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST)
298       offset = seg.Offset.Value.Int32;
299     else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST)
300       offset = seg.Offset.Value.Int64;
301     else
302       fatal(toString(this) + ": invalid table elements");
303     for (size_t index = 0; index < seg.Functions.size(); index++) {
304       auto functionIndex = seg.Functions[index];
305       tableEntriesRel[functionIndex] = index;
306       tableEntries[functionIndex] = offset + index;
307     }
308   }
309 
310   uint32_t sectionIndex = 0;
311 
312   // Bool for each symbol, true if called directly.  This allows us to implement
313   // a weaker form of signature checking where undefined functions that are not
314   // called directly (i.e. only address taken) don't have to match the defined
315   // function's signature.  We cannot do this for directly called functions
316   // because those signatures are checked at validation times.
317   // See https://bugs.llvm.org/show_bug.cgi?id=40412
318   std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
319   for (const SectionRef &sec : wasmObj->sections()) {
320     const WasmSection &section = wasmObj->getWasmSection(sec);
321     // Wasm objects can have at most one code and one data section.
322     if (section.Type == WASM_SEC_CODE) {
323       assert(!codeSection);
324       codeSection = &section;
325     } else if (section.Type == WASM_SEC_DATA) {
326       assert(!dataSection);
327       dataSection = &section;
328     } else if (section.Type == WASM_SEC_CUSTOM) {
329       customSections.emplace_back(make<InputSection>(section, this));
330       customSections.back()->setRelocations(section.Relocations);
331       customSectionsByIndex[sectionIndex] = customSections.back();
332     }
333     sectionIndex++;
334     // Scans relocations to determine if a function symbol is called directly.
335     for (const WasmRelocation &reloc : section.Relocations)
336       if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
337         isCalledDirectly[reloc.Index] = true;
338   }
339 
340   typeMap.resize(getWasmObj()->types().size());
341   typeIsUsed.resize(getWasmObj()->types().size(), false);
342 
343   ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
344   for (StringRef comdat : comdats) {
345     bool isNew = ignoreComdats || symtab->addComdat(comdat);
346     keptComdats.push_back(isNew);
347   }
348 
349   // Populate `Segments`.
350   for (const WasmSegment &s : wasmObj->dataSegments()) {
351     auto* seg = make<InputSegment>(s, this);
352     seg->discarded = isExcludedByComdat(seg);
353     segments.emplace_back(seg);
354   }
355   setRelocs(segments, dataSection);
356 
357   // Populate `Functions`.
358   ArrayRef<WasmFunction> funcs = wasmObj->functions();
359   ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes();
360   ArrayRef<WasmSignature> types = wasmObj->types();
361   functions.reserve(funcs.size());
362 
363   for (size_t i = 0, e = funcs.size(); i != e; ++i) {
364     auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this);
365     func->discarded = isExcludedByComdat(func);
366     functions.emplace_back(func);
367   }
368   setRelocs(functions, codeSection);
369 
370   // Populate `Globals`.
371   for (const WasmGlobal &g : wasmObj->globals())
372     globals.emplace_back(make<InputGlobal>(g, this));
373 
374   // Populate `Events`.
375   for (const WasmEvent &e : wasmObj->events())
376     events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this));
377 
378   // Populate `Symbols` based on the symbols in the object.
379   symbols.reserve(wasmObj->getNumberOfSymbols());
380   for (const SymbolRef &sym : wasmObj->symbols()) {
381     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
382     if (wasmSym.isDefined()) {
383       // createDefined may fail if the symbol is comdat excluded in which case
384       // we fall back to creating an undefined symbol
385       if (Symbol *d = createDefined(wasmSym)) {
386         symbols.push_back(d);
387         continue;
388       }
389     }
390     size_t idx = symbols.size();
391     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
392   }
393 }
394 
395 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const {
396   uint32_t c = chunk->getComdat();
397   if (c == UINT32_MAX)
398     return false;
399   return !keptComdats[c];
400 }
401 
402 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
403   return cast<FunctionSymbol>(symbols[index]);
404 }
405 
406 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
407   return cast<GlobalSymbol>(symbols[index]);
408 }
409 
410 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const {
411   return cast<EventSymbol>(symbols[index]);
412 }
413 
414 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
415   return cast<SectionSymbol>(symbols[index]);
416 }
417 
418 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
419   return cast<DataSymbol>(symbols[index]);
420 }
421 
422 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
423   StringRef name = sym.Info.Name;
424   uint32_t flags = sym.Info.Flags;
425 
426   switch (sym.Info.Kind) {
427   case WASM_SYMBOL_TYPE_FUNCTION: {
428     InputFunction *func =
429         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
430     if (sym.isBindingLocal())
431       return make<DefinedFunction>(name, flags, this, func);
432     if (func->discarded)
433       return nullptr;
434     return symtab->addDefinedFunction(name, flags, this, func);
435   }
436   case WASM_SYMBOL_TYPE_DATA: {
437     InputSegment *seg = segments[sym.Info.DataRef.Segment];
438     auto offset = sym.Info.DataRef.Offset;
439     auto size = sym.Info.DataRef.Size;
440     if (sym.isBindingLocal())
441       return make<DefinedData>(name, flags, this, seg, offset, size);
442     if (seg->discarded)
443       return nullptr;
444     return symtab->addDefinedData(name, flags, this, seg, offset, size);
445   }
446   case WASM_SYMBOL_TYPE_GLOBAL: {
447     InputGlobal *global =
448         globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
449     if (sym.isBindingLocal())
450       return make<DefinedGlobal>(name, flags, this, global);
451     return symtab->addDefinedGlobal(name, flags, this, global);
452   }
453   case WASM_SYMBOL_TYPE_SECTION: {
454     InputSection *section = customSectionsByIndex[sym.Info.ElementIndex];
455     assert(sym.isBindingLocal());
456     return make<SectionSymbol>(flags, section, this);
457   }
458   case WASM_SYMBOL_TYPE_EVENT: {
459     InputEvent *event =
460         events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()];
461     if (sym.isBindingLocal())
462       return make<DefinedEvent>(name, flags, this, event);
463     return symtab->addDefinedEvent(name, flags, this, event);
464   }
465   }
466   llvm_unreachable("unknown symbol kind");
467 }
468 
469 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
470   StringRef name = sym.Info.Name;
471   uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
472 
473   switch (sym.Info.Kind) {
474   case WASM_SYMBOL_TYPE_FUNCTION:
475     if (sym.isBindingLocal())
476       return make<UndefinedFunction>(name, sym.Info.ImportName,
477                                      sym.Info.ImportModule, flags, this,
478                                      sym.Signature, isCalledDirectly);
479     return symtab->addUndefinedFunction(name, sym.Info.ImportName,
480                                         sym.Info.ImportModule, flags, this,
481                                         sym.Signature, isCalledDirectly);
482   case WASM_SYMBOL_TYPE_DATA:
483     if (sym.isBindingLocal())
484       return make<UndefinedData>(name, flags, this);
485     return symtab->addUndefinedData(name, flags, this);
486   case WASM_SYMBOL_TYPE_GLOBAL:
487     if (sym.isBindingLocal())
488       return make<UndefinedGlobal>(name, sym.Info.ImportName,
489                                    sym.Info.ImportModule, flags, this,
490                                    sym.GlobalType);
491     return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
492                                       sym.Info.ImportModule, flags, this,
493                                       sym.GlobalType);
494   case WASM_SYMBOL_TYPE_SECTION:
495     llvm_unreachable("section symbols cannot be undefined");
496   }
497   llvm_unreachable("unknown symbol kind");
498 }
499 
500 void ArchiveFile::parse() {
501   // Parse a MemoryBufferRef as an archive file.
502   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
503   file = CHECK(Archive::create(mb), toString(this));
504 
505   // Read the symbol table to construct Lazy symbols.
506   int count = 0;
507   for (const Archive::Symbol &sym : file->symbols()) {
508     symtab->addLazy(this, &sym);
509     ++count;
510   }
511   LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
512 }
513 
514 void ArchiveFile::addMember(const Archive::Symbol *sym) {
515   const Archive::Child &c =
516       CHECK(sym->getMember(),
517             "could not get the member for symbol " + sym->getName());
518 
519   // Don't try to load the same member twice (this can happen when members
520   // mutually reference each other).
521   if (!seen.insert(c.getChildOffset()).second)
522     return;
523 
524   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
525   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
526 
527   MemoryBufferRef mb =
528       CHECK(c.getMemoryBufferRef(),
529             "could not get the buffer for the member defining symbol " +
530                 sym->getName());
531 
532   InputFile *obj = createObjectFile(mb, getName());
533   symtab->addFile(obj);
534 }
535 
536 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
537   switch (gvVisibility) {
538   case GlobalValue::DefaultVisibility:
539     return WASM_SYMBOL_VISIBILITY_DEFAULT;
540   case GlobalValue::HiddenVisibility:
541   case GlobalValue::ProtectedVisibility:
542     return WASM_SYMBOL_VISIBILITY_HIDDEN;
543   }
544   llvm_unreachable("unknown visibility");
545 }
546 
547 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
548                                    const lto::InputFile::Symbol &objSym,
549                                    BitcodeFile &f) {
550   StringRef name = saver.save(objSym.getName());
551 
552   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
553   flags |= mapVisibility(objSym.getVisibility());
554 
555   int c = objSym.getComdatIndex();
556   bool excludedByComdat = c != -1 && !keptComdats[c];
557 
558   if (objSym.isUndefined() || excludedByComdat) {
559     flags |= WASM_SYMBOL_UNDEFINED;
560     if (objSym.isExecutable())
561       return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
562                                           true);
563     return symtab->addUndefinedData(name, flags, &f);
564   }
565 
566   if (objSym.isExecutable())
567     return symtab->addDefinedFunction(name, flags, &f, nullptr);
568   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
569 }
570 
571 bool BitcodeFile::doneLTO = false;
572 
573 void BitcodeFile::parse() {
574   if (doneLTO) {
575     error(toString(this) + ": attempt to add bitcode file after LTO.");
576     return;
577   }
578 
579   obj = check(lto::InputFile::create(MemoryBufferRef(
580       mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier()))));
581   Triple t(obj->getTargetTriple());
582   if (!t.isWasm()) {
583     error(toString(this) + ": machine type must be wasm32 or wasm64");
584     return;
585   }
586   bool is64 = t.getArch() == Triple::wasm64;
587   if (config->is64.hasValue() && *config->is64 != is64) {
588     error(toString(this) + ": machine type for all bitcode files must match");
589     return;
590   }
591   config->is64 = is64;
592   std::vector<bool> keptComdats;
593   for (StringRef s : obj->getComdatTable())
594     keptComdats.push_back(symtab->addComdat(s));
595 
596   for (const lto::InputFile::Symbol &objSym : obj->symbols())
597     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
598 }
599 
600 } // namespace wasm
601 } // namespace lld
602