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       if (Section.Name == "producers")
248         ProducersSection = &Section;
249     }
250     SectionIndex++;
251   }
252 
253   TypeMap.resize(getWasmObj()->types().size());
254   TypeIsUsed.resize(getWasmObj()->types().size(), false);
255 
256   ArrayRef<StringRef> Comdats = WasmObj->linkingData().Comdats;
257   UsedComdats.resize(Comdats.size());
258   for (unsigned I = 0; I < Comdats.size(); ++I)
259     UsedComdats[I] = Symtab->addComdat(Comdats[I]);
260 
261   // Populate `Segments`.
262   for (const WasmSegment &S : WasmObj->dataSegments())
263     Segments.emplace_back(make<InputSegment>(S, this));
264   setRelocs(Segments, DataSection);
265 
266   // Populate `Functions`.
267   ArrayRef<WasmFunction> Funcs = WasmObj->functions();
268   ArrayRef<uint32_t> FuncTypes = WasmObj->functionTypes();
269   ArrayRef<WasmSignature> Types = WasmObj->types();
270   Functions.reserve(Funcs.size());
271 
272   for (size_t I = 0, E = Funcs.size(); I != E; ++I)
273     Functions.emplace_back(
274         make<InputFunction>(Types[FuncTypes[I]], &Funcs[I], this));
275   setRelocs(Functions, CodeSection);
276 
277   // Populate `Globals`.
278   for (const WasmGlobal &G : WasmObj->globals())
279     Globals.emplace_back(make<InputGlobal>(G, this));
280 
281   // Populate `Events`.
282   for (const WasmEvent &E : WasmObj->events())
283     Events.emplace_back(make<InputEvent>(Types[E.Type.SigIndex], E, this));
284 
285   // Populate `Symbols` based on the WasmSymbols in the object.
286   Symbols.reserve(WasmObj->getNumberOfSymbols());
287   for (const SymbolRef &Sym : WasmObj->symbols()) {
288     const WasmSymbol &WasmSym = WasmObj->getWasmSymbol(Sym.getRawDataRefImpl());
289     if (Symbol *Sym = createDefined(WasmSym))
290       Symbols.push_back(Sym);
291     else
292       Symbols.push_back(createUndefined(WasmSym));
293   }
294 }
295 
296 bool ObjFile::isExcludedByComdat(InputChunk *Chunk) const {
297   uint32_t C = Chunk->getComdat();
298   if (C == UINT32_MAX)
299     return false;
300   return !UsedComdats[C];
301 }
302 
303 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t Index) const {
304   return cast<FunctionSymbol>(Symbols[Index]);
305 }
306 
307 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t Index) const {
308   return cast<GlobalSymbol>(Symbols[Index]);
309 }
310 
311 EventSymbol *ObjFile::getEventSymbol(uint32_t Index) const {
312   return cast<EventSymbol>(Symbols[Index]);
313 }
314 
315 SectionSymbol *ObjFile::getSectionSymbol(uint32_t Index) const {
316   return cast<SectionSymbol>(Symbols[Index]);
317 }
318 
319 DataSymbol *ObjFile::getDataSymbol(uint32_t Index) const {
320   return cast<DataSymbol>(Symbols[Index]);
321 }
322 
323 Symbol *ObjFile::createDefined(const WasmSymbol &Sym) {
324   if (!Sym.isDefined())
325     return nullptr;
326 
327   StringRef Name = Sym.Info.Name;
328   uint32_t Flags = Sym.Info.Flags;
329 
330   switch (Sym.Info.Kind) {
331   case WASM_SYMBOL_TYPE_FUNCTION: {
332     InputFunction *Func =
333         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
334     if (isExcludedByComdat(Func)) {
335       Func->Live = false;
336       return nullptr;
337     }
338 
339     if (Sym.isBindingLocal())
340       return make<DefinedFunction>(Name, Flags, this, Func);
341     return Symtab->addDefinedFunction(Name, Flags, this, Func);
342   }
343   case WASM_SYMBOL_TYPE_DATA: {
344     InputSegment *Seg = Segments[Sym.Info.DataRef.Segment];
345     if (isExcludedByComdat(Seg)) {
346       Seg->Live = false;
347       return nullptr;
348     }
349 
350     uint32_t Offset = Sym.Info.DataRef.Offset;
351     uint32_t Size = Sym.Info.DataRef.Size;
352 
353     if (Sym.isBindingLocal())
354       return make<DefinedData>(Name, Flags, this, Seg, Offset, Size);
355     return Symtab->addDefinedData(Name, Flags, this, Seg, Offset, Size);
356   }
357   case WASM_SYMBOL_TYPE_GLOBAL: {
358     InputGlobal *Global =
359         Globals[Sym.Info.ElementIndex - WasmObj->getNumImportedGlobals()];
360     if (Sym.isBindingLocal())
361       return make<DefinedGlobal>(Name, Flags, this, Global);
362     return Symtab->addDefinedGlobal(Name, Flags, this, Global);
363   }
364   case WASM_SYMBOL_TYPE_SECTION: {
365     InputSection *Section = CustomSectionsByIndex[Sym.Info.ElementIndex];
366     assert(Sym.isBindingLocal());
367     return make<SectionSymbol>(Name, Flags, Section, this);
368   }
369   case WASM_SYMBOL_TYPE_EVENT: {
370     InputEvent *Event =
371         Events[Sym.Info.ElementIndex - WasmObj->getNumImportedEvents()];
372     if (Sym.isBindingLocal())
373       return make<DefinedEvent>(Name, Flags, this, Event);
374     return Symtab->addDefinedEvent(Name, Flags, this, Event);
375   }
376   }
377   llvm_unreachable("unknown symbol kind");
378 }
379 
380 Symbol *ObjFile::createUndefined(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     return Symtab->addUndefinedFunction(Name, Sym.Info.ImportName,
387                                         Sym.Info.ImportModule, Flags, this,
388                                         Sym.Signature);
389   case WASM_SYMBOL_TYPE_DATA:
390     return Symtab->addUndefinedData(Name, Flags, this);
391   case WASM_SYMBOL_TYPE_GLOBAL:
392     return Symtab->addUndefinedGlobal(Name, Sym.Info.ImportName,
393                                       Sym.Info.ImportModule, Flags, this,
394                                       Sym.GlobalType);
395   case WASM_SYMBOL_TYPE_SECTION:
396     llvm_unreachable("section symbols cannot be undefined");
397   }
398   llvm_unreachable("unknown symbol kind");
399 }
400 
401 void ArchiveFile::parse() {
402   // Parse a MemoryBufferRef as an archive file.
403   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
404   File = CHECK(Archive::create(MB), toString(this));
405 
406   // Read the symbol table to construct Lazy symbols.
407   int Count = 0;
408   for (const Archive::Symbol &Sym : File->symbols()) {
409     Symtab->addLazy(this, &Sym);
410     ++Count;
411   }
412   LLVM_DEBUG(dbgs() << "Read " << Count << " symbols\n");
413 }
414 
415 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
416   const Archive::Child &C =
417       CHECK(Sym->getMember(),
418             "could not get the member for symbol " + Sym->getName());
419 
420   // Don't try to load the same member twice (this can happen when members
421   // mutually reference each other).
422   if (!Seen.insert(C.getChildOffset()).second)
423     return;
424 
425   LLVM_DEBUG(dbgs() << "loading lazy: " << Sym->getName() << "\n");
426   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
427 
428   MemoryBufferRef MB =
429       CHECK(C.getMemoryBufferRef(),
430             "could not get the buffer for the member defining symbol " +
431                 Sym->getName());
432 
433   InputFile *Obj = createObjectFile(MB);
434   Obj->ArchiveName = getName();
435   Symtab->addFile(Obj);
436 }
437 
438 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
439   switch (GvVisibility) {
440   case GlobalValue::DefaultVisibility:
441     return WASM_SYMBOL_VISIBILITY_DEFAULT;
442   case GlobalValue::HiddenVisibility:
443   case GlobalValue::ProtectedVisibility:
444     return WASM_SYMBOL_VISIBILITY_HIDDEN;
445   }
446   llvm_unreachable("unknown visibility");
447 }
448 
449 static Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &ObjSym,
450                                    BitcodeFile &F) {
451   StringRef Name = Saver.save(ObjSym.getName());
452 
453   uint32_t Flags = ObjSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
454   Flags |= mapVisibility(ObjSym.getVisibility());
455 
456   if (ObjSym.isUndefined()) {
457     if (ObjSym.isExecutable())
458       return Symtab->addUndefinedFunction(Name, Name, DefaultModule, Flags, &F,
459                                           nullptr);
460     return Symtab->addUndefinedData(Name, Flags, &F);
461   }
462 
463   if (ObjSym.isExecutable())
464     return Symtab->addDefinedFunction(Name, Flags, &F, nullptr);
465   return Symtab->addDefinedData(Name, Flags, &F, nullptr, 0, 0);
466 }
467 
468 void BitcodeFile::parse() {
469   Obj = check(lto::InputFile::create(MemoryBufferRef(
470       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier()))));
471   Triple T(Obj->getTargetTriple());
472   if (T.getArch() != Triple::wasm32) {
473     error(toString(MB.getBufferIdentifier()) + ": machine type must be wasm32");
474     return;
475   }
476 
477   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
478     Symbols.push_back(createBitcodeSymbol(ObjSym, *this));
479 }
480 
481 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
482 std::string lld::toString(const wasm::InputFile *File) {
483   if (!File)
484     return "<internal>";
485 
486   if (File->ArchiveName.empty())
487     return File->getName();
488 
489   return (File->ArchiveName + "(" + File->getName() + ")").str();
490 }
491