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