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