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