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)".
toString(const wasm::InputFile * file)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 
checkArch(Triple::ArchType arch) const45 void InputFile::checkArch(Triple::ArchType arch) const {
46   bool is64 = arch == Triple::wasm64;
47   if (is64 && !config->is64) {
48     fatal(toString(this) +
49           ": must specify -mwasm64 to process wasm64 object files");
50   } else if (config->is64.value_or(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 
readFile(StringRef path)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 
createObjectFile(MemoryBufferRef mb,StringRef archiveName,uint64_t offsetInArchive)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   std::string name = mb.getBufferIdentifier().str();
91   if (!archiveName.empty()) {
92     name = archiveName.str() + "(" + name + ")";
93   }
94 
95   fatal("unknown file type: " + name);
96 }
97 
98 // Relocations contain either symbol or type indices.  This function takes a
99 // relocation and returns relocated index (i.e. translates from the input
100 // symbol/type space to the output symbol/type space).
calcNewIndex(const WasmRelocation & reloc) const101 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
102   if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
103     assert(typeIsUsed[reloc.Index]);
104     return typeMap[reloc.Index];
105   }
106   const Symbol *sym = symbols[reloc.Index];
107   if (auto *ss = dyn_cast<SectionSymbol>(sym))
108     sym = ss->getOutputSectionSymbol();
109   return sym->getOutputSymbolIndex();
110 }
111 
112 // Relocations can contain addend for combined sections. This function takes a
113 // relocation and returns updated addend by offset in the output section.
calcNewAddend(const WasmRelocation & reloc) const114 int64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
115   switch (reloc.Type) {
116   case R_WASM_MEMORY_ADDR_LEB:
117   case R_WASM_MEMORY_ADDR_LEB64:
118   case R_WASM_MEMORY_ADDR_SLEB64:
119   case R_WASM_MEMORY_ADDR_SLEB:
120   case R_WASM_MEMORY_ADDR_REL_SLEB:
121   case R_WASM_MEMORY_ADDR_REL_SLEB64:
122   case R_WASM_MEMORY_ADDR_I32:
123   case R_WASM_MEMORY_ADDR_I64:
124   case R_WASM_MEMORY_ADDR_TLS_SLEB:
125   case R_WASM_MEMORY_ADDR_TLS_SLEB64:
126   case R_WASM_FUNCTION_OFFSET_I32:
127   case R_WASM_FUNCTION_OFFSET_I64:
128   case R_WASM_MEMORY_ADDR_LOCREL_I32:
129     return reloc.Addend;
130   case R_WASM_SECTION_OFFSET_I32:
131     return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
132   default:
133     llvm_unreachable("unexpected relocation type");
134   }
135 }
136 
137 // Translate from the relocation's index into the final linked output value.
calcNewValue(const WasmRelocation & reloc,uint64_t tombstone,const InputChunk * chunk) const138 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone,
139                                const InputChunk *chunk) const {
140   const Symbol* sym = nullptr;
141   if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
142     sym = symbols[reloc.Index];
143 
144     // We can end up with relocations against non-live symbols.  For example
145     // in debug sections. We return a tombstone value in debug symbol sections
146     // so this will not produce a valid range conflicting with ranges of actual
147     // code. In other sections we return reloc.Addend.
148 
149     if (!isa<SectionSymbol>(sym) && !sym->isLive())
150       return tombstone ? tombstone : reloc.Addend;
151   }
152 
153   switch (reloc.Type) {
154   case R_WASM_TABLE_INDEX_I32:
155   case R_WASM_TABLE_INDEX_I64:
156   case R_WASM_TABLE_INDEX_SLEB:
157   case R_WASM_TABLE_INDEX_SLEB64:
158   case R_WASM_TABLE_INDEX_REL_SLEB:
159   case R_WASM_TABLE_INDEX_REL_SLEB64: {
160     if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
161       return 0;
162     uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
163     if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB ||
164         reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB64)
165       index -= config->tableBase;
166     return index;
167   }
168   case R_WASM_MEMORY_ADDR_LEB:
169   case R_WASM_MEMORY_ADDR_LEB64:
170   case R_WASM_MEMORY_ADDR_SLEB:
171   case R_WASM_MEMORY_ADDR_SLEB64:
172   case R_WASM_MEMORY_ADDR_REL_SLEB:
173   case R_WASM_MEMORY_ADDR_REL_SLEB64:
174   case R_WASM_MEMORY_ADDR_I32:
175   case R_WASM_MEMORY_ADDR_I64:
176   case R_WASM_MEMORY_ADDR_TLS_SLEB:
177   case R_WASM_MEMORY_ADDR_TLS_SLEB64:
178   case R_WASM_MEMORY_ADDR_LOCREL_I32: {
179     if (isa<UndefinedData>(sym) || sym->isUndefWeak())
180       return 0;
181     auto D = cast<DefinedData>(sym);
182     uint64_t value = D->getVA() + reloc.Addend;
183     if (reloc.Type == R_WASM_MEMORY_ADDR_LOCREL_I32) {
184       const auto *segment = cast<InputSegment>(chunk);
185       uint64_t p = segment->outputSeg->startVA + segment->outputSegmentOffset +
186                    reloc.Offset - segment->getInputSectionOffset();
187       value -= p;
188     }
189     return value;
190   }
191   case R_WASM_TYPE_INDEX_LEB:
192     return typeMap[reloc.Index];
193   case R_WASM_FUNCTION_INDEX_LEB:
194     return getFunctionSymbol(reloc.Index)->getFunctionIndex();
195   case R_WASM_GLOBAL_INDEX_LEB:
196   case R_WASM_GLOBAL_INDEX_I32:
197     if (auto gs = dyn_cast<GlobalSymbol>(sym))
198       return gs->getGlobalIndex();
199     return sym->getGOTIndex();
200   case R_WASM_TAG_INDEX_LEB:
201     return getTagSymbol(reloc.Index)->getTagIndex();
202   case R_WASM_FUNCTION_OFFSET_I32:
203   case R_WASM_FUNCTION_OFFSET_I64: {
204     if (isa<UndefinedFunction>(sym)) {
205       return tombstone ? tombstone : reloc.Addend;
206     }
207     auto *f = cast<DefinedFunction>(sym);
208     return f->function->getOffset(f->function->getFunctionCodeOffset() +
209                                   reloc.Addend);
210   }
211   case R_WASM_SECTION_OFFSET_I32:
212     return getSectionSymbol(reloc.Index)->section->getOffset(reloc.Addend);
213   case R_WASM_TABLE_NUMBER_LEB:
214     return getTableSymbol(reloc.Index)->getTableNumber();
215   default:
216     llvm_unreachable("unknown relocation type");
217   }
218 }
219 
220 template <class T>
setRelocs(const std::vector<T * > & chunks,const WasmSection * section)221 static void setRelocs(const std::vector<T *> &chunks,
222                       const WasmSection *section) {
223   if (!section)
224     return;
225 
226   ArrayRef<WasmRelocation> relocs = section->Relocations;
227   assert(llvm::is_sorted(
228       relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
229         return r1.Offset < r2.Offset;
230       }));
231   assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
232     return c1->getInputSectionOffset() < c2->getInputSectionOffset();
233   }));
234 
235   auto relocsNext = relocs.begin();
236   auto relocsEnd = relocs.end();
237   auto relocLess = [](const WasmRelocation &r, uint32_t val) {
238     return r.Offset < val;
239   };
240   for (InputChunk *c : chunks) {
241     auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
242                                         c->getInputSectionOffset(), relocLess);
243     relocsNext = std::lower_bound(
244         relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
245         relocLess);
246     c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
247   }
248 }
249 
250 // An object file can have two approaches to tables.  With the reference-types
251 // feature enabled, input files that define or use tables declare the tables
252 // using symbols, and record each use with a relocation.  This way when the
253 // linker combines inputs, it can collate the tables used by the inputs,
254 // assigning them distinct table numbers, and renumber all the uses as
255 // appropriate.  At the same time, the linker has special logic to build the
256 // indirect function table if it is needed.
257 //
258 // However, MVP object files (those that target WebAssembly 1.0, the "minimum
259 // viable product" version of WebAssembly) neither write table symbols nor
260 // record relocations.  These files can have at most one table, the indirect
261 // function table used by call_indirect and which is the address space for
262 // function pointers.  If this table is present, it is always an import.  If we
263 // have a file with a table import but no table symbols, it is an MVP object
264 // file.  synthesizeMVPIndirectFunctionTableSymbolIfNeeded serves as a shim when
265 // loading these input files, defining the missing symbol to allow the indirect
266 // function table to be built.
267 //
268 // As indirect function table table usage in MVP objects cannot be relocated,
269 // the linker must ensure that this table gets assigned index zero.
addLegacyIndirectFunctionTableIfNeeded(uint32_t tableSymbolCount)270 void ObjFile::addLegacyIndirectFunctionTableIfNeeded(
271     uint32_t tableSymbolCount) {
272   uint32_t tableCount = wasmObj->getNumImportedTables() + tables.size();
273 
274   // If there are symbols for all tables, then all is good.
275   if (tableCount == tableSymbolCount)
276     return;
277 
278   // It's possible for an input to define tables and also use the indirect
279   // function table, but forget to compile with -mattr=+reference-types.
280   // For these newer files, we require symbols for all tables, and
281   // relocations for all of their uses.
282   if (tableSymbolCount != 0) {
283     error(toString(this) +
284           ": expected one symbol table entry for each of the " +
285           Twine(tableCount) + " table(s) present, but got " +
286           Twine(tableSymbolCount) + " symbol(s) instead.");
287     return;
288   }
289 
290   // An MVP object file can have up to one table import, for the indirect
291   // function table, but will have no table definitions.
292   if (tables.size()) {
293     error(toString(this) +
294           ": unexpected table definition(s) without corresponding "
295           "symbol-table entries.");
296     return;
297   }
298 
299   // An MVP object file can have only one table import.
300   if (tableCount != 1) {
301     error(toString(this) +
302           ": multiple table imports, but no corresponding symbol-table "
303           "entries.");
304     return;
305   }
306 
307   const WasmImport *tableImport = nullptr;
308   for (const auto &import : wasmObj->imports()) {
309     if (import.Kind == WASM_EXTERNAL_TABLE) {
310       assert(!tableImport);
311       tableImport = &import;
312     }
313   }
314   assert(tableImport);
315 
316   // We can only synthesize a symtab entry for the indirect function table; if
317   // it has an unexpected name or type, assume that it's not actually the
318   // indirect function table.
319   if (tableImport->Field != functionTableName ||
320       tableImport->Table.ElemType != uint8_t(ValType::FUNCREF)) {
321     error(toString(this) + ": table import " + Twine(tableImport->Field) +
322           " is missing a symbol table entry.");
323     return;
324   }
325 
326   auto *info = make<WasmSymbolInfo>();
327   info->Name = tableImport->Field;
328   info->Kind = WASM_SYMBOL_TYPE_TABLE;
329   info->ImportModule = tableImport->Module;
330   info->ImportName = tableImport->Field;
331   info->Flags = WASM_SYMBOL_UNDEFINED;
332   info->Flags |= WASM_SYMBOL_NO_STRIP;
333   info->ElementIndex = 0;
334   LLVM_DEBUG(dbgs() << "Synthesizing symbol for table import: " << info->Name
335                     << "\n");
336   const WasmGlobalType *globalType = nullptr;
337   const WasmSignature *signature = nullptr;
338   auto *wasmSym =
339       make<WasmSymbol>(*info, globalType, &tableImport->Table, signature);
340   Symbol *sym = createUndefined(*wasmSym, false);
341   // We're only sure it's a TableSymbol if the createUndefined succeeded.
342   if (errorCount())
343     return;
344   symbols.push_back(sym);
345   // Because there are no TABLE_NUMBER relocs, we can't compute accurate
346   // liveness info; instead, just mark the symbol as always live.
347   sym->markLive();
348 
349   // We assume that this compilation unit has unrelocatable references to
350   // this table.
351   config->legacyFunctionTable = true;
352 }
353 
shouldMerge(const WasmSection & sec)354 static bool shouldMerge(const WasmSection &sec) {
355   if (config->optimize == 0)
356     return false;
357   // Sadly we don't have section attributes yet for custom sections, so we
358   // currently go by the name alone.
359   // TODO(sbc): Add ability for wasm sections to carry flags so we don't
360   // need to use names here.
361   // For now, keep in sync with uses of wasm::WASM_SEG_FLAG_STRINGS in
362   // MCObjectFileInfo::initWasmMCObjectFileInfo which creates these custom
363   // sections.
364   return sec.Name == ".debug_str" || sec.Name == ".debug_str.dwo" ||
365          sec.Name == ".debug_line_str";
366 }
367 
shouldMerge(const WasmSegment & seg)368 static bool shouldMerge(const WasmSegment &seg) {
369   // As of now we only support merging strings, and only with single byte
370   // alignment (2^0).
371   if (!(seg.Data.LinkingFlags & WASM_SEG_FLAG_STRINGS) ||
372       (seg.Data.Alignment != 0))
373     return false;
374 
375   // On a regular link we don't merge sections if -O0 (default is -O1). This
376   // sometimes makes the linker significantly faster, although the output will
377   // be bigger.
378   if (config->optimize == 0)
379     return false;
380 
381   // A mergeable section with size 0 is useless because they don't have
382   // any data to merge. A mergeable string section with size 0 can be
383   // argued as invalid because it doesn't end with a null character.
384   // We'll avoid a mess by handling them as if they were non-mergeable.
385   if (seg.Data.Content.size() == 0)
386     return false;
387 
388   return true;
389 }
390 
parse(bool ignoreComdats)391 void ObjFile::parse(bool ignoreComdats) {
392   // Parse a memory buffer as a wasm file.
393   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
394   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
395 
396   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
397   if (!obj)
398     fatal(toString(this) + ": not a wasm file");
399   if (!obj->isRelocatableObject())
400     fatal(toString(this) + ": not a relocatable wasm file");
401 
402   bin.release();
403   wasmObj.reset(obj);
404 
405   checkArch(obj->getArch());
406 
407   // Build up a map of function indices to table indices for use when
408   // verifying the existing table index relocations
409   uint32_t totalFunctions =
410       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
411   tableEntriesRel.resize(totalFunctions);
412   tableEntries.resize(totalFunctions);
413   for (const WasmElemSegment &seg : wasmObj->elements()) {
414     int64_t offset;
415     if (seg.Offset.Extended)
416       fatal(toString(this) + ": extended init exprs not supported");
417     else if (seg.Offset.Inst.Opcode == WASM_OPCODE_I32_CONST)
418       offset = seg.Offset.Inst.Value.Int32;
419     else if (seg.Offset.Inst.Opcode == WASM_OPCODE_I64_CONST)
420       offset = seg.Offset.Inst.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     segments.emplace_back(seg);
491   }
492   setRelocs(segments, dataSection);
493 
494   // Populate `Functions`.
495   ArrayRef<WasmFunction> funcs = wasmObj->functions();
496   ArrayRef<WasmSignature> types = wasmObj->types();
497   functions.reserve(funcs.size());
498 
499   for (auto &f : funcs) {
500     auto *func = make<InputFunction>(types[f.SigIndex], &f, this);
501     func->discarded = isExcludedByComdat(func);
502     functions.emplace_back(func);
503   }
504   setRelocs(functions, codeSection);
505 
506   // Populate `Tables`.
507   for (const WasmTable &t : wasmObj->tables())
508     tables.emplace_back(make<InputTable>(t, this));
509 
510   // Populate `Globals`.
511   for (const WasmGlobal &g : wasmObj->globals())
512     globals.emplace_back(make<InputGlobal>(g, this));
513 
514   // Populate `Tags`.
515   for (const WasmTag &t : wasmObj->tags())
516     tags.emplace_back(make<InputTag>(types[t.SigIndex], t, this));
517 
518   // Populate `Symbols` based on the symbols in the object.
519   symbols.reserve(wasmObj->getNumberOfSymbols());
520   uint32_t tableSymbolCount = 0;
521   for (const SymbolRef &sym : wasmObj->symbols()) {
522     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
523     if (wasmSym.isTypeTable())
524       tableSymbolCount++;
525     if (wasmSym.isDefined()) {
526       // createDefined may fail if the symbol is comdat excluded in which case
527       // we fall back to creating an undefined symbol
528       if (Symbol *d = createDefined(wasmSym)) {
529         symbols.push_back(d);
530         continue;
531       }
532     }
533     size_t idx = symbols.size();
534     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
535   }
536 
537   addLegacyIndirectFunctionTableIfNeeded(tableSymbolCount);
538 }
539 
isExcludedByComdat(const InputChunk * chunk) const540 bool ObjFile::isExcludedByComdat(const InputChunk *chunk) const {
541   uint32_t c = chunk->getComdat();
542   if (c == UINT32_MAX)
543     return false;
544   return !keptComdats[c];
545 }
546 
getFunctionSymbol(uint32_t index) const547 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
548   return cast<FunctionSymbol>(symbols[index]);
549 }
550 
getGlobalSymbol(uint32_t index) const551 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
552   return cast<GlobalSymbol>(symbols[index]);
553 }
554 
getTagSymbol(uint32_t index) const555 TagSymbol *ObjFile::getTagSymbol(uint32_t index) const {
556   return cast<TagSymbol>(symbols[index]);
557 }
558 
getTableSymbol(uint32_t index) const559 TableSymbol *ObjFile::getTableSymbol(uint32_t index) const {
560   return cast<TableSymbol>(symbols[index]);
561 }
562 
getSectionSymbol(uint32_t index) const563 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
564   return cast<SectionSymbol>(symbols[index]);
565 }
566 
getDataSymbol(uint32_t index) const567 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
568   return cast<DataSymbol>(symbols[index]);
569 }
570 
createDefined(const WasmSymbol & sym)571 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
572   StringRef name = sym.Info.Name;
573   uint32_t flags = sym.Info.Flags;
574 
575   switch (sym.Info.Kind) {
576   case WASM_SYMBOL_TYPE_FUNCTION: {
577     InputFunction *func =
578         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
579     if (sym.isBindingLocal())
580       return make<DefinedFunction>(name, flags, this, func);
581     if (func->discarded)
582       return nullptr;
583     return symtab->addDefinedFunction(name, flags, this, func);
584   }
585   case WASM_SYMBOL_TYPE_DATA: {
586     InputChunk *seg = segments[sym.Info.DataRef.Segment];
587     auto offset = sym.Info.DataRef.Offset;
588     auto size = sym.Info.DataRef.Size;
589     // Support older (e.g. llvm 13) object files that pre-date the per-symbol
590     // TLS flag, and symbols were assumed to be TLS by being defined in a TLS
591     // segment.
592     if (!(flags & WASM_SYMBOL_TLS) && seg->isTLS())
593       flags |= WASM_SYMBOL_TLS;
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 
createUndefined(const WasmSymbol & sym,bool isCalledDirectly)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 
parse()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   (void) count;
693 }
694 
addMember(const Archive::Symbol * sym)695 void ArchiveFile::addMember(const Archive::Symbol *sym) {
696   const Archive::Child &c =
697       CHECK(sym->getMember(),
698             "could not get the member for symbol " + sym->getName());
699 
700   // Don't try to load the same member twice (this can happen when members
701   // mutually reference each other).
702   if (!seen.insert(c.getChildOffset()).second)
703     return;
704 
705   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
706   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
707 
708   MemoryBufferRef mb =
709       CHECK(c.getMemoryBufferRef(),
710             "could not get the buffer for the member defining symbol " +
711                 sym->getName());
712 
713   InputFile *obj = createObjectFile(mb, getName(), c.getChildOffset());
714   symtab->addFile(obj);
715 }
716 
mapVisibility(GlobalValue::VisibilityTypes gvVisibility)717 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
718   switch (gvVisibility) {
719   case GlobalValue::DefaultVisibility:
720     return WASM_SYMBOL_VISIBILITY_DEFAULT;
721   case GlobalValue::HiddenVisibility:
722   case GlobalValue::ProtectedVisibility:
723     return WASM_SYMBOL_VISIBILITY_HIDDEN;
724   }
725   llvm_unreachable("unknown visibility");
726 }
727 
createBitcodeSymbol(const std::vector<bool> & keptComdats,const lto::InputFile::Symbol & objSym,BitcodeFile & f)728 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
729                                    const lto::InputFile::Symbol &objSym,
730                                    BitcodeFile &f) {
731   StringRef name = saver().save(objSym.getName());
732 
733   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
734   flags |= mapVisibility(objSym.getVisibility());
735 
736   int c = objSym.getComdatIndex();
737   bool excludedByComdat = c != -1 && !keptComdats[c];
738 
739   if (objSym.isUndefined() || excludedByComdat) {
740     flags |= WASM_SYMBOL_UNDEFINED;
741     if (objSym.isExecutable())
742       return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
743                                           true);
744     return symtab->addUndefinedData(name, flags, &f);
745   }
746 
747   if (objSym.isExecutable())
748     return symtab->addDefinedFunction(name, flags, &f, nullptr);
749   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
750 }
751 
BitcodeFile(MemoryBufferRef m,StringRef archiveName,uint64_t offsetInArchive)752 BitcodeFile::BitcodeFile(MemoryBufferRef m, StringRef archiveName,
753                          uint64_t offsetInArchive)
754     : InputFile(BitcodeKind, m) {
755   this->archiveName = std::string(archiveName);
756 
757   std::string path = mb.getBufferIdentifier().str();
758 
759   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
760   // name. If two archives define two members with the same name, this
761   // causes a collision which result in only one of the objects being taken
762   // into consideration at LTO time (which very likely causes undefined
763   // symbols later in the link stage). So we append file offset to make
764   // filename unique.
765   StringRef name = archiveName.empty()
766                        ? saver().save(path)
767                        : saver().save(archiveName + "(" + path::filename(path) +
768                                       " at " + utostr(offsetInArchive) + ")");
769   MemoryBufferRef mbref(mb.getBuffer(), name);
770 
771   obj = check(lto::InputFile::create(mbref));
772 
773   // If this isn't part of an archive, it's eagerly linked, so mark it live.
774   if (archiveName.empty())
775     markLive();
776 }
777 
778 bool BitcodeFile::doneLTO = false;
779 
parse()780 void BitcodeFile::parse() {
781   if (doneLTO) {
782     error(toString(this) + ": attempt to add bitcode file after LTO.");
783     return;
784   }
785 
786   Triple t(obj->getTargetTriple());
787   if (!t.isWasm()) {
788     error(toString(this) + ": machine type must be wasm32 or wasm64");
789     return;
790   }
791   checkArch(t.getArch());
792   std::vector<bool> keptComdats;
793   // TODO Support nodeduplicate https://bugs.llvm.org/show_bug.cgi?id=50531
794   for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable())
795     keptComdats.push_back(symtab->addComdat(s.first));
796 
797   for (const lto::InputFile::Symbol &objSym : obj->symbols())
798     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
799 }
800 
801 } // namespace wasm
802 } // namespace lld
803