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   case R_WASM_TABLE_INDEX_REL_SLEB: {
104     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
105     return TableEntries[Sym.Info.ElementIndex];
106   }
107   case R_WASM_MEMORY_ADDR_SLEB:
108   case R_WASM_MEMORY_ADDR_I32:
109   case R_WASM_MEMORY_ADDR_LEB:
110   case R_WASM_MEMORY_ADDR_REL_SLEB: {
111     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
112     if (Sym.isUndefined())
113       return 0;
114     const WasmSegment &Segment =
115         WasmObj->dataSegments()[Sym.Info.DataRef.Segment];
116     return Segment.Data.Offset.Value.Int32 + Sym.Info.DataRef.Offset +
117            Reloc.Addend;
118   }
119   case R_WASM_FUNCTION_OFFSET_I32:
120     if (auto *Sym = dyn_cast<DefinedFunction>(getFunctionSymbol(Reloc.Index))) {
121       return Sym->Function->getFunctionInputOffset() +
122              Sym->Function->getFunctionCodeOffset() + Reloc.Addend;
123     }
124     return 0;
125   case R_WASM_SECTION_OFFSET_I32:
126     return Reloc.Addend;
127   case R_WASM_TYPE_INDEX_LEB:
128     return Reloc.Index;
129   case R_WASM_FUNCTION_INDEX_LEB:
130   case R_WASM_GLOBAL_INDEX_LEB:
131   case R_WASM_EVENT_INDEX_LEB: {
132     const WasmSymbol &Sym = WasmObj->syms()[Reloc.Index];
133     return Sym.Info.ElementIndex;
134   }
135   default:
136     llvm_unreachable("unknown relocation type");
137   }
138 }
139 
140 // Translate from the relocation's index into the final linked output value.
141 uint32_t ObjFile::calcNewValue(const WasmRelocation &Reloc) const {
142   switch (Reloc.Type) {
143   case R_WASM_TABLE_INDEX_I32:
144   case R_WASM_TABLE_INDEX_SLEB:
145   case R_WASM_TABLE_INDEX_REL_SLEB:
146     return getFunctionSymbol(Reloc.Index)->getTableIndex();
147   case R_WASM_MEMORY_ADDR_SLEB:
148   case R_WASM_MEMORY_ADDR_I32:
149   case R_WASM_MEMORY_ADDR_LEB:
150   case R_WASM_MEMORY_ADDR_REL_SLEB:
151     if (auto *Sym = dyn_cast<DefinedData>(getDataSymbol(Reloc.Index)))
152       if (Sym->isLive())
153         return Sym->getVirtualAddress() + Reloc.Addend;
154     return 0;
155   case R_WASM_TYPE_INDEX_LEB:
156     return TypeMap[Reloc.Index];
157   case R_WASM_FUNCTION_INDEX_LEB:
158     return getFunctionSymbol(Reloc.Index)->getFunctionIndex();
159   case R_WASM_GLOBAL_INDEX_LEB: {
160     const Symbol* Sym = Symbols[Reloc.Index];
161     if (auto GS = dyn_cast<GlobalSymbol>(Sym))
162       return GS->getGlobalIndex();
163     return Sym->getGOTIndex();
164   } case R_WASM_EVENT_INDEX_LEB:
165     return getEventSymbol(Reloc.Index)->getEventIndex();
166   case R_WASM_FUNCTION_OFFSET_I32:
167     if (auto *Sym = dyn_cast<DefinedFunction>(getFunctionSymbol(Reloc.Index))) {
168       if (Sym->isLive())
169         return Sym->Function->OutputOffset +
170                Sym->Function->getFunctionCodeOffset() + Reloc.Addend;
171     }
172     return 0;
173   case R_WASM_SECTION_OFFSET_I32:
174     return getSectionSymbol(Reloc.Index)->Section->OutputOffset + Reloc.Addend;
175   default:
176     llvm_unreachable("unknown relocation type");
177   }
178 }
179 
180 template <class T>
181 static void setRelocs(const std::vector<T *> &Chunks,
182                       const WasmSection *Section) {
183   if (!Section)
184     return;
185 
186   ArrayRef<WasmRelocation> Relocs = Section->Relocations;
187   assert(std::is_sorted(Relocs.begin(), Relocs.end(),
188                         [](const WasmRelocation &R1, const WasmRelocation &R2) {
189                           return R1.Offset < R2.Offset;
190                         }));
191   assert(std::is_sorted(
192       Chunks.begin(), Chunks.end(), [](InputChunk *C1, InputChunk *C2) {
193         return C1->getInputSectionOffset() < C2->getInputSectionOffset();
194       }));
195 
196   auto RelocsNext = Relocs.begin();
197   auto RelocsEnd = Relocs.end();
198   auto RelocLess = [](const WasmRelocation &R, uint32_t Val) {
199     return R.Offset < Val;
200   };
201   for (InputChunk *C : Chunks) {
202     auto RelocsStart = std::lower_bound(RelocsNext, RelocsEnd,
203                                         C->getInputSectionOffset(), RelocLess);
204     RelocsNext = std::lower_bound(
205         RelocsStart, RelocsEnd, C->getInputSectionOffset() + C->getInputSize(),
206         RelocLess);
207     C->setRelocations(ArrayRef<WasmRelocation>(RelocsStart, RelocsNext));
208   }
209 }
210 
211 void ObjFile::parse() {
212   // Parse a memory buffer as a wasm file.
213   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
214   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), toString(this));
215 
216   auto *Obj = dyn_cast<WasmObjectFile>(Bin.get());
217   if (!Obj)
218     fatal(toString(this) + ": not a wasm file");
219   if (!Obj->isRelocatableObject())
220     fatal(toString(this) + ": not a relocatable wasm file");
221 
222   Bin.release();
223   WasmObj.reset(Obj);
224 
225   // Build up a map of function indices to table indices for use when
226   // verifying the existing table index relocations
227   uint32_t TotalFunctions =
228       WasmObj->getNumImportedFunctions() + WasmObj->functions().size();
229   TableEntries.resize(TotalFunctions);
230   for (const WasmElemSegment &Seg : WasmObj->elements()) {
231     if (Seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
232       fatal(toString(this) + ": invalid table elements");
233     uint32_t Offset = Seg.Offset.Value.Int32;
234     for (uint32_t Index = 0; Index < Seg.Functions.size(); Index++) {
235 
236       uint32_t FunctionIndex = Seg.Functions[Index];
237       TableEntries[FunctionIndex] = Offset + Index;
238     }
239   }
240 
241   // Find the code and data sections.  Wasm objects can have at most one code
242   // and one data section.
243   uint32_t SectionIndex = 0;
244   for (const SectionRef &Sec : WasmObj->sections()) {
245     const WasmSection &Section = WasmObj->getWasmSection(Sec);
246     if (Section.Type == WASM_SEC_CODE) {
247       CodeSection = &Section;
248     } else if (Section.Type == WASM_SEC_DATA) {
249       DataSection = &Section;
250     } else if (Section.Type == WASM_SEC_CUSTOM) {
251       CustomSections.emplace_back(make<InputSection>(Section, this));
252       CustomSections.back()->setRelocations(Section.Relocations);
253       CustomSectionsByIndex[SectionIndex] = CustomSections.back();
254     }
255     SectionIndex++;
256   }
257 
258   TypeMap.resize(getWasmObj()->types().size());
259   TypeIsUsed.resize(getWasmObj()->types().size(), false);
260 
261   ArrayRef<StringRef> Comdats = WasmObj->linkingData().Comdats;
262   UsedComdats.resize(Comdats.size());
263   for (unsigned I = 0; I < Comdats.size(); ++I)
264     UsedComdats[I] = Symtab->addComdat(Comdats[I]);
265 
266   // Populate `Segments`.
267   for (const WasmSegment &S : WasmObj->dataSegments())
268     Segments.emplace_back(make<InputSegment>(S, this));
269   setRelocs(Segments, DataSection);
270 
271   // Populate `Functions`.
272   ArrayRef<WasmFunction> Funcs = WasmObj->functions();
273   ArrayRef<uint32_t> FuncTypes = WasmObj->functionTypes();
274   ArrayRef<WasmSignature> Types = WasmObj->types();
275   Functions.reserve(Funcs.size());
276 
277   for (size_t I = 0, E = Funcs.size(); I != E; ++I)
278     Functions.emplace_back(
279         make<InputFunction>(Types[FuncTypes[I]], &Funcs[I], this));
280   setRelocs(Functions, CodeSection);
281 
282   // Populate `Globals`.
283   for (const WasmGlobal &G : WasmObj->globals())
284     Globals.emplace_back(make<InputGlobal>(G, this));
285 
286   // Populate `Events`.
287   for (const WasmEvent &E : WasmObj->events())
288     Events.emplace_back(make<InputEvent>(Types[E.Type.SigIndex], E, this));
289 
290   // Populate `Symbols` based on the WasmSymbols in the object.
291   Symbols.reserve(WasmObj->getNumberOfSymbols());
292   for (const SymbolRef &Sym : WasmObj->symbols()) {
293     const WasmSymbol &WasmSym = WasmObj->getWasmSymbol(Sym.getRawDataRefImpl());
294     if (Symbol *Sym = createDefined(WasmSym))
295       Symbols.push_back(Sym);
296     else
297       Symbols.push_back(createUndefined(WasmSym));
298   }
299 }
300 
301 bool ObjFile::isExcludedByComdat(InputChunk *Chunk) const {
302   uint32_t C = Chunk->getComdat();
303   if (C == UINT32_MAX)
304     return false;
305   return !UsedComdats[C];
306 }
307 
308 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t Index) const {
309   return cast<FunctionSymbol>(Symbols[Index]);
310 }
311 
312 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t Index) const {
313   return cast<GlobalSymbol>(Symbols[Index]);
314 }
315 
316 EventSymbol *ObjFile::getEventSymbol(uint32_t Index) const {
317   return cast<EventSymbol>(Symbols[Index]);
318 }
319 
320 SectionSymbol *ObjFile::getSectionSymbol(uint32_t Index) const {
321   return cast<SectionSymbol>(Symbols[Index]);
322 }
323 
324 DataSymbol *ObjFile::getDataSymbol(uint32_t Index) const {
325   return cast<DataSymbol>(Symbols[Index]);
326 }
327 
328 Symbol *ObjFile::createDefined(const WasmSymbol &Sym) {
329   if (!Sym.isDefined())
330     return nullptr;
331 
332   StringRef Name = Sym.Info.Name;
333   uint32_t Flags = Sym.Info.Flags;
334 
335   switch (Sym.Info.Kind) {
336   case WASM_SYMBOL_TYPE_FUNCTION: {
337     InputFunction *Func =
338         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
339     if (isExcludedByComdat(Func)) {
340       Func->Live = false;
341       return nullptr;
342     }
343 
344     if (Sym.isBindingLocal())
345       return make<DefinedFunction>(Name, Flags, this, Func);
346     return Symtab->addDefinedFunction(Name, Flags, this, Func);
347   }
348   case WASM_SYMBOL_TYPE_DATA: {
349     InputSegment *Seg = Segments[Sym.Info.DataRef.Segment];
350     if (isExcludedByComdat(Seg)) {
351       Seg->Live = false;
352       return nullptr;
353     }
354 
355     uint32_t Offset = Sym.Info.DataRef.Offset;
356     uint32_t Size = Sym.Info.DataRef.Size;
357 
358     if (Sym.isBindingLocal())
359       return make<DefinedData>(Name, Flags, this, Seg, Offset, Size);
360     return Symtab->addDefinedData(Name, Flags, this, Seg, Offset, Size);
361   }
362   case WASM_SYMBOL_TYPE_GLOBAL: {
363     InputGlobal *Global =
364         Globals[Sym.Info.ElementIndex - WasmObj->getNumImportedGlobals()];
365     if (Sym.isBindingLocal())
366       return make<DefinedGlobal>(Name, Flags, this, Global);
367     return Symtab->addDefinedGlobal(Name, Flags, this, Global);
368   }
369   case WASM_SYMBOL_TYPE_SECTION: {
370     InputSection *Section = CustomSectionsByIndex[Sym.Info.ElementIndex];
371     assert(Sym.isBindingLocal());
372     return make<SectionSymbol>(Name, Flags, Section, this);
373   }
374   case WASM_SYMBOL_TYPE_EVENT: {
375     InputEvent *Event =
376         Events[Sym.Info.ElementIndex - WasmObj->getNumImportedEvents()];
377     if (Sym.isBindingLocal())
378       return make<DefinedEvent>(Name, Flags, this, Event);
379     return Symtab->addDefinedEvent(Name, Flags, this, Event);
380   }
381   }
382   llvm_unreachable("unknown symbol kind");
383 }
384 
385 Symbol *ObjFile::createUndefined(const WasmSymbol &Sym) {
386   StringRef Name = Sym.Info.Name;
387   uint32_t Flags = Sym.Info.Flags;
388 
389   switch (Sym.Info.Kind) {
390   case WASM_SYMBOL_TYPE_FUNCTION:
391     return Symtab->addUndefinedFunction(Name, Sym.Info.ImportName,
392                                         Sym.Info.ImportModule, Flags, this,
393                                         Sym.Signature);
394   case WASM_SYMBOL_TYPE_DATA:
395     return Symtab->addUndefinedData(Name, Flags, this);
396   case WASM_SYMBOL_TYPE_GLOBAL:
397     return Symtab->addUndefinedGlobal(Name, Sym.Info.ImportName,
398                                       Sym.Info.ImportModule, Flags, this,
399                                       Sym.GlobalType);
400   case WASM_SYMBOL_TYPE_SECTION:
401     llvm_unreachable("section symbols cannot be undefined");
402   }
403   llvm_unreachable("unknown symbol kind");
404 }
405 
406 void ArchiveFile::parse() {
407   // Parse a MemoryBufferRef as an archive file.
408   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
409   File = CHECK(Archive::create(MB), toString(this));
410 
411   // Read the symbol table to construct Lazy symbols.
412   int Count = 0;
413   for (const Archive::Symbol &Sym : File->symbols()) {
414     Symtab->addLazy(this, &Sym);
415     ++Count;
416   }
417   LLVM_DEBUG(dbgs() << "Read " << Count << " symbols\n");
418 }
419 
420 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
421   const Archive::Child &C =
422       CHECK(Sym->getMember(),
423             "could not get the member for symbol " + Sym->getName());
424 
425   // Don't try to load the same member twice (this can happen when members
426   // mutually reference each other).
427   if (!Seen.insert(C.getChildOffset()).second)
428     return;
429 
430   LLVM_DEBUG(dbgs() << "loading lazy: " << Sym->getName() << "\n");
431   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
432 
433   MemoryBufferRef MB =
434       CHECK(C.getMemoryBufferRef(),
435             "could not get the buffer for the member defining symbol " +
436                 Sym->getName());
437 
438   InputFile *Obj = createObjectFile(MB);
439   Obj->ArchiveName = 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