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