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