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