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