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 "InputElement.h"
13 #include "OutputSegment.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/Path.h"
21 #include "llvm/Support/TarWriter.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 #define DEBUG_TYPE "lld"
25 
26 using namespace llvm;
27 using namespace llvm::object;
28 using namespace llvm::wasm;
29 using namespace llvm::sys;
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                             uint64_t offsetInArchive) {
78   file_magic magic = identify_magic(mb.getBuffer());
79   if (magic == file_magic::wasm_object) {
80     std::unique_ptr<Binary> bin =
81         CHECK(createBinary(mb), mb.getBufferIdentifier());
82     auto *obj = cast<WasmObjectFile>(bin.get());
83     if (obj->isSharedObject())
84       return make<SharedFile>(mb);
85     return make<ObjFile>(mb, archiveName);
86   }
87 
88   if (magic == file_magic::bitcode)
89     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
90 
91   fatal("unknown file type: " + mb.getBufferIdentifier());
92 }
93 
94 // Relocations contain either symbol or type indices.  This function takes a
95 // relocation and returns relocated index (i.e. translates from the input
96 // symbol/type space to the output symbol/type space).
97 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
98   if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
99     assert(typeIsUsed[reloc.Index]);
100     return typeMap[reloc.Index];
101   }
102   const Symbol *sym = symbols[reloc.Index];
103   if (auto *ss = dyn_cast<SectionSymbol>(sym))
104     sym = ss->getOutputSectionSymbol();
105   return sym->getOutputSymbolIndex();
106 }
107 
108 // Relocations can contain addend for combined sections. This function takes a
109 // relocation and returns updated addend by offset in the output section.
110 uint64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
111   switch (reloc.Type) {
112   case R_WASM_MEMORY_ADDR_LEB:
113   case R_WASM_MEMORY_ADDR_LEB64:
114   case R_WASM_MEMORY_ADDR_SLEB64:
115   case R_WASM_MEMORY_ADDR_SLEB:
116   case R_WASM_MEMORY_ADDR_REL_SLEB:
117   case R_WASM_MEMORY_ADDR_REL_SLEB64:
118   case R_WASM_MEMORY_ADDR_I32:
119   case R_WASM_MEMORY_ADDR_I64:
120   case R_WASM_MEMORY_ADDR_TLS_SLEB:
121   case R_WASM_MEMORY_ADDR_TLS_SLEB64:
122   case R_WASM_FUNCTION_OFFSET_I32:
123   case R_WASM_FUNCTION_OFFSET_I64:
124   case R_WASM_MEMORY_ADDR_LOCREL_I32:
125     return reloc.Addend;
126   case R_WASM_SECTION_OFFSET_I32:
127     return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
128   default:
129     llvm_unreachable("unexpected relocation type");
130   }
131 }
132 
133 // Translate from the relocation's index into the final linked output value.
134 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone,
135                                const InputChunk *chunk) const {
136   const Symbol* sym = nullptr;
137   if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
138     sym = symbols[reloc.Index];
139 
140     // We can end up with relocations against non-live symbols.  For example
141     // in debug sections. We return a tombstone value in debug symbol sections
142     // so this will not produce a valid range conflicting with ranges of actual
143     // code. In other sections we return reloc.Addend.
144 
145     if (!isa<SectionSymbol>(sym) && !sym->isLive())
146       return tombstone ? tombstone : reloc.Addend;
147   }
148 
149   switch (reloc.Type) {
150   case R_WASM_TABLE_INDEX_I32:
151   case R_WASM_TABLE_INDEX_I64:
152   case R_WASM_TABLE_INDEX_SLEB:
153   case R_WASM_TABLE_INDEX_SLEB64:
154   case R_WASM_TABLE_INDEX_REL_SLEB:
155   case R_WASM_TABLE_INDEX_REL_SLEB64: {
156     if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
157       return 0;
158     uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
159     if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB ||
160         reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB64)
161       index -= config->tableBase;
162     return index;
163   }
164   case R_WASM_MEMORY_ADDR_LEB:
165   case R_WASM_MEMORY_ADDR_LEB64:
166   case R_WASM_MEMORY_ADDR_SLEB:
167   case R_WASM_MEMORY_ADDR_SLEB64:
168   case R_WASM_MEMORY_ADDR_REL_SLEB:
169   case R_WASM_MEMORY_ADDR_REL_SLEB64:
170   case R_WASM_MEMORY_ADDR_I32:
171   case R_WASM_MEMORY_ADDR_I64:
172   case R_WASM_MEMORY_ADDR_TLS_SLEB:
173   case R_WASM_MEMORY_ADDR_TLS_SLEB64:
174   case R_WASM_MEMORY_ADDR_LOCREL_I32: {
175     if (isa<UndefinedData>(sym) || sym->isUndefWeak())
176       return 0;
177     auto D = cast<DefinedData>(sym);
178     uint64_t value = D->getVA() + reloc.Addend;
179     if (reloc.Type == R_WASM_MEMORY_ADDR_LOCREL_I32) {
180       const auto *segment = cast<InputSegment>(chunk);
181       uint64_t p = segment->outputSeg->startVA + segment->outputSegmentOffset +
182                    reloc.Offset - segment->getInputSectionOffset();
183       value -= p;
184     }
185     return value;
186   }
187   case R_WASM_TYPE_INDEX_LEB:
188     return typeMap[reloc.Index];
189   case R_WASM_FUNCTION_INDEX_LEB:
190     return getFunctionSymbol(reloc.Index)->getFunctionIndex();
191   case R_WASM_GLOBAL_INDEX_LEB:
192   case R_WASM_GLOBAL_INDEX_I32:
193     if (auto gs = dyn_cast<GlobalSymbol>(sym))
194       return gs->getGlobalIndex();
195     return sym->getGOTIndex();
196   case R_WASM_TAG_INDEX_LEB:
197     return getTagSymbol(reloc.Index)->getTagIndex();
198   case R_WASM_FUNCTION_OFFSET_I32:
199   case R_WASM_FUNCTION_OFFSET_I64: {
200     auto *f = cast<DefinedFunction>(sym);
201     return f->function->getOffset(f->function->getFunctionCodeOffset() +
202                                   reloc.Addend);
203   }
204   case R_WASM_SECTION_OFFSET_I32:
205     return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
206   case R_WASM_TABLE_NUMBER_LEB:
207     return getTableSymbol(reloc.Index)->getTableNumber();
208   default:
209     llvm_unreachable("unknown relocation type");
210   }
211 }
212 
213 template <class T>
214 static void setRelocs(const std::vector<T *> &chunks,
215                       const WasmSection *section) {
216   if (!section)
217     return;
218 
219   ArrayRef<WasmRelocation> relocs = section->Relocations;
220   assert(llvm::is_sorted(
221       relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
222         return r1.Offset < r2.Offset;
223       }));
224   assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
225     return c1->getInputSectionOffset() < c2->getInputSectionOffset();
226   }));
227 
228   auto relocsNext = relocs.begin();
229   auto relocsEnd = relocs.end();
230   auto relocLess = [](const WasmRelocation &r, uint32_t val) {
231     return r.Offset < val;
232   };
233   for (InputChunk *c : chunks) {
234     auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
235                                         c->getInputSectionOffset(), relocLess);
236     relocsNext = std::lower_bound(
237         relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
238         relocLess);
239     c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
240   }
241 }
242 
243 // An object file can have two approaches to tables.  With the reference-types
244 // feature enabled, input files that define or use tables declare the tables
245 // using symbols, and record each use with a relocation.  This way when the
246 // linker combines inputs, it can collate the tables used by the inputs,
247 // assigning them distinct table numbers, and renumber all the uses as
248 // appropriate.  At the same time, the linker has special logic to build the
249 // indirect function table if it is needed.
250 //
251 // However, MVP object files (those that target WebAssembly 1.0, the "minimum
252 // viable product" version of WebAssembly) neither write table symbols nor
253 // record relocations.  These files can have at most one table, the indirect
254 // function table used by call_indirect and which is the address space for
255 // function pointers.  If this table is present, it is always an import.  If we
256 // have a file with a table import but no table symbols, it is an MVP object
257 // file.  synthesizeMVPIndirectFunctionTableSymbolIfNeeded serves as a shim when
258 // loading these input files, defining the missing symbol to allow the indirect
259 // function table to be built.
260 //
261 // As indirect function table table usage in MVP objects cannot be relocated,
262 // the linker must ensure that this table gets assigned index zero.
263 void ObjFile::addLegacyIndirectFunctionTableIfNeeded(
264     uint32_t tableSymbolCount) {
265   uint32_t tableCount = wasmObj->getNumImportedTables() + tables.size();
266 
267   // If there are symbols for all tables, then all is good.
268   if (tableCount == tableSymbolCount)
269     return;
270 
271   // It's possible for an input to define tables and also use the indirect
272   // function table, but forget to compile with -mattr=+reference-types.
273   // For these newer files, we require symbols for all tables, and
274   // relocations for all of their uses.
275   if (tableSymbolCount != 0) {
276     error(toString(this) +
277           ": expected one symbol table entry for each of the " +
278           Twine(tableCount) + " table(s) present, but got " +
279           Twine(tableSymbolCount) + " symbol(s) instead.");
280     return;
281   }
282 
283   // An MVP object file can have up to one table import, for the indirect
284   // function table, but will have no table definitions.
285   if (tables.size()) {
286     error(toString(this) +
287           ": unexpected table definition(s) without corresponding "
288           "symbol-table entries.");
289     return;
290   }
291 
292   // An MVP object file can have only one table import.
293   if (tableCount != 1) {
294     error(toString(this) +
295           ": multiple table imports, but no corresponding symbol-table "
296           "entries.");
297     return;
298   }
299 
300   const WasmImport *tableImport = nullptr;
301   for (const auto &import : wasmObj->imports()) {
302     if (import.Kind == WASM_EXTERNAL_TABLE) {
303       assert(!tableImport);
304       tableImport = &import;
305     }
306   }
307   assert(tableImport);
308 
309   // We can only synthesize a symtab entry for the indirect function table; if
310   // it has an unexpected name or type, assume that it's not actually the
311   // indirect function table.
312   if (tableImport->Field != functionTableName ||
313       tableImport->Table.ElemType != uint8_t(ValType::FUNCREF)) {
314     error(toString(this) + ": table import " + Twine(tableImport->Field) +
315           " is missing a symbol table entry.");
316     return;
317   }
318 
319   auto *info = make<WasmSymbolInfo>();
320   info->Name = tableImport->Field;
321   info->Kind = WASM_SYMBOL_TYPE_TABLE;
322   info->ImportModule = tableImport->Module;
323   info->ImportName = tableImport->Field;
324   info->Flags = WASM_SYMBOL_UNDEFINED;
325   info->Flags |= WASM_SYMBOL_NO_STRIP;
326   info->ElementIndex = 0;
327   LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " << info->Name
328                     << "\n");
329   const WasmGlobalType *globalType = nullptr;
330   const WasmSignature *signature = nullptr;
331   auto *wasmSym =
332       make<WasmSymbol>(*info, globalType, &tableImport->Table, signature);
333   Symbol *sym = createUndefined(*wasmSym, false);
334   // We're only sure it's a TableSymbol if the createUndefined succeeded.
335   if (errorCount())
336     return;
337   symbols.push_back(sym);
338   // Because there are no TABLE_NUMBER relocs, we can't compute accurate
339   // liveness info; instead, just mark the symbol as always live.
340   sym->markLive();
341 
342   // We assume that this compilation unit has unrelocatable references to
343   // this table.
344   config->legacyFunctionTable = true;
345 }
346 
347 static bool shouldMerge(const WasmSection &sec) {
348   if (config->optimize == 0)
349     return false;
350   // Sadly we don't have section attributes yet for custom sections, so we
351   // currently go by the name alone.
352   // TODO(sbc): Add ability for wasm sections to carry flags so we don't
353   // need to use names here.
354   // For now, keep in sync with uses of wasm::WASM_SEG_FLAG_STRINGS in
355   // MCObjectFileInfo::initWasmMCObjectFileInfo which creates these custom
356   // sections.
357   return sec.Name == ".debug_str" || sec.Name == ".debug_str.dwo" ||
358          sec.Name == ".debug_line_str";
359 }
360 
361 static bool shouldMerge(const WasmSegment &seg) {
362   // As of now we only support merging strings, and only with single byte
363   // alignment (2^0).
364   if (!(seg.Data.LinkingFlags & WASM_SEG_FLAG_STRINGS) ||
365       (seg.Data.Alignment != 0))
366     return false;
367 
368   // On a regular link we don't merge sections if -O0 (default is -O1). This
369   // sometimes makes the linker significantly faster, although the output will
370   // be bigger.
371   if (config->optimize == 0)
372     return false;
373 
374   // A mergeable section with size 0 is useless because they don't have
375   // any data to merge. A mergeable string section with size 0 can be
376   // argued as invalid because it doesn't end with a null character.
377   // We'll avoid a mess by handling them as if they were non-mergeable.
378   if (seg.Data.Content.size() == 0)
379     return false;
380 
381   return true;
382 }
383 
384 void ObjFile::parse(bool ignoreComdats) {
385   // Parse a memory buffer as a wasm file.
386   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
387   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
388 
389   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
390   if (!obj)
391     fatal(toString(this) + ": not a wasm file");
392   if (!obj->isRelocatableObject())
393     fatal(toString(this) + ": not a relocatable wasm file");
394 
395   bin.release();
396   wasmObj.reset(obj);
397 
398   checkArch(obj->getArch());
399 
400   // Build up a map of function indices to table indices for use when
401   // verifying the existing table index relocations
402   uint32_t totalFunctions =
403       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
404   tableEntriesRel.resize(totalFunctions);
405   tableEntries.resize(totalFunctions);
406   for (const WasmElemSegment &seg : wasmObj->elements()) {
407     int64_t offset;
408     if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST)
409       offset = seg.Offset.Value.Int32;
410     else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST)
411       offset = seg.Offset.Value.Int64;
412     else
413       fatal(toString(this) + ": invalid table elements");
414     for (size_t index = 0; index < seg.Functions.size(); index++) {
415       auto functionIndex = seg.Functions[index];
416       tableEntriesRel[functionIndex] = index;
417       tableEntries[functionIndex] = offset + index;
418     }
419   }
420 
421   ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
422   for (StringRef comdat : comdats) {
423     bool isNew = ignoreComdats || symtab->addComdat(comdat);
424     keptComdats.push_back(isNew);
425   }
426 
427   uint32_t sectionIndex = 0;
428 
429   // Bool for each symbol, true if called directly.  This allows us to implement
430   // a weaker form of signature checking where undefined functions that are not
431   // called directly (i.e. only address taken) don't have to match the defined
432   // function's signature.  We cannot do this for directly called functions
433   // because those signatures are checked at validation times.
434   // See https://bugs.llvm.org/show_bug.cgi?id=40412
435   std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
436   for (const SectionRef &sec : wasmObj->sections()) {
437     const WasmSection &section = wasmObj->getWasmSection(sec);
438     // Wasm objects can have at most one code and one data section.
439     if (section.Type == WASM_SEC_CODE) {
440       assert(!codeSection);
441       codeSection = &section;
442     } else if (section.Type == WASM_SEC_DATA) {
443       assert(!dataSection);
444       dataSection = &section;
445     } else if (section.Type == WASM_SEC_CUSTOM) {
446       InputChunk *customSec;
447       if (shouldMerge(section))
448         customSec = make<MergeInputChunk>(section, this);
449       else
450         customSec = make<InputSection>(section, this);
451       customSec->discarded = isExcludedByComdat(customSec);
452       customSections.emplace_back(customSec);
453       customSections.back()->setRelocations(section.Relocations);
454       customSectionsByIndex[sectionIndex] = customSections.back();
455     }
456     sectionIndex++;
457     // Scans relocations to determine if a function symbol is called directly.
458     for (const WasmRelocation &reloc : section.Relocations)
459       if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
460         isCalledDirectly[reloc.Index] = true;
461   }
462 
463   typeMap.resize(getWasmObj()->types().size());
464   typeIsUsed.resize(getWasmObj()->types().size(), false);
465 
466 
467   // Populate `Segments`.
468   for (const WasmSegment &s : wasmObj->dataSegments()) {
469     InputChunk *seg;
470     if (shouldMerge(s)) {
471       seg = make<MergeInputChunk>(s, this);
472     } else
473       seg = make<InputSegment>(s, this);
474     seg->discarded = isExcludedByComdat(seg);
475     // Older object files did not include WASM_SEG_FLAG_TLS and instead
476     // relied on the naming convention.  To maintain compat with such objects
477     // we still imply the TLS flag based on the name of the segment.
478     if (!seg->isTLS() &&
479         (seg->name.startswith(".tdata") || seg->name.startswith(".tbss"))) {
480       seg->flags |= WASM_SEG_FLAG_TLS;
481       seg->implicitTLS = true;
482     }
483     segments.emplace_back(seg);
484   }
485   setRelocs(segments, dataSection);
486 
487   // Populate `Functions`.
488   ArrayRef<WasmFunction> funcs = wasmObj->functions();
489   ArrayRef<WasmSignature> types = wasmObj->types();
490   functions.reserve(funcs.size());
491 
492   for (auto &f : funcs) {
493     auto *func = make<InputFunction>(types[f.SigIndex], &f, this);
494     func->discarded = isExcludedByComdat(func);
495     functions.emplace_back(func);
496   }
497   setRelocs(functions, codeSection);
498 
499   // Populate `Tables`.
500   for (const WasmTable &t : wasmObj->tables())
501     tables.emplace_back(make<InputTable>(t, this));
502 
503   // Populate `Globals`.
504   for (const WasmGlobal &g : wasmObj->globals())
505     globals.emplace_back(make<InputGlobal>(g, this));
506 
507   // Populate `Tags`.
508   for (const WasmTag &t : wasmObj->tags())
509     tags.emplace_back(make<InputTag>(types[t.SigIndex], t, this));
510 
511   // Populate `Symbols` based on the symbols in the object.
512   symbols.reserve(wasmObj->getNumberOfSymbols());
513   uint32_t tableSymbolCount = 0;
514   for (const SymbolRef &sym : wasmObj->symbols()) {
515     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
516     if (wasmSym.isTypeTable())
517       tableSymbolCount++;
518     if (wasmSym.isDefined()) {
519       // createDefined may fail if the symbol is comdat excluded in which case
520       // we fall back to creating an undefined symbol
521       if (Symbol *d = createDefined(wasmSym)) {
522         symbols.push_back(d);
523         continue;
524       }
525     }
526     size_t idx = symbols.size();
527     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
528   }
529 
530   addLegacyIndirectFunctionTableIfNeeded(tableSymbolCount);
531 }
532 
533 bool ObjFile::isExcludedByComdat(const InputChunk *chunk) const {
534   uint32_t c = chunk->getComdat();
535   if (c == UINT32_MAX)
536     return false;
537   return !keptComdats[c];
538 }
539 
540 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
541   return cast<FunctionSymbol>(symbols[index]);
542 }
543 
544 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
545   return cast<GlobalSymbol>(symbols[index]);
546 }
547 
548 TagSymbol *ObjFile::getTagSymbol(uint32_t index) const {
549   return cast<TagSymbol>(symbols[index]);
550 }
551 
552 TableSymbol *ObjFile::getTableSymbol(uint32_t index) const {
553   return cast<TableSymbol>(symbols[index]);
554 }
555 
556 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
557   return cast<SectionSymbol>(symbols[index]);
558 }
559 
560 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
561   return cast<DataSymbol>(symbols[index]);
562 }
563 
564 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
565   StringRef name = sym.Info.Name;
566   uint32_t flags = sym.Info.Flags;
567 
568   switch (sym.Info.Kind) {
569   case WASM_SYMBOL_TYPE_FUNCTION: {
570     InputFunction *func =
571         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
572     if (sym.isBindingLocal())
573       return make<DefinedFunction>(name, flags, this, func);
574     if (func->discarded)
575       return nullptr;
576     return symtab->addDefinedFunction(name, flags, this, func);
577   }
578   case WASM_SYMBOL_TYPE_DATA: {
579     InputChunk *seg = segments[sym.Info.DataRef.Segment];
580     auto offset = sym.Info.DataRef.Offset;
581     auto size = sym.Info.DataRef.Size;
582     if (seg->implicitTLS) {
583       flags |= WASM_SYMBOL_TLS;
584     }
585     if (sym.isBindingLocal())
586       return make<DefinedData>(name, flags, this, seg, offset, size);
587     if (seg->discarded)
588       return nullptr;
589     return symtab->addDefinedData(name, flags, this, seg, offset, size);
590   }
591   case WASM_SYMBOL_TYPE_GLOBAL: {
592     InputGlobal *global =
593         globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
594     if (sym.isBindingLocal())
595       return make<DefinedGlobal>(name, flags, this, global);
596     return symtab->addDefinedGlobal(name, flags, this, global);
597   }
598   case WASM_SYMBOL_TYPE_SECTION: {
599     InputChunk *section = customSectionsByIndex[sym.Info.ElementIndex];
600     assert(sym.isBindingLocal());
601     // Need to return null if discarded here? data and func only do that when
602     // binding is not local.
603     if (section->discarded)
604       return nullptr;
605     return make<SectionSymbol>(flags, section, this);
606   }
607   case WASM_SYMBOL_TYPE_TAG: {
608     InputTag *tag = tags[sym.Info.ElementIndex - wasmObj->getNumImportedTags()];
609     if (sym.isBindingLocal())
610       return make<DefinedTag>(name, flags, this, tag);
611     return symtab->addDefinedTag(name, flags, this, tag);
612   }
613   case WASM_SYMBOL_TYPE_TABLE: {
614     InputTable *table =
615         tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()];
616     if (sym.isBindingLocal())
617       return make<DefinedTable>(name, flags, this, table);
618     return symtab->addDefinedTable(name, flags, this, table);
619   }
620   }
621   llvm_unreachable("unknown symbol kind");
622 }
623 
624 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
625   StringRef name = sym.Info.Name;
626   uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
627 
628   switch (sym.Info.Kind) {
629   case WASM_SYMBOL_TYPE_FUNCTION:
630     if (sym.isBindingLocal())
631       return make<UndefinedFunction>(name, sym.Info.ImportName,
632                                      sym.Info.ImportModule, flags, this,
633                                      sym.Signature, isCalledDirectly);
634     return symtab->addUndefinedFunction(name, sym.Info.ImportName,
635                                         sym.Info.ImportModule, flags, this,
636                                         sym.Signature, isCalledDirectly);
637   case WASM_SYMBOL_TYPE_DATA:
638     if (sym.isBindingLocal())
639       return make<UndefinedData>(name, flags, this);
640     return symtab->addUndefinedData(name, flags, this);
641   case WASM_SYMBOL_TYPE_GLOBAL:
642     if (sym.isBindingLocal())
643       return make<UndefinedGlobal>(name, sym.Info.ImportName,
644                                    sym.Info.ImportModule, flags, this,
645                                    sym.GlobalType);
646     return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
647                                       sym.Info.ImportModule, flags, this,
648                                       sym.GlobalType);
649   case WASM_SYMBOL_TYPE_TABLE:
650     if (sym.isBindingLocal())
651       return make<UndefinedTable>(name, sym.Info.ImportName,
652                                   sym.Info.ImportModule, flags, this,
653                                   sym.TableType);
654     return symtab->addUndefinedTable(name, sym.Info.ImportName,
655                                      sym.Info.ImportModule, flags, this,
656                                      sym.TableType);
657   case WASM_SYMBOL_TYPE_TAG:
658     if (sym.isBindingLocal())
659       return make<UndefinedTag>(name, sym.Info.ImportName,
660                                 sym.Info.ImportModule, flags, this,
661                                 sym.Signature);
662     return symtab->addUndefinedTag(name, sym.Info.ImportName,
663                                    sym.Info.ImportModule, flags, this,
664                                    sym.Signature);
665   case WASM_SYMBOL_TYPE_SECTION:
666     llvm_unreachable("section symbols cannot be undefined");
667   }
668   llvm_unreachable("unknown symbol kind");
669 }
670 
671 void ArchiveFile::parse() {
672   // Parse a MemoryBufferRef as an archive file.
673   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
674   file = CHECK(Archive::create(mb), toString(this));
675 
676   // Read the symbol table to construct Lazy symbols.
677   int count = 0;
678   for (const Archive::Symbol &sym : file->symbols()) {
679     symtab->addLazy(this, &sym);
680     ++count;
681   }
682   LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
683 }
684 
685 void ArchiveFile::addMember(const Archive::Symbol *sym) {
686   const Archive::Child &c =
687       CHECK(sym->getMember(),
688             "could not get the member for symbol " + sym->getName());
689 
690   // Don't try to load the same member twice (this can happen when members
691   // mutually reference each other).
692   if (!seen.insert(c.getChildOffset()).second)
693     return;
694 
695   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
696   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
697 
698   MemoryBufferRef mb =
699       CHECK(c.getMemoryBufferRef(),
700             "could not get the buffer for the member defining symbol " +
701                 sym->getName());
702 
703   InputFile *obj = createObjectFile(mb, getName(), c.getChildOffset());
704   symtab->addFile(obj);
705 }
706 
707 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
708   switch (gvVisibility) {
709   case GlobalValue::DefaultVisibility:
710     return WASM_SYMBOL_VISIBILITY_DEFAULT;
711   case GlobalValue::HiddenVisibility:
712   case GlobalValue::ProtectedVisibility:
713     return WASM_SYMBOL_VISIBILITY_HIDDEN;
714   }
715   llvm_unreachable("unknown visibility");
716 }
717 
718 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
719                                    const lto::InputFile::Symbol &objSym,
720                                    BitcodeFile &f) {
721   StringRef name = saver.save(objSym.getName());
722 
723   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
724   flags |= mapVisibility(objSym.getVisibility());
725 
726   int c = objSym.getComdatIndex();
727   bool excludedByComdat = c != -1 && !keptComdats[c];
728 
729   if (objSym.isUndefined() || excludedByComdat) {
730     flags |= WASM_SYMBOL_UNDEFINED;
731     if (objSym.isExecutable())
732       return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
733                                           true);
734     return symtab->addUndefinedData(name, flags, &f);
735   }
736 
737   if (objSym.isExecutable())
738     return symtab->addDefinedFunction(name, flags, &f, nullptr);
739   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
740 }
741 
742 BitcodeFile::BitcodeFile(MemoryBufferRef m, StringRef archiveName,
743                          uint64_t offsetInArchive)
744     : InputFile(BitcodeKind, m) {
745   this->archiveName = std::string(archiveName);
746 
747   std::string path = mb.getBufferIdentifier().str();
748 
749   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
750   // name. If two archives define two members with the same name, this
751   // causes a collision which result in only one of the objects being taken
752   // into consideration at LTO time (which very likely causes undefined
753   // symbols later in the link stage). So we append file offset to make
754   // filename unique.
755   StringRef name = archiveName.empty()
756                        ? saver.save(path)
757                        : saver.save(archiveName + "(" + path::filename(path) +
758                                     " at " + utostr(offsetInArchive) + ")");
759   MemoryBufferRef mbref(mb.getBuffer(), name);
760 
761   obj = check(lto::InputFile::create(mbref));
762 
763   // If this isn't part of an archive, it's eagerly linked, so mark it live.
764   if (archiveName.empty())
765     markLive();
766 }
767 
768 bool BitcodeFile::doneLTO = false;
769 
770 void BitcodeFile::parse() {
771   if (doneLTO) {
772     error(toString(this) + ": attempt to add bitcode file after LTO.");
773     return;
774   }
775 
776   Triple t(obj->getTargetTriple());
777   if (!t.isWasm()) {
778     error(toString(this) + ": machine type must be wasm32 or wasm64");
779     return;
780   }
781   checkArch(t.getArch());
782   std::vector<bool> keptComdats;
783   // TODO Support nodeduplicate https://bugs.llvm.org/show_bug.cgi?id=50531
784   for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable())
785     keptComdats.push_back(symtab->addComdat(s.first));
786 
787   for (const lto::InputFile::Symbol &objSym : obj->symbols())
788     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
789 }
790 
791 } // namespace wasm
792 } // namespace lld
793