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