1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "InputFiles.h"
11 #include "Config.h"
12 #include "InputChunks.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 void ObjFile::dumpInfo() const {
46   log("info for: " + getName() +
47       "\n              Symbols : " + Twine(Symbols.size()) +
48       "\n     Function Imports : " + Twine(WasmObj->getNumImportedFunctions()) +
49       "\n       Global Imports : " + Twine(WasmObj->getNumImportedGlobals()));
50 }
51 
52 // Relocations contain either symbol or type indices.  This function takes a
53 // relocation and returns relocated index (i.e. translates from the input
54 // sybmol/type space to the output symbol/type space).
55 uint32_t ObjFile::calcNewIndex(const WasmRelocation &Reloc) const {
56   if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
57     assert(TypeIsUsed[Reloc.Index]);
58     return TypeMap[Reloc.Index];
59   }
60   return Symbols[Reloc.Index]->getOutputSymbolIndex();
61 }
62 
63 // Calculate the value we expect to find at the relocation location.
64 // This is used as a sanity check before applying a relocation to a given
65 // location.  It is useful for catching bugs in the compiler and linker.
66 uint32_t ObjFile::calcExpectedValue(const WasmRelocation &Reloc) const {
67   switch (Reloc.Type) {
68   case R_WEBASSEMBLY_TABLE_INDEX_I32:
69   case R_WEBASSEMBLY_TABLE_INDEX_SLEB: {
70     const WasmSymbol& Sym = WasmObj->syms()[Reloc.Index];
71     return TableEntries[Sym.Info.ElementIndex];
72   }
73   case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
74   case R_WEBASSEMBLY_MEMORY_ADDR_I32:
75   case R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
76     const WasmSymbol& Sym = WasmObj->syms()[Reloc.Index];
77     if (Sym.isUndefined())
78       return 0;
79     const WasmSegment& Segment = WasmObj->dataSegments()[Sym.Info.DataRef.Segment];
80     return Segment.Data.Offset.Value.Int32 + Sym.Info.DataRef.Offset +
81            Reloc.Addend;
82   }
83   case R_WEBASSEMBLY_TYPE_INDEX_LEB:
84     return Reloc.Index;
85   case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
86   case R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
87     const WasmSymbol& Sym = WasmObj->syms()[Reloc.Index];
88     return Sym.Info.ElementIndex;
89   }
90   default:
91     llvm_unreachable("unknown relocation type");
92   }
93 }
94 
95 // Translate from the relocation's index into the final linked output value.
96 uint32_t ObjFile::calcNewValue(const WasmRelocation &Reloc) const {
97   switch (Reloc.Type) {
98   case R_WEBASSEMBLY_TABLE_INDEX_I32:
99   case R_WEBASSEMBLY_TABLE_INDEX_SLEB:
100     return getFunctionSymbol(Reloc.Index)->getTableIndex();
101   case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
102   case R_WEBASSEMBLY_MEMORY_ADDR_I32:
103   case R_WEBASSEMBLY_MEMORY_ADDR_LEB:
104     if (auto *Sym = dyn_cast<DefinedData>(getDataSymbol(Reloc.Index)))
105       return Sym->getVirtualAddress() + Reloc.Addend;
106     return 0;
107   case R_WEBASSEMBLY_TYPE_INDEX_LEB:
108     return TypeMap[Reloc.Index];
109   case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
110     return getFunctionSymbol(Reloc.Index)->getFunctionIndex();
111   case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
112     return getGlobalSymbol(Reloc.Index)->getGlobalIndex();
113   default:
114     llvm_unreachable("unknown relocation type");
115   }
116 }
117 
118 void ObjFile::parse() {
119   // Parse a memory buffer as a wasm file.
120   DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
121   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), toString(this));
122 
123   auto *Obj = dyn_cast<WasmObjectFile>(Bin.get());
124   if (!Obj)
125     fatal(toString(this) + ": not a wasm file");
126   if (!Obj->isRelocatableObject())
127     fatal(toString(this) + ": not a relocatable wasm file");
128 
129   Bin.release();
130   WasmObj.reset(Obj);
131 
132   // Build up a map of function indices to table indices for use when
133   // verifying the existing table index relocations
134   uint32_t TotalFunctions =
135       WasmObj->getNumImportedFunctions() + WasmObj->functions().size();
136   TableEntries.resize(TotalFunctions);
137   for (const WasmElemSegment &Seg : WasmObj->elements()) {
138     if (Seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
139       fatal(toString(this) + ": invalid table elements");
140     uint32_t Offset = Seg.Offset.Value.Int32;
141     for (uint32_t Index = 0; Index < Seg.Functions.size(); Index++) {
142 
143       uint32_t FunctionIndex = Seg.Functions[Index];
144       TableEntries[FunctionIndex] = Offset + Index;
145     }
146   }
147 
148   // Find the code and data sections.  Wasm objects can have at most one code
149   // and one data section.
150   for (const SectionRef &Sec : WasmObj->sections()) {
151     const WasmSection &Section = WasmObj->getWasmSection(Sec);
152     if (Section.Type == WASM_SEC_CODE)
153       CodeSection = &Section;
154     else if (Section.Type == WASM_SEC_DATA)
155       DataSection = &Section;
156     else if (Section.Type == WASM_SEC_CUSTOM)
157       CustomSections.emplace_back(make<InputSection>(Section, this));
158   }
159 
160   TypeMap.resize(getWasmObj()->types().size());
161   TypeIsUsed.resize(getWasmObj()->types().size(), false);
162 
163   ArrayRef<StringRef> Comdats = WasmObj->linkingData().Comdats;
164   UsedComdats.resize(Comdats.size());
165   for (unsigned I = 0; I < Comdats.size(); ++I)
166     UsedComdats[I] = Symtab->addComdat(Comdats[I]);
167 
168   // Populate `Segments`.
169   for (const WasmSegment &S : WasmObj->dataSegments()) {
170     InputSegment *Seg = make<InputSegment>(S, this);
171     Seg->copyRelocations(*DataSection);
172     Segments.emplace_back(Seg);
173   }
174 
175   // Populate `Functions`.
176   ArrayRef<WasmFunction> Funcs = WasmObj->functions();
177   ArrayRef<uint32_t> FuncTypes = WasmObj->functionTypes();
178   ArrayRef<WasmSignature> Types = WasmObj->types();
179   Functions.reserve(Funcs.size());
180 
181   for (size_t I = 0, E = Funcs.size(); I != E; ++I) {
182     InputFunction *F =
183         make<InputFunction>(Types[FuncTypes[I]], &Funcs[I], this);
184     F->copyRelocations(*CodeSection);
185     Functions.emplace_back(F);
186   }
187 
188   // Populate `Globals`.
189   for (const WasmGlobal &G : WasmObj->globals())
190     Globals.emplace_back(make<InputGlobal>(G));
191 
192   // Populate `Symbols` based on the WasmSymbols in the object.
193   Symbols.reserve(WasmObj->getNumberOfSymbols());
194   for (const SymbolRef &Sym : WasmObj->symbols()) {
195     const WasmSymbol &WasmSym = WasmObj->getWasmSymbol(Sym.getRawDataRefImpl());
196     if (Symbol *Sym = createDefined(WasmSym))
197       Symbols.push_back(Sym);
198     else
199       Symbols.push_back(createUndefined(WasmSym));
200   }
201 }
202 
203 bool ObjFile::isExcludedByComdat(InputChunk *Chunk) const {
204   uint32_t C = Chunk->getComdat();
205   if (C == UINT32_MAX)
206     return false;
207   return !UsedComdats[C];
208 }
209 
210 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t Index) const {
211   return cast<FunctionSymbol>(Symbols[Index]);
212 }
213 
214 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t Index) const {
215   return cast<GlobalSymbol>(Symbols[Index]);
216 }
217 
218 DataSymbol *ObjFile::getDataSymbol(uint32_t Index) const {
219   return cast<DataSymbol>(Symbols[Index]);
220 }
221 
222 Symbol *ObjFile::createDefined(const WasmSymbol &Sym) {
223   if (!Sym.isDefined())
224     return nullptr;
225 
226   StringRef Name = Sym.Info.Name;
227   uint32_t Flags = Sym.Info.Flags;
228 
229   switch (Sym.Info.Kind) {
230   case WASM_SYMBOL_TYPE_FUNCTION: {
231     InputFunction *Func =
232         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
233     if (isExcludedByComdat(Func)) {
234       Func->Live = false;
235       return nullptr;
236     }
237 
238     if (Sym.isBindingLocal())
239       return make<DefinedFunction>(Name, Flags, this, Func);
240     return Symtab->addDefinedFunction(Name, Flags, this, Func);
241   }
242   case WASM_SYMBOL_TYPE_DATA: {
243     InputSegment *Seg = Segments[Sym.Info.DataRef.Segment];
244     if (isExcludedByComdat(Seg)) {
245       Seg->Live = false;
246       return nullptr;
247     }
248 
249     uint32_t Offset = Sym.Info.DataRef.Offset;
250     uint32_t Size = Sym.Info.DataRef.Size;
251 
252     if (Sym.isBindingLocal())
253       return make<DefinedData>(Name, Flags, this, Seg, Offset, Size);
254     return Symtab->addDefinedData(Name, Flags, this, Seg, Offset, Size);
255   }
256   case WASM_SYMBOL_TYPE_GLOBAL:
257     InputGlobal *Global =
258         Globals[Sym.Info.ElementIndex - WasmObj->getNumImportedGlobals()];
259     if (Sym.isBindingLocal())
260       return make<DefinedGlobal>(Name, Flags, this, Global);
261     return Symtab->addDefinedGlobal(Name, Flags, this, Global);
262   }
263   llvm_unreachable("unkown symbol kind");
264 }
265 
266 Symbol *ObjFile::createUndefined(const WasmSymbol &Sym) {
267   StringRef Name = Sym.Info.Name;
268   uint32_t Flags = Sym.Info.Flags;
269 
270   switch (Sym.Info.Kind) {
271   case WASM_SYMBOL_TYPE_FUNCTION:
272     return Symtab->addUndefinedFunction(Name, Flags, this, Sym.FunctionType);
273   case WASM_SYMBOL_TYPE_DATA:
274     return Symtab->addUndefinedData(Name, Flags, this);
275   case WASM_SYMBOL_TYPE_GLOBAL:
276     return Symtab->addUndefinedGlobal(Name, Flags, this, Sym.GlobalType);
277   }
278   llvm_unreachable("unkown symbol kind");
279 }
280 
281 void ArchiveFile::parse() {
282   // Parse a MemoryBufferRef as an archive file.
283   DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
284   File = CHECK(Archive::create(MB), toString(this));
285 
286   // Read the symbol table to construct Lazy symbols.
287   int Count = 0;
288   for (const Archive::Symbol &Sym : File->symbols()) {
289     Symtab->addLazy(this, &Sym);
290     ++Count;
291   }
292   DEBUG(dbgs() << "Read " << Count << " symbols\n");
293 }
294 
295 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
296   const Archive::Child &C =
297       CHECK(Sym->getMember(),
298             "could not get the member for symbol " + Sym->getName());
299 
300   // Don't try to load the same member twice (this can happen when members
301   // mutually reference each other).
302   if (!Seen.insert(C.getChildOffset()).second)
303     return;
304 
305   DEBUG(dbgs() << "loading lazy: " << Sym->getName() << "\n");
306   DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
307 
308   MemoryBufferRef MB =
309       CHECK(C.getMemoryBufferRef(),
310             "could not get the buffer for the member defining symbol " +
311                 Sym->getName());
312 
313   if (identify_magic(MB.getBuffer()) != file_magic::wasm_object) {
314     error("unknown file type: " + MB.getBufferIdentifier());
315     return;
316   }
317 
318   InputFile *Obj = make<ObjFile>(MB);
319   Obj->ParentName = ParentName;
320   Symtab->addFile(Obj);
321 }
322 
323 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
324 std::string lld::toString(const wasm::InputFile *File) {
325   if (!File)
326     return "<internal>";
327 
328   if (File->ParentName.empty())
329     return File->getName();
330 
331   return (File->ParentName + "(" + File->getName() + ")").str();
332 }
333