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