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 WasmTagType *tagType = nullptr;
340   const WasmSignature *signature = nullptr;
341   auto *wasmSym = make<WasmSymbol>(*info, globalType, &tableImport->Table,
342                                    tagType, signature);
343   Symbol *sym = createUndefined(*wasmSym, false);
344   // We're only sure it's a TableSymbol if the createUndefined succeeded.
345   if (errorCount())
346     return;
347   symbols.push_back(sym);
348   // Because there are no TABLE_NUMBER relocs, we can't compute accurate
349   // liveness info; instead, just mark the symbol as always live.
350   sym->markLive();
351 
352   // We assume that this compilation unit has unrelocatable references to
353   // this table.
354   config->legacyFunctionTable = true;
355 }
356 
357 static bool shouldMerge(const WasmSection &sec) {
358   if (config->optimize == 0)
359     return false;
360   // Sadly we don't have section attributes yet for custom sections, so we
361   // currently go by the name alone.
362   // TODO(sbc): Add ability for wasm sections to carry flags so we don't
363   // need to use names here.
364   // For now, keep in sync with uses of wasm::WASM_SEG_FLAG_STRINGS in
365   // MCObjectFileInfo::initWasmMCObjectFileInfo which creates these custom
366   // sections.
367   return sec.Name == ".debug_str" || sec.Name == ".debug_str.dwo" ||
368          sec.Name == ".debug_line_str";
369 }
370 
371 static bool shouldMerge(const WasmSegment &seg) {
372   // As of now we only support merging strings, and only with single byte
373   // alignment (2^0).
374   if (!(seg.Data.LinkingFlags & WASM_SEG_FLAG_STRINGS) ||
375       (seg.Data.Alignment != 0))
376     return false;
377 
378   // On a regular link we don't merge sections if -O0 (default is -O1). This
379   // sometimes makes the linker significantly faster, although the output will
380   // be bigger.
381   if (config->optimize == 0)
382     return false;
383 
384   // A mergeable section with size 0 is useless because they don't have
385   // any data to merge. A mergeable string section with size 0 can be
386   // argued as invalid because it doesn't end with a null character.
387   // We'll avoid a mess by handling them as if they were non-mergeable.
388   if (seg.Data.Content.size() == 0)
389     return false;
390 
391   return true;
392 }
393 
394 void ObjFile::parse(bool ignoreComdats) {
395   // Parse a memory buffer as a wasm file.
396   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
397   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
398 
399   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
400   if (!obj)
401     fatal(toString(this) + ": not a wasm file");
402   if (!obj->isRelocatableObject())
403     fatal(toString(this) + ": not a relocatable wasm file");
404 
405   bin.release();
406   wasmObj.reset(obj);
407 
408   checkArch(obj->getArch());
409 
410   // Build up a map of function indices to table indices for use when
411   // verifying the existing table index relocations
412   uint32_t totalFunctions =
413       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
414   tableEntriesRel.resize(totalFunctions);
415   tableEntries.resize(totalFunctions);
416   for (const WasmElemSegment &seg : wasmObj->elements()) {
417     int64_t offset;
418     if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST)
419       offset = seg.Offset.Value.Int32;
420     else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST)
421       offset = seg.Offset.Value.Int64;
422     else
423       fatal(toString(this) + ": invalid table elements");
424     for (size_t index = 0; index < seg.Functions.size(); index++) {
425       auto functionIndex = seg.Functions[index];
426       tableEntriesRel[functionIndex] = index;
427       tableEntries[functionIndex] = offset + index;
428     }
429   }
430 
431   ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
432   for (StringRef comdat : comdats) {
433     bool isNew = ignoreComdats || symtab->addComdat(comdat);
434     keptComdats.push_back(isNew);
435   }
436 
437   uint32_t sectionIndex = 0;
438 
439   // Bool for each symbol, true if called directly.  This allows us to implement
440   // a weaker form of signature checking where undefined functions that are not
441   // called directly (i.e. only address taken) don't have to match the defined
442   // function's signature.  We cannot do this for directly called functions
443   // because those signatures are checked at validation times.
444   // See https://bugs.llvm.org/show_bug.cgi?id=40412
445   std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
446   for (const SectionRef &sec : wasmObj->sections()) {
447     const WasmSection &section = wasmObj->getWasmSection(sec);
448     // Wasm objects can have at most one code and one data section.
449     if (section.Type == WASM_SEC_CODE) {
450       assert(!codeSection);
451       codeSection = &section;
452     } else if (section.Type == WASM_SEC_DATA) {
453       assert(!dataSection);
454       dataSection = &section;
455     } else if (section.Type == WASM_SEC_CUSTOM) {
456       InputChunk *customSec;
457       if (shouldMerge(section))
458         customSec = make<MergeInputChunk>(section, this);
459       else
460         customSec = make<InputSection>(section, this);
461       customSec->discarded = isExcludedByComdat(customSec);
462       customSections.emplace_back(customSec);
463       customSections.back()->setRelocations(section.Relocations);
464       customSectionsByIndex[sectionIndex] = customSections.back();
465     }
466     sectionIndex++;
467     // Scans relocations to determine if a function symbol is called directly.
468     for (const WasmRelocation &reloc : section.Relocations)
469       if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
470         isCalledDirectly[reloc.Index] = true;
471   }
472 
473   typeMap.resize(getWasmObj()->types().size());
474   typeIsUsed.resize(getWasmObj()->types().size(), false);
475 
476 
477   // Populate `Segments`.
478   for (const WasmSegment &s : wasmObj->dataSegments()) {
479     InputChunk *seg;
480     if (shouldMerge(s)) {
481       seg = make<MergeInputChunk>(s, this);
482     } else
483       seg = make<InputSegment>(s, this);
484     seg->discarded = isExcludedByComdat(seg);
485     // Older object files did not include WASM_SEG_FLAG_TLS and instead
486     // relied on the naming convention.  To maintain compat with such objects
487     // we still imply the TLS flag based on the name of the segment.
488     if (!seg->isTLS() &&
489         (seg->name.startswith(".tdata") || seg->name.startswith(".tbss"))) {
490       seg->flags |= WASM_SEG_FLAG_TLS;
491       seg->implicitTLS = true;
492     }
493     segments.emplace_back(seg);
494   }
495   setRelocs(segments, dataSection);
496 
497   // Populate `Functions`.
498   ArrayRef<WasmFunction> funcs = wasmObj->functions();
499   ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes();
500   ArrayRef<WasmSignature> types = wasmObj->types();
501   functions.reserve(funcs.size());
502 
503   for (size_t i = 0, e = funcs.size(); i != e; ++i) {
504     auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this);
505     func->discarded = isExcludedByComdat(func);
506     functions.emplace_back(func);
507   }
508   setRelocs(functions, codeSection);
509 
510   // Populate `Tables`.
511   for (const WasmTable &t : wasmObj->tables())
512     tables.emplace_back(make<InputTable>(t, this));
513 
514   // Populate `Globals`.
515   for (const WasmGlobal &g : wasmObj->globals())
516     globals.emplace_back(make<InputGlobal>(g, this));
517 
518   // Populate `Tags`.
519   for (const WasmTag &t : wasmObj->tags())
520     tags.emplace_back(make<InputTag>(types[t.Type.SigIndex], t, this));
521 
522   // Populate `Symbols` based on the symbols in the object.
523   symbols.reserve(wasmObj->getNumberOfSymbols());
524   uint32_t tableSymbolCount = 0;
525   for (const SymbolRef &sym : wasmObj->symbols()) {
526     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
527     if (wasmSym.isTypeTable())
528       tableSymbolCount++;
529     if (wasmSym.isDefined()) {
530       // createDefined may fail if the symbol is comdat excluded in which case
531       // we fall back to creating an undefined symbol
532       if (Symbol *d = createDefined(wasmSym)) {
533         symbols.push_back(d);
534         continue;
535       }
536     }
537     size_t idx = symbols.size();
538     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
539   }
540 
541   addLegacyIndirectFunctionTableIfNeeded(tableSymbolCount);
542 }
543 
544 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const {
545   uint32_t c = chunk->getComdat();
546   if (c == UINT32_MAX)
547     return false;
548   return !keptComdats[c];
549 }
550 
551 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
552   return cast<FunctionSymbol>(symbols[index]);
553 }
554 
555 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
556   return cast<GlobalSymbol>(symbols[index]);
557 }
558 
559 TagSymbol *ObjFile::getTagSymbol(uint32_t index) const {
560   return cast<TagSymbol>(symbols[index]);
561 }
562 
563 TableSymbol *ObjFile::getTableSymbol(uint32_t index) const {
564   return cast<TableSymbol>(symbols[index]);
565 }
566 
567 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
568   return cast<SectionSymbol>(symbols[index]);
569 }
570 
571 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
572   return cast<DataSymbol>(symbols[index]);
573 }
574 
575 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
576   StringRef name = sym.Info.Name;
577   uint32_t flags = sym.Info.Flags;
578 
579   switch (sym.Info.Kind) {
580   case WASM_SYMBOL_TYPE_FUNCTION: {
581     InputFunction *func =
582         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
583     if (sym.isBindingLocal())
584       return make<DefinedFunction>(name, flags, this, func);
585     if (func->discarded)
586       return nullptr;
587     return symtab->addDefinedFunction(name, flags, this, func);
588   }
589   case WASM_SYMBOL_TYPE_DATA: {
590     InputChunk *seg = segments[sym.Info.DataRef.Segment];
591     auto offset = sym.Info.DataRef.Offset;
592     auto size = sym.Info.DataRef.Size;
593     if (seg->implicitTLS) {
594       flags |= WASM_SYMBOL_TLS;
595     }
596     if (sym.isBindingLocal())
597       return make<DefinedData>(name, flags, this, seg, offset, size);
598     if (seg->discarded)
599       return nullptr;
600     return symtab->addDefinedData(name, flags, this, seg, offset, size);
601   }
602   case WASM_SYMBOL_TYPE_GLOBAL: {
603     InputGlobal *global =
604         globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
605     if (sym.isBindingLocal())
606       return make<DefinedGlobal>(name, flags, this, global);
607     return symtab->addDefinedGlobal(name, flags, this, global);
608   }
609   case WASM_SYMBOL_TYPE_SECTION: {
610     InputChunk *section = customSectionsByIndex[sym.Info.ElementIndex];
611     assert(sym.isBindingLocal());
612     // Need to return null if discarded here? data and func only do that when
613     // binding is not local.
614     if (section->discarded)
615       return nullptr;
616     return make<SectionSymbol>(flags, section, this);
617   }
618   case WASM_SYMBOL_TYPE_TAG: {
619     InputTag *tag = tags[sym.Info.ElementIndex - wasmObj->getNumImportedTags()];
620     if (sym.isBindingLocal())
621       return make<DefinedTag>(name, flags, this, tag);
622     return symtab->addDefinedTag(name, flags, this, tag);
623   }
624   case WASM_SYMBOL_TYPE_TABLE: {
625     InputTable *table =
626         tables[sym.Info.ElementIndex - wasmObj->getNumImportedTables()];
627     if (sym.isBindingLocal())
628       return make<DefinedTable>(name, flags, this, table);
629     return symtab->addDefinedTable(name, flags, this, table);
630   }
631   }
632   llvm_unreachable("unknown symbol kind");
633 }
634 
635 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
636   StringRef name = sym.Info.Name;
637   uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
638 
639   switch (sym.Info.Kind) {
640   case WASM_SYMBOL_TYPE_FUNCTION:
641     if (sym.isBindingLocal())
642       return make<UndefinedFunction>(name, sym.Info.ImportName,
643                                      sym.Info.ImportModule, flags, this,
644                                      sym.Signature, isCalledDirectly);
645     return symtab->addUndefinedFunction(name, sym.Info.ImportName,
646                                         sym.Info.ImportModule, flags, this,
647                                         sym.Signature, isCalledDirectly);
648   case WASM_SYMBOL_TYPE_DATA:
649     if (sym.isBindingLocal())
650       return make<UndefinedData>(name, flags, this);
651     return symtab->addUndefinedData(name, flags, this);
652   case WASM_SYMBOL_TYPE_GLOBAL:
653     if (sym.isBindingLocal())
654       return make<UndefinedGlobal>(name, sym.Info.ImportName,
655                                    sym.Info.ImportModule, flags, this,
656                                    sym.GlobalType);
657     return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
658                                       sym.Info.ImportModule, flags, this,
659                                       sym.GlobalType);
660   case WASM_SYMBOL_TYPE_TABLE:
661     if (sym.isBindingLocal())
662       return make<UndefinedTable>(name, sym.Info.ImportName,
663                                   sym.Info.ImportModule, flags, this,
664                                   sym.TableType);
665     return symtab->addUndefinedTable(name, sym.Info.ImportName,
666                                      sym.Info.ImportModule, flags, this,
667                                      sym.TableType);
668   case WASM_SYMBOL_TYPE_SECTION:
669     llvm_unreachable("section symbols cannot be undefined");
670   }
671   llvm_unreachable("unknown symbol kind");
672 }
673 
674 void ArchiveFile::parse() {
675   // Parse a MemoryBufferRef as an archive file.
676   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
677   file = CHECK(Archive::create(mb), toString(this));
678 
679   // Read the symbol table to construct Lazy symbols.
680   int count = 0;
681   for (const Archive::Symbol &sym : file->symbols()) {
682     symtab->addLazy(this, &sym);
683     ++count;
684   }
685   LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
686 }
687 
688 void ArchiveFile::addMember(const Archive::Symbol *sym) {
689   const Archive::Child &c =
690       CHECK(sym->getMember(),
691             "could not get the member for symbol " + sym->getName());
692 
693   // Don't try to load the same member twice (this can happen when members
694   // mutually reference each other).
695   if (!seen.insert(c.getChildOffset()).second)
696     return;
697 
698   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
699   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
700 
701   MemoryBufferRef mb =
702       CHECK(c.getMemoryBufferRef(),
703             "could not get the buffer for the member defining symbol " +
704                 sym->getName());
705 
706   InputFile *obj = createObjectFile(mb, getName());
707   symtab->addFile(obj);
708 }
709 
710 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
711   switch (gvVisibility) {
712   case GlobalValue::DefaultVisibility:
713     return WASM_SYMBOL_VISIBILITY_DEFAULT;
714   case GlobalValue::HiddenVisibility:
715   case GlobalValue::ProtectedVisibility:
716     return WASM_SYMBOL_VISIBILITY_HIDDEN;
717   }
718   llvm_unreachable("unknown visibility");
719 }
720 
721 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
722                                    const lto::InputFile::Symbol &objSym,
723                                    BitcodeFile &f) {
724   StringRef name = saver.save(objSym.getName());
725 
726   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
727   flags |= mapVisibility(objSym.getVisibility());
728 
729   int c = objSym.getComdatIndex();
730   bool excludedByComdat = c != -1 && !keptComdats[c];
731 
732   if (objSym.isUndefined() || excludedByComdat) {
733     flags |= WASM_SYMBOL_UNDEFINED;
734     if (objSym.isExecutable())
735       return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
736                                           true);
737     return symtab->addUndefinedData(name, flags, &f);
738   }
739 
740   if (objSym.isExecutable())
741     return symtab->addDefinedFunction(name, flags, &f, nullptr);
742   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
743 }
744 
745 bool BitcodeFile::doneLTO = false;
746 
747 void BitcodeFile::parse() {
748   if (doneLTO) {
749     error(toString(this) + ": attempt to add bitcode file after LTO.");
750     return;
751   }
752 
753   obj = check(lto::InputFile::create(MemoryBufferRef(
754       mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier()))));
755   Triple t(obj->getTargetTriple());
756   if (!t.isWasm()) {
757     error(toString(this) + ": machine type must be wasm32 or wasm64");
758     return;
759   }
760   checkArch(t.getArch());
761   std::vector<bool> keptComdats;
762   // TODO Support nodeduplicate https://bugs.llvm.org/show_bug.cgi?id=50531
763   for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable())
764     keptComdats.push_back(symtab->addComdat(s.first));
765 
766   for (const lto::InputFile::Symbol &objSym : obj->symbols())
767     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
768 }
769 
770 } // namespace wasm
771 } // namespace lld
772