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 "llvm/Object/Binary.h"
18 #include "llvm/Object/Wasm.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 #define DEBUG_TYPE "lld"
22 
23 using namespace lld;
24 using namespace lld::wasm;
25 
26 using namespace llvm;
27 using namespace llvm::object;
28 using namespace llvm::wasm;
29 
30 Optional<MemoryBufferRef> lld::wasm::readFile(StringRef Path) {
31   log("Loading: " + Path);
32 
33   auto MBOrErr = MemoryBuffer::getFile(Path);
34   if (auto EC = MBOrErr.getError()) {
35     error("cannot open " + Path + ": " + EC.message());
36     return None;
37   }
38   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
39   MemoryBufferRef MBRef = MB->getMemBufferRef();
40   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
41 
42   return MBRef;
43 }
44 
45 InputFile *lld::wasm::createObjectFile(MemoryBufferRef MB,
46                                        StringRef ArchiveName) {
47   file_magic Magic = identify_magic(MB.getBuffer());
48   if (Magic == file_magic::wasm_object) {
49     std::unique_ptr<Binary> Bin = check(createBinary(MB));
50     auto *Obj = cast<WasmObjectFile>(Bin.get());
51     if (Obj->isSharedObject())
52       return make<SharedFile>(MB);
53     return make<ObjFile>(MB, ArchiveName);
54   }
55 
56   if (Magic == file_magic::bitcode)
57     return make<BitcodeFile>(MB, ArchiveName);
58 
59   fatal("unknown file type: " + MB.getBufferIdentifier());
60 }
61 
62 void ObjFile::dumpInfo() const {
63   log("info for: " + getName() +
64       "\n              Symbols : " + Twine(Symbols.size()) +
65       "\n     Function Imports : " + Twine(WasmObj->getNumImportedFunctions()) +
66       "\n       Global Imports : " + Twine(WasmObj->getNumImportedGlobals()) +
67       "\n        Event Imports : " + Twine(WasmObj->getNumImportedEvents()));
68 }
69 
70 // Relocations contain either symbol or type indices.  This function takes a
71 // relocation and returns relocated index (i.e. translates from the input
72 // symbol/type space to the output symbol/type space).
73 uint32_t ObjFile::calcNewIndex(const WasmRelocation &Reloc) const {
74   if (Reloc.Type == R_WASM_TYPE_INDEX_LEB) {
75     assert(TypeIsUsed[Reloc.Index]);
76     return TypeMap[Reloc.Index];
77   }
78   return Symbols[Reloc.Index]->getOutputSymbolIndex();
79 }
80 
81 // Relocations can contain addend for combined sections. This function takes a
82 // relocation and returns updated addend by offset in the output section.
83 uint32_t ObjFile::calcNewAddend(const WasmRelocation &Reloc) const {
84   switch (Reloc.Type) {
85   case R_WASM_MEMORY_ADDR_LEB:
86   case R_WASM_MEMORY_ADDR_SLEB:
87   case R_WASM_MEMORY_ADDR_I32:
88   case R_WASM_FUNCTION_OFFSET_I32:
89     return Reloc.Addend;
90   case R_WASM_SECTION_OFFSET_I32:
91     return getSectionSymbol(Reloc.Index)->Section->OutputOffset + Reloc.Addend;
92   default:
93     llvm_unreachable("unexpected relocation type");
94   }
95 }
96 
97 // Calculate the value we expect to find at the relocation location.
98 // This is used as a sanity check before applying a relocation to a given
99 // location.  It is useful for catching bugs in the compiler and linker.
100 uint32_t ObjFile::calcExpectedValue(const WasmRelocation &Reloc) const {
101   switch (Reloc.Type) {
102   case R_WASM_TABLE_INDEX_I32:
103   case R_WASM_TABLE_INDEX_SLEB:
104   case R_WASM_TABLE_INDEX_REL_SLEB: {
105     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
106     return TableEntries[Sym.Info.ElementIndex];
107   }
108   case R_WASM_MEMORY_ADDR_SLEB:
109   case R_WASM_MEMORY_ADDR_I32:
110   case R_WASM_MEMORY_ADDR_LEB:
111   case R_WASM_MEMORY_ADDR_REL_SLEB: {
112     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
113     if (Sym.isUndefined())
114       return 0;
115     const WasmSegment &Segment =
116         WasmObj->dataSegments()[Sym.Info.DataRef.Segment];
117     return Segment.Data.Offset.Value.Int32 + Sym.Info.DataRef.Offset +
118            Reloc.Addend;
119   }
120   case R_WASM_FUNCTION_OFFSET_I32:
121     if (auto *Sym = dyn_cast<DefinedFunction>(getFunctionSymbol(Reloc.Index))) {
122       return Sym->Function->getFunctionInputOffset() +
123              Sym->Function->getFunctionCodeOffset() + Reloc.Addend;
124     }
125     return 0;
126   case R_WASM_SECTION_OFFSET_I32:
127     return Reloc.Addend;
128   case R_WASM_TYPE_INDEX_LEB:
129     return Reloc.Index;
130   case R_WASM_FUNCTION_INDEX_LEB:
131   case R_WASM_GLOBAL_INDEX_LEB:
132   case R_WASM_EVENT_INDEX_LEB: {
133     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
134     return Sym.Info.ElementIndex;
135   }
136   default:
137     llvm_unreachable("unknown relocation type");
138   }
139 }
140 
141 // Translate from the relocation's index into the final linked output value.
142 uint32_t ObjFile::calcNewValue(const WasmRelocation &Reloc) const {
143   switch (Reloc.Type) {
144   case R_WASM_TABLE_INDEX_I32:
145   case R_WASM_TABLE_INDEX_SLEB:
146   case R_WASM_TABLE_INDEX_REL_SLEB:
147     return getFunctionSymbol(Reloc.Index)->getTableIndex();
148   case R_WASM_MEMORY_ADDR_SLEB:
149   case R_WASM_MEMORY_ADDR_I32:
150   case R_WASM_MEMORY_ADDR_LEB:
151   case R_WASM_MEMORY_ADDR_REL_SLEB:
152     if (auto *Sym = dyn_cast<DefinedData>(getDataSymbol(Reloc.Index)))
153       if (Sym->isLive())
154         return Sym->getVirtualAddress() + Reloc.Addend;
155     return 0;
156   case R_WASM_TYPE_INDEX_LEB:
157     return TypeMap[Reloc.Index];
158   case R_WASM_FUNCTION_INDEX_LEB:
159     return getFunctionSymbol(Reloc.Index)->getFunctionIndex();
160   case R_WASM_GLOBAL_INDEX_LEB: {
161     const Symbol* Sym = Symbols[Reloc.Index];
162     if (auto GS = dyn_cast<GlobalSymbol>(Sym))
163       return GS->getGlobalIndex();
164     return Sym->getGOTIndex();
165   } case R_WASM_EVENT_INDEX_LEB:
166     return getEventSymbol(Reloc.Index)->getEventIndex();
167   case R_WASM_FUNCTION_OFFSET_I32:
168     if (auto *Sym = dyn_cast<DefinedFunction>(getFunctionSymbol(Reloc.Index))) {
169       if (Sym->isLive())
170         return Sym->Function->OutputOffset +
171                Sym->Function->getFunctionCodeOffset() + Reloc.Addend;
172     }
173     return 0;
174   case R_WASM_SECTION_OFFSET_I32:
175     return getSectionSymbol(Reloc.Index)->Section->OutputOffset + Reloc.Addend;
176   default:
177     llvm_unreachable("unknown relocation type");
178   }
179 }
180 
181 template <class T>
182 static void setRelocs(const std::vector<T *> &Chunks,
183                       const WasmSection *Section) {
184   if (!Section)
185     return;
186 
187   ArrayRef<WasmRelocation> Relocs = Section->Relocations;
188   assert(std::is_sorted(Relocs.begin(), Relocs.end(),
189                         [](const WasmRelocation &R1, const WasmRelocation &R2) {
190                           return R1.Offset < R2.Offset;
191                         }));
192   assert(std::is_sorted(
193       Chunks.begin(), Chunks.end(), [](InputChunk *C1, InputChunk *C2) {
194         return C1->getInputSectionOffset() < C2->getInputSectionOffset();
195       }));
196 
197   auto RelocsNext = Relocs.begin();
198   auto RelocsEnd = Relocs.end();
199   auto RelocLess = [](const WasmRelocation &R, uint32_t Val) {
200     return R.Offset < Val;
201   };
202   for (InputChunk *C : Chunks) {
203     auto RelocsStart = std::lower_bound(RelocsNext, RelocsEnd,
204                                         C->getInputSectionOffset(), RelocLess);
205     RelocsNext = std::lower_bound(
206         RelocsStart, RelocsEnd, C->getInputSectionOffset() + C->getInputSize(),
207         RelocLess);
208     C->setRelocations(ArrayRef<WasmRelocation>(RelocsStart, RelocsNext));
209   }
210 }
211 
212 void ObjFile::parse() {
213   // Parse a memory buffer as a wasm file.
214   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
215   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), toString(this));
216 
217   auto *Obj = dyn_cast<WasmObjectFile>(Bin.get());
218   if (!Obj)
219     fatal(toString(this) + ": not a wasm file");
220   if (!Obj->isRelocatableObject())
221     fatal(toString(this) + ": not a relocatable wasm file");
222 
223   Bin.release();
224   WasmObj.reset(Obj);
225 
226   // Build up a map of function indices to table indices for use when
227   // verifying the existing table index relocations
228   uint32_t TotalFunctions =
229       WasmObj->getNumImportedFunctions() + WasmObj->functions().size();
230   TableEntries.resize(TotalFunctions);
231   for (const WasmElemSegment &Seg : WasmObj->elements()) {
232     if (Seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
233       fatal(toString(this) + ": invalid table elements");
234     uint32_t Offset = Seg.Offset.Value.Int32;
235     for (uint32_t Index = 0; Index < Seg.Functions.size(); Index++) {
236 
237       uint32_t FunctionIndex = Seg.Functions[Index];
238       TableEntries[FunctionIndex] = Offset + Index;
239     }
240   }
241 
242   // Find the code and data sections.  Wasm objects can have at most one code
243   // and one data section.
244   uint32_t SectionIndex = 0;
245   for (const SectionRef &Sec : WasmObj->sections()) {
246     const WasmSection &Section = WasmObj->getWasmSection(Sec);
247     if (Section.Type == WASM_SEC_CODE) {
248       CodeSection = &Section;
249     } else if (Section.Type == WASM_SEC_DATA) {
250       DataSection = &Section;
251     } else if (Section.Type == WASM_SEC_CUSTOM) {
252       CustomSections.emplace_back(make<InputSection>(Section, this));
253       CustomSections.back()->setRelocations(Section.Relocations);
254       CustomSectionsByIndex[SectionIndex] = CustomSections.back();
255     }
256     SectionIndex++;
257   }
258 
259   TypeMap.resize(getWasmObj()->types().size());
260   TypeIsUsed.resize(getWasmObj()->types().size(), false);
261 
262   ArrayRef<StringRef> Comdats = WasmObj->linkingData().Comdats;
263   UsedComdats.resize(Comdats.size());
264   for (unsigned I = 0; I < Comdats.size(); ++I)
265     UsedComdats[I] = Symtab->addComdat(Comdats[I]);
266 
267   // Populate `Segments`.
268   for (const WasmSegment &S : WasmObj->dataSegments())
269     Segments.emplace_back(make<InputSegment>(S, this));
270   setRelocs(Segments, DataSection);
271 
272   // Populate `Functions`.
273   ArrayRef<WasmFunction> Funcs = WasmObj->functions();
274   ArrayRef<uint32_t> FuncTypes = WasmObj->functionTypes();
275   ArrayRef<WasmSignature> Types = WasmObj->types();
276   Functions.reserve(Funcs.size());
277 
278   for (size_t I = 0, E = Funcs.size(); I != E; ++I)
279     Functions.emplace_back(
280         make<InputFunction>(Types[FuncTypes[I]], &Funcs[I], this));
281   setRelocs(Functions, CodeSection);
282 
283   // Populate `Globals`.
284   for (const WasmGlobal &G : WasmObj->globals())
285     Globals.emplace_back(make<InputGlobal>(G, this));
286 
287   // Populate `Events`.
288   for (const WasmEvent &E : WasmObj->events())
289     Events.emplace_back(make<InputEvent>(Types[E.Type.SigIndex], E, this));
290 
291   // Populate `Symbols` based on the WasmSymbols in the object.
292   Symbols.reserve(WasmObj->getNumberOfSymbols());
293   for (const SymbolRef &Sym : WasmObj->symbols()) {
294     const WasmSymbol &WasmSym = WasmObj->getWasmSymbol(Sym.getRawDataRefImpl());
295     if (Symbol *Sym = createDefined(WasmSym))
296       Symbols.push_back(Sym);
297     else
298       Symbols.push_back(createUndefined(WasmSym));
299   }
300 }
301 
302 bool ObjFile::isExcludedByComdat(InputChunk *Chunk) const {
303   uint32_t C = Chunk->getComdat();
304   if (C == UINT32_MAX)
305     return false;
306   return !UsedComdats[C];
307 }
308 
309 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t Index) const {
310   return cast<FunctionSymbol>(Symbols[Index]);
311 }
312 
313 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t Index) const {
314   return cast<GlobalSymbol>(Symbols[Index]);
315 }
316 
317 EventSymbol *ObjFile::getEventSymbol(uint32_t Index) const {
318   return cast<EventSymbol>(Symbols[Index]);
319 }
320 
321 SectionSymbol *ObjFile::getSectionSymbol(uint32_t Index) const {
322   return cast<SectionSymbol>(Symbols[Index]);
323 }
324 
325 DataSymbol *ObjFile::getDataSymbol(uint32_t Index) const {
326   return cast<DataSymbol>(Symbols[Index]);
327 }
328 
329 Symbol *ObjFile::createDefined(const WasmSymbol &Sym) {
330   if (!Sym.isDefined())
331     return nullptr;
332 
333   StringRef Name = Sym.Info.Name;
334   uint32_t Flags = Sym.Info.Flags;
335 
336   switch (Sym.Info.Kind) {
337   case WASM_SYMBOL_TYPE_FUNCTION: {
338     InputFunction *Func =
339         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
340     if (isExcludedByComdat(Func)) {
341       Func->Live = false;
342       return nullptr;
343     }
344 
345     if (Sym.isBindingLocal())
346       return make<DefinedFunction>(Name, Flags, this, Func);
347     return Symtab->addDefinedFunction(Name, Flags, this, Func);
348   }
349   case WASM_SYMBOL_TYPE_DATA: {
350     InputSegment *Seg = Segments[Sym.Info.DataRef.Segment];
351     if (isExcludedByComdat(Seg)) {
352       Seg->Live = false;
353       return nullptr;
354     }
355 
356     uint32_t Offset = Sym.Info.DataRef.Offset;
357     uint32_t Size = Sym.Info.DataRef.Size;
358 
359     if (Sym.isBindingLocal())
360       return make<DefinedData>(Name, Flags, this, Seg, Offset, Size);
361     return Symtab->addDefinedData(Name, Flags, this, Seg, Offset, Size);
362   }
363   case WASM_SYMBOL_TYPE_GLOBAL: {
364     InputGlobal *Global =
365         Globals[Sym.Info.ElementIndex - WasmObj->getNumImportedGlobals()];
366     if (Sym.isBindingLocal())
367       return make<DefinedGlobal>(Name, Flags, this, Global);
368     return Symtab->addDefinedGlobal(Name, Flags, this, Global);
369   }
370   case WASM_SYMBOL_TYPE_SECTION: {
371     InputSection *Section = CustomSectionsByIndex[Sym.Info.ElementIndex];
372     assert(Sym.isBindingLocal());
373     return make<SectionSymbol>(Name, Flags, Section, this);
374   }
375   case WASM_SYMBOL_TYPE_EVENT: {
376     InputEvent *Event =
377         Events[Sym.Info.ElementIndex - WasmObj->getNumImportedEvents()];
378     if (Sym.isBindingLocal())
379       return make<DefinedEvent>(Name, Flags, this, Event);
380     return Symtab->addDefinedEvent(Name, Flags, this, Event);
381   }
382   }
383   llvm_unreachable("unknown symbol kind");
384 }
385 
386 Symbol *ObjFile::createUndefined(const WasmSymbol &Sym) {
387   StringRef Name = Sym.Info.Name;
388   uint32_t Flags = Sym.Info.Flags;
389 
390   switch (Sym.Info.Kind) {
391   case WASM_SYMBOL_TYPE_FUNCTION:
392     return Symtab->addUndefinedFunction(Name, Sym.Info.ImportName,
393                                         Sym.Info.ImportModule, Flags, this,
394                                         Sym.Signature);
395   case WASM_SYMBOL_TYPE_DATA:
396     return Symtab->addUndefinedData(Name, Flags, this);
397   case WASM_SYMBOL_TYPE_GLOBAL:
398     return Symtab->addUndefinedGlobal(Name, Sym.Info.ImportName,
399                                       Sym.Info.ImportModule, Flags, this,
400                                       Sym.GlobalType);
401   case WASM_SYMBOL_TYPE_SECTION:
402     llvm_unreachable("section symbols cannot be undefined");
403   }
404   llvm_unreachable("unknown symbol kind");
405 }
406 
407 void ArchiveFile::parse() {
408   // Parse a MemoryBufferRef as an archive file.
409   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
410   File = CHECK(Archive::create(MB), toString(this));
411 
412   // Read the symbol table to construct Lazy symbols.
413   int Count = 0;
414   for (const Archive::Symbol &Sym : File->symbols()) {
415     Symtab->addLazy(this, &Sym);
416     ++Count;
417   }
418   LLVM_DEBUG(dbgs() << "Read " << Count << " symbols\n");
419 }
420 
421 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
422   const Archive::Child &C =
423       CHECK(Sym->getMember(),
424             "could not get the member for symbol " + Sym->getName());
425 
426   // Don't try to load the same member twice (this can happen when members
427   // mutually reference each other).
428   if (!Seen.insert(C.getChildOffset()).second)
429     return;
430 
431   LLVM_DEBUG(dbgs() << "loading lazy: " << Sym->getName() << "\n");
432   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
433 
434   MemoryBufferRef MB =
435       CHECK(C.getMemoryBufferRef(),
436             "could not get the buffer for the member defining symbol " +
437                 Sym->getName());
438 
439   InputFile *Obj = createObjectFile(MB, getName());
440   Symtab->addFile(Obj);
441 }
442 
443 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
444   switch (GvVisibility) {
445   case GlobalValue::DefaultVisibility:
446     return WASM_SYMBOL_VISIBILITY_DEFAULT;
447   case GlobalValue::HiddenVisibility:
448   case GlobalValue::ProtectedVisibility:
449     return WASM_SYMBOL_VISIBILITY_HIDDEN;
450   }
451   llvm_unreachable("unknown visibility");
452 }
453 
454 static Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &ObjSym,
455                                    BitcodeFile &F) {
456   StringRef Name = Saver.save(ObjSym.getName());
457 
458   uint32_t Flags = ObjSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
459   Flags |= mapVisibility(ObjSym.getVisibility());
460 
461   if (ObjSym.isUndefined()) {
462     if (ObjSym.isExecutable())
463       return Symtab->addUndefinedFunction(Name, Name, DefaultModule, Flags, &F,
464                                           nullptr);
465     return Symtab->addUndefinedData(Name, Flags, &F);
466   }
467 
468   if (ObjSym.isExecutable())
469     return Symtab->addDefinedFunction(Name, Flags, &F, nullptr);
470   return Symtab->addDefinedData(Name, Flags, &F, nullptr, 0, 0);
471 }
472 
473 void BitcodeFile::parse() {
474   Obj = check(lto::InputFile::create(MemoryBufferRef(
475       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier()))));
476   Triple T(Obj->getTargetTriple());
477   if (T.getArch() != Triple::wasm32) {
478     error(toString(MB.getBufferIdentifier()) + ": machine type must be wasm32");
479     return;
480   }
481 
482   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
483     Symbols.push_back(createBitcodeSymbol(ObjSym, *this));
484 }
485 
486 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
487 std::string lld::toString(const wasm::InputFile *File) {
488   if (!File)
489     return "<internal>";
490 
491   if (File->ArchiveName.empty())
492     return File->getName();
493 
494   return (File->ArchiveName + "(" + File->getName() + ")").str();
495 }
496