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