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 "InputEvent.h"
13 #include "InputGlobal.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 lld;
26 using namespace lld::wasm;
27 
28 using namespace llvm;
29 using namespace llvm::object;
30 using namespace llvm::wasm;
31 
32 std::unique_ptr<llvm::TarWriter> lld::wasm::tar;
33 
34 Optional<MemoryBufferRef> lld::wasm::readFile(StringRef path) {
35   log("Loading: " + path);
36 
37   auto mbOrErr = MemoryBuffer::getFile(path);
38   if (auto ec = mbOrErr.getError()) {
39     error("cannot open " + path + ": " + ec.message());
40     return None;
41   }
42   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
43   MemoryBufferRef mbref = mb->getMemBufferRef();
44   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
45 
46   if (tar)
47     tar->append(relativeToRoot(path), mbref.getBuffer());
48   return mbref;
49 }
50 
51 InputFile *lld::wasm::createObjectFile(MemoryBufferRef mb,
52                                        StringRef archiveName) {
53   file_magic magic = identify_magic(mb.getBuffer());
54   if (magic == file_magic::wasm_object) {
55     std::unique_ptr<Binary> bin =
56         CHECK(createBinary(mb), mb.getBufferIdentifier());
57     auto *obj = cast<WasmObjectFile>(bin.get());
58     if (obj->isSharedObject())
59       return make<SharedFile>(mb);
60     return make<ObjFile>(mb, archiveName);
61   }
62 
63   if (magic == file_magic::bitcode)
64     return make<BitcodeFile>(mb, archiveName);
65 
66   fatal("unknown file type: " + mb.getBufferIdentifier());
67 }
68 
69 void ObjFile::dumpInfo() const {
70   log("info for: " + toString(this) +
71       "\n              Symbols : " + Twine(symbols.size()) +
72       "\n     Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) +
73       "\n       Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) +
74       "\n        Event Imports : " + Twine(wasmObj->getNumImportedEvents()));
75 }
76 
77 // Relocations contain either symbol or type indices.  This function takes a
78 // relocation and returns relocated index (i.e. translates from the input
79 // symbol/type space to the output symbol/type space).
80 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
81   if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
82     assert(typeIsUsed[reloc.Index]);
83     return typeMap[reloc.Index];
84   }
85   const Symbol *sym = symbols[reloc.Index];
86   if (auto *ss = dyn_cast<SectionSymbol>(sym))
87     sym = ss->getOutputSectionSymbol();
88   return sym->getOutputSymbolIndex();
89 }
90 
91 // Relocations can contain addend for combined sections. This function takes a
92 // relocation and returns updated addend by offset in the output section.
93 uint32_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
94   switch (reloc.Type) {
95   case R_WASM_MEMORY_ADDR_LEB:
96   case R_WASM_MEMORY_ADDR_SLEB:
97   case R_WASM_MEMORY_ADDR_REL_SLEB:
98   case R_WASM_MEMORY_ADDR_I32:
99   case R_WASM_FUNCTION_OFFSET_I32:
100     return reloc.Addend;
101   case R_WASM_SECTION_OFFSET_I32:
102     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
103   default:
104     llvm_unreachable("unexpected relocation type");
105   }
106 }
107 
108 // Calculate the value we expect to find at the relocation location.
109 // This is used as a sanity check before applying a relocation to a given
110 // location.  It is useful for catching bugs in the compiler and linker.
111 uint32_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const {
112   switch (reloc.Type) {
113   case R_WASM_TABLE_INDEX_I32:
114   case R_WASM_TABLE_INDEX_SLEB:
115   case R_WASM_TABLE_INDEX_REL_SLEB: {
116     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
117     return tableEntries[sym.Info.ElementIndex];
118   }
119   case R_WASM_MEMORY_ADDR_SLEB:
120   case R_WASM_MEMORY_ADDR_I32:
121   case R_WASM_MEMORY_ADDR_LEB:
122   case R_WASM_MEMORY_ADDR_REL_SLEB: {
123     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
124     if (sym.isUndefined())
125       return 0;
126     const WasmSegment &segment =
127         wasmObj->dataSegments()[sym.Info.DataRef.Segment];
128     return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset +
129            reloc.Addend;
130   }
131   case R_WASM_FUNCTION_OFFSET_I32: {
132     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
133     InputFunction *f =
134         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
135     return f->getFunctionInputOffset() + f->getFunctionCodeOffset() +
136            reloc.Addend;
137   }
138   case R_WASM_SECTION_OFFSET_I32:
139     return reloc.Addend;
140   case R_WASM_TYPE_INDEX_LEB:
141     return reloc.Index;
142   case R_WASM_FUNCTION_INDEX_LEB:
143   case R_WASM_GLOBAL_INDEX_LEB:
144   case R_WASM_EVENT_INDEX_LEB: {
145     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
146     return sym.Info.ElementIndex;
147   }
148   default:
149     llvm_unreachable("unknown relocation type");
150   }
151 }
152 
153 // Translate from the relocation's index into the final linked output value.
154 uint32_t ObjFile::calcNewValue(const WasmRelocation &reloc) const {
155   const Symbol* sym = nullptr;
156   if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
157     sym = symbols[reloc.Index];
158 
159     // We can end up with relocations against non-live symbols.  For example
160     // in debug sections.
161     if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive())
162       return 0;
163   }
164 
165   switch (reloc.Type) {
166   case R_WASM_TABLE_INDEX_I32:
167   case R_WASM_TABLE_INDEX_SLEB:
168   case R_WASM_TABLE_INDEX_REL_SLEB: {
169     if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
170       return 0;
171     uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
172     if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB)
173       index -= config->tableBase;
174     return index;
175 
176   }
177   case R_WASM_MEMORY_ADDR_SLEB:
178   case R_WASM_MEMORY_ADDR_I32:
179   case R_WASM_MEMORY_ADDR_LEB:
180   case R_WASM_MEMORY_ADDR_REL_SLEB:
181     if (isa<UndefinedData>(sym))
182       return 0;
183     return cast<DefinedData>(sym)->getVirtualAddress() + reloc.Addend;
184   case R_WASM_TYPE_INDEX_LEB:
185     return typeMap[reloc.Index];
186   case R_WASM_FUNCTION_INDEX_LEB:
187     return getFunctionSymbol(reloc.Index)->getFunctionIndex();
188   case R_WASM_GLOBAL_INDEX_LEB:
189     if (auto gs = dyn_cast<GlobalSymbol>(sym))
190       return gs->getGlobalIndex();
191     return sym->getGOTIndex();
192   case R_WASM_EVENT_INDEX_LEB:
193     return getEventSymbol(reloc.Index)->getEventIndex();
194   case R_WASM_FUNCTION_OFFSET_I32: {
195     auto *f = cast<DefinedFunction>(sym);
196     return f->function->outputOffset + f->function->getFunctionCodeOffset() +
197            reloc.Addend;
198   }
199   case R_WASM_SECTION_OFFSET_I32:
200     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
201   default:
202     llvm_unreachable("unknown relocation type");
203   }
204 }
205 
206 template <class T>
207 static void setRelocs(const std::vector<T *> &chunks,
208                       const WasmSection *section) {
209   if (!section)
210     return;
211 
212   ArrayRef<WasmRelocation> relocs = section->Relocations;
213   assert(std::is_sorted(relocs.begin(), relocs.end(),
214                         [](const WasmRelocation &r1, const WasmRelocation &r2) {
215                           return r1.Offset < r2.Offset;
216                         }));
217   assert(std::is_sorted(
218       chunks.begin(), chunks.end(), [](InputChunk *c1, InputChunk *c2) {
219         return c1->getInputSectionOffset() < c2->getInputSectionOffset();
220       }));
221 
222   auto relocsNext = relocs.begin();
223   auto relocsEnd = relocs.end();
224   auto relocLess = [](const WasmRelocation &r, uint32_t val) {
225     return r.Offset < val;
226   };
227   for (InputChunk *c : chunks) {
228     auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
229                                         c->getInputSectionOffset(), relocLess);
230     relocsNext = std::lower_bound(
231         relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
232         relocLess);
233     c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
234   }
235 }
236 
237 void ObjFile::parse(bool ignoreComdats) {
238   // Parse a memory buffer as a wasm file.
239   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
240   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
241 
242   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
243   if (!obj)
244     fatal(toString(this) + ": not a wasm file");
245   if (!obj->isRelocatableObject())
246     fatal(toString(this) + ": not a relocatable wasm file");
247 
248   bin.release();
249   wasmObj.reset(obj);
250 
251   // Build up a map of function indices to table indices for use when
252   // verifying the existing table index relocations
253   uint32_t totalFunctions =
254       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
255   tableEntries.resize(totalFunctions);
256   for (const WasmElemSegment &seg : wasmObj->elements()) {
257     if (seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
258       fatal(toString(this) + ": invalid table elements");
259     uint32_t offset = seg.Offset.Value.Int32;
260     for (uint32_t index = 0; index < seg.Functions.size(); index++) {
261 
262       uint32_t functionIndex = seg.Functions[index];
263       tableEntries[functionIndex] = offset + index;
264     }
265   }
266 
267   uint32_t sectionIndex = 0;
268 
269   // Bool for each symbol, true if called directly.  This allows us to implement
270   // a weaker form of signature checking where undefined functions that are not
271   // called directly (i.e. only address taken) don't have to match the defined
272   // function's signature.  We cannot do this for directly called functions
273   // because those signatures are checked at validation times.
274   // See https://bugs.llvm.org/show_bug.cgi?id=40412
275   std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
276   for (const SectionRef &sec : wasmObj->sections()) {
277     const WasmSection &section = wasmObj->getWasmSection(sec);
278     // Wasm objects can have at most one code and one data section.
279     if (section.Type == WASM_SEC_CODE) {
280       assert(!codeSection);
281       codeSection = &section;
282     } else if (section.Type == WASM_SEC_DATA) {
283       assert(!dataSection);
284       dataSection = &section;
285     } else if (section.Type == WASM_SEC_CUSTOM) {
286       customSections.emplace_back(make<InputSection>(section, this));
287       customSections.back()->setRelocations(section.Relocations);
288       customSectionsByIndex[sectionIndex] = customSections.back();
289     }
290     sectionIndex++;
291     // Scans relocations to dermine determine if a function symbol is called
292     // directly
293     for (const WasmRelocation &reloc : section.Relocations)
294       if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
295         isCalledDirectly[reloc.Index] = true;
296   }
297 
298   typeMap.resize(getWasmObj()->types().size());
299   typeIsUsed.resize(getWasmObj()->types().size(), false);
300 
301   ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
302   for (StringRef comdat : comdats) {
303     bool isNew = ignoreComdats || symtab->addComdat(comdat);
304     keptComdats.push_back(isNew);
305   }
306 
307   // Populate `Segments`.
308   for (const WasmSegment &s : wasmObj->dataSegments()) {
309     auto* seg = make<InputSegment>(s, this);
310     seg->discarded = isExcludedByComdat(seg);
311     segments.emplace_back(seg);
312   }
313   setRelocs(segments, dataSection);
314 
315   // Populate `Functions`.
316   ArrayRef<WasmFunction> funcs = wasmObj->functions();
317   ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes();
318   ArrayRef<WasmSignature> types = wasmObj->types();
319   functions.reserve(funcs.size());
320 
321   for (size_t i = 0, e = funcs.size(); i != e; ++i) {
322     auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this);
323     func->discarded = isExcludedByComdat(func);
324     functions.emplace_back(func);
325   }
326   setRelocs(functions, codeSection);
327 
328   // Populate `Globals`.
329   for (const WasmGlobal &g : wasmObj->globals())
330     globals.emplace_back(make<InputGlobal>(g, this));
331 
332   // Populate `Events`.
333   for (const WasmEvent &e : wasmObj->events())
334     events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this));
335 
336   // Populate `Symbols` based on the symbols in the object.
337   symbols.reserve(wasmObj->getNumberOfSymbols());
338   for (const SymbolRef &sym : wasmObj->symbols()) {
339     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
340     if (wasmSym.isDefined()) {
341       // createDefined may fail if the symbol is comdat excluded in which case
342       // we fall back to creating an undefined symbol
343       if (Symbol *d = createDefined(wasmSym)) {
344         symbols.push_back(d);
345         continue;
346       }
347     }
348     size_t idx = symbols.size();
349     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
350   }
351 }
352 
353 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const {
354   uint32_t c = chunk->getComdat();
355   if (c == UINT32_MAX)
356     return false;
357   return !keptComdats[c];
358 }
359 
360 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
361   return cast<FunctionSymbol>(symbols[index]);
362 }
363 
364 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
365   return cast<GlobalSymbol>(symbols[index]);
366 }
367 
368 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const {
369   return cast<EventSymbol>(symbols[index]);
370 }
371 
372 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
373   return cast<SectionSymbol>(symbols[index]);
374 }
375 
376 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
377   return cast<DataSymbol>(symbols[index]);
378 }
379 
380 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
381   StringRef name = sym.Info.Name;
382   uint32_t flags = sym.Info.Flags;
383 
384   switch (sym.Info.Kind) {
385   case WASM_SYMBOL_TYPE_FUNCTION: {
386     InputFunction *func =
387         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
388     if (sym.isBindingLocal())
389       return make<DefinedFunction>(name, flags, this, func);
390     if (func->discarded)
391       return nullptr;
392     return symtab->addDefinedFunction(name, flags, this, func);
393   }
394   case WASM_SYMBOL_TYPE_DATA: {
395     InputSegment *seg = segments[sym.Info.DataRef.Segment];
396     uint32_t offset = sym.Info.DataRef.Offset;
397     uint32_t size = sym.Info.DataRef.Size;
398     if (sym.isBindingLocal())
399       return make<DefinedData>(name, flags, this, seg, offset, size);
400     if (seg->discarded)
401       return nullptr;
402     return symtab->addDefinedData(name, flags, this, seg, offset, size);
403   }
404   case WASM_SYMBOL_TYPE_GLOBAL: {
405     InputGlobal *global =
406         globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
407     if (sym.isBindingLocal())
408       return make<DefinedGlobal>(name, flags, this, global);
409     return symtab->addDefinedGlobal(name, flags, this, global);
410   }
411   case WASM_SYMBOL_TYPE_SECTION: {
412     InputSection *section = customSectionsByIndex[sym.Info.ElementIndex];
413     assert(sym.isBindingLocal());
414     return make<SectionSymbol>(flags, section, this);
415   }
416   case WASM_SYMBOL_TYPE_EVENT: {
417     InputEvent *event =
418         events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()];
419     if (sym.isBindingLocal())
420       return make<DefinedEvent>(name, flags, this, event);
421     return symtab->addDefinedEvent(name, flags, this, event);
422   }
423   }
424   llvm_unreachable("unknown symbol kind");
425 }
426 
427 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
428   StringRef name = sym.Info.Name;
429   uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
430 
431   switch (sym.Info.Kind) {
432   case WASM_SYMBOL_TYPE_FUNCTION:
433     if (sym.isBindingLocal())
434       return make<UndefinedFunction>(name, sym.Info.ImportName,
435                                      sym.Info.ImportModule, flags, this,
436                                      sym.Signature, isCalledDirectly);
437     return symtab->addUndefinedFunction(name, sym.Info.ImportName,
438                                         sym.Info.ImportModule, flags, this,
439                                         sym.Signature, isCalledDirectly);
440   case WASM_SYMBOL_TYPE_DATA:
441     if (sym.isBindingLocal())
442       return make<UndefinedData>(name, flags, this);
443     return symtab->addUndefinedData(name, flags, this);
444   case WASM_SYMBOL_TYPE_GLOBAL:
445     if (sym.isBindingLocal())
446       return make<UndefinedGlobal>(name, sym.Info.ImportName,
447                                    sym.Info.ImportModule, flags, this,
448                                    sym.GlobalType);
449     return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
450                                       sym.Info.ImportModule, flags, this,
451                                       sym.GlobalType);
452   case WASM_SYMBOL_TYPE_SECTION:
453     llvm_unreachable("section symbols cannot be undefined");
454   }
455   llvm_unreachable("unknown symbol kind");
456 }
457 
458 void ArchiveFile::parse() {
459   // Parse a MemoryBufferRef as an archive file.
460   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
461   file = CHECK(Archive::create(mb), toString(this));
462 
463   // Read the symbol table to construct Lazy symbols.
464   int count = 0;
465   for (const Archive::Symbol &sym : file->symbols()) {
466     symtab->addLazy(this, &sym);
467     ++count;
468   }
469   LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
470 }
471 
472 void ArchiveFile::addMember(const Archive::Symbol *sym) {
473   const Archive::Child &c =
474       CHECK(sym->getMember(),
475             "could not get the member for symbol " + sym->getName());
476 
477   // Don't try to load the same member twice (this can happen when members
478   // mutually reference each other).
479   if (!seen.insert(c.getChildOffset()).second)
480     return;
481 
482   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
483   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
484 
485   MemoryBufferRef mb =
486       CHECK(c.getMemoryBufferRef(),
487             "could not get the buffer for the member defining symbol " +
488                 sym->getName());
489 
490   InputFile *obj = createObjectFile(mb, getName());
491   symtab->addFile(obj);
492 }
493 
494 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
495   switch (gvVisibility) {
496   case GlobalValue::DefaultVisibility:
497     return WASM_SYMBOL_VISIBILITY_DEFAULT;
498   case GlobalValue::HiddenVisibility:
499   case GlobalValue::ProtectedVisibility:
500     return WASM_SYMBOL_VISIBILITY_HIDDEN;
501   }
502   llvm_unreachable("unknown visibility");
503 }
504 
505 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
506                                    const lto::InputFile::Symbol &objSym,
507                                    BitcodeFile &f) {
508   StringRef name = saver.save(objSym.getName());
509 
510   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
511   flags |= mapVisibility(objSym.getVisibility());
512 
513   int c = objSym.getComdatIndex();
514   bool excludedByComdat = c != -1 && !keptComdats[c];
515 
516   if (objSym.isUndefined() || excludedByComdat) {
517     flags |= WASM_SYMBOL_UNDEFINED;
518     if (objSym.isExecutable())
519       return symtab->addUndefinedFunction(name, name, defaultModule, flags, &f,
520                                           nullptr, true);
521     return symtab->addUndefinedData(name, flags, &f);
522   }
523 
524   if (objSym.isExecutable())
525     return symtab->addDefinedFunction(name, flags, &f, nullptr);
526   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
527 }
528 
529 void BitcodeFile::parse() {
530   obj = check(lto::InputFile::create(MemoryBufferRef(
531       mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier()))));
532   Triple t(obj->getTargetTriple());
533   if (t.getArch() != Triple::wasm32) {
534     error(toString(mb.getBufferIdentifier()) + ": machine type must be wasm32");
535     return;
536   }
537   std::vector<bool> keptComdats;
538   for (StringRef s : obj->getComdatTable())
539     keptComdats.push_back(symtab->addComdat(s));
540 
541   for (const lto::InputFile::Symbol &objSym : obj->symbols())
542     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
543 }
544 
545 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
546 std::string lld::toString(const wasm::InputFile *file) {
547   if (!file)
548     return "<internal>";
549 
550   if (file->archiveName.empty())
551     return file->getName();
552 
553   return (file->archiveName + "(" + file->getName() + ")").str();
554 }
555