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       // R_WASM_MEMORY_ADDR_I32 relocations in PIC code are turned into runtime
159       // fixups in __wasm_apply_relocs
160       if (Config->Pic && Reloc.Type == R_WASM_MEMORY_ADDR_I32)
161         return 0;
162       if (Reloc.Type != R_WASM_GLOBAL_INDEX_LEB) {
163         llvm_unreachable(
164           ("invalid relocation against undefined data symbol: " + toString(*Sym))
165               .c_str());
166       }
167     }
168   }
169 
170   switch (Reloc.Type) {
171   case R_WASM_TABLE_INDEX_I32:
172   case R_WASM_TABLE_INDEX_SLEB:
173   case R_WASM_TABLE_INDEX_REL_SLEB:
174     return getFunctionSymbol(Reloc.Index)->getTableIndex();
175   case R_WASM_MEMORY_ADDR_SLEB:
176   case R_WASM_MEMORY_ADDR_I32:
177   case R_WASM_MEMORY_ADDR_LEB:
178   case R_WASM_MEMORY_ADDR_REL_SLEB:
179     return cast<DefinedData>(Sym)->getVirtualAddress() + Reloc.Addend;
180   case R_WASM_TYPE_INDEX_LEB:
181     return TypeMap[Reloc.Index];
182   case R_WASM_FUNCTION_INDEX_LEB:
183     return getFunctionSymbol(Reloc.Index)->getFunctionIndex();
184   case R_WASM_GLOBAL_INDEX_LEB:
185     if (auto GS = dyn_cast<GlobalSymbol>(Sym))
186       return GS->getGlobalIndex();
187     return Sym->getGOTIndex();
188   case R_WASM_EVENT_INDEX_LEB:
189     return getEventSymbol(Reloc.Index)->getEventIndex();
190   case R_WASM_FUNCTION_OFFSET_I32: {
191     auto *F = cast<DefinedFunction>(Sym);
192     return F->Function->OutputOffset + F->Function->getFunctionCodeOffset() +
193            Reloc.Addend;
194   }
195   case R_WASM_SECTION_OFFSET_I32:
196     return getSectionSymbol(Reloc.Index)->Section->OutputOffset + Reloc.Addend;
197   default:
198     llvm_unreachable("unknown relocation type");
199   }
200 }
201 
202 template <class T>
203 static void setRelocs(const std::vector<T *> &Chunks,
204                       const WasmSection *Section) {
205   if (!Section)
206     return;
207 
208   ArrayRef<WasmRelocation> Relocs = Section->Relocations;
209   assert(std::is_sorted(Relocs.begin(), Relocs.end(),
210                         [](const WasmRelocation &R1, const WasmRelocation &R2) {
211                           return R1.Offset < R2.Offset;
212                         }));
213   assert(std::is_sorted(
214       Chunks.begin(), Chunks.end(), [](InputChunk *C1, InputChunk *C2) {
215         return C1->getInputSectionOffset() < C2->getInputSectionOffset();
216       }));
217 
218   auto RelocsNext = Relocs.begin();
219   auto RelocsEnd = Relocs.end();
220   auto RelocLess = [](const WasmRelocation &R, uint32_t Val) {
221     return R.Offset < Val;
222   };
223   for (InputChunk *C : Chunks) {
224     auto RelocsStart = std::lower_bound(RelocsNext, RelocsEnd,
225                                         C->getInputSectionOffset(), RelocLess);
226     RelocsNext = std::lower_bound(
227         RelocsStart, RelocsEnd, C->getInputSectionOffset() + C->getInputSize(),
228         RelocLess);
229     C->setRelocations(ArrayRef<WasmRelocation>(RelocsStart, RelocsNext));
230   }
231 }
232 
233 void ObjFile::parse() {
234   // Parse a memory buffer as a wasm file.
235   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
236   std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), toString(this));
237 
238   auto *Obj = dyn_cast<WasmObjectFile>(Bin.get());
239   if (!Obj)
240     fatal(toString(this) + ": not a wasm file");
241   if (!Obj->isRelocatableObject())
242     fatal(toString(this) + ": not a relocatable wasm file");
243 
244   Bin.release();
245   WasmObj.reset(Obj);
246 
247   // Build up a map of function indices to table indices for use when
248   // verifying the existing table index relocations
249   uint32_t TotalFunctions =
250       WasmObj->getNumImportedFunctions() + WasmObj->functions().size();
251   TableEntries.resize(TotalFunctions);
252   for (const WasmElemSegment &Seg : WasmObj->elements()) {
253     if (Seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
254       fatal(toString(this) + ": invalid table elements");
255     uint32_t Offset = Seg.Offset.Value.Int32;
256     for (uint32_t Index = 0; Index < Seg.Functions.size(); Index++) {
257 
258       uint32_t FunctionIndex = Seg.Functions[Index];
259       TableEntries[FunctionIndex] = Offset + Index;
260     }
261   }
262 
263   // Find the code and data sections.  Wasm objects can have at most one code
264   // and one data section.
265   uint32_t SectionIndex = 0;
266   for (const SectionRef &Sec : WasmObj->sections()) {
267     const WasmSection &Section = WasmObj->getWasmSection(Sec);
268     if (Section.Type == WASM_SEC_CODE) {
269       CodeSection = &Section;
270     } else if (Section.Type == WASM_SEC_DATA) {
271       DataSection = &Section;
272     } else if (Section.Type == WASM_SEC_CUSTOM) {
273       CustomSections.emplace_back(make<InputSection>(Section, this));
274       CustomSections.back()->setRelocations(Section.Relocations);
275       CustomSectionsByIndex[SectionIndex] = CustomSections.back();
276     }
277     SectionIndex++;
278   }
279 
280   TypeMap.resize(getWasmObj()->types().size());
281   TypeIsUsed.resize(getWasmObj()->types().size(), false);
282 
283   ArrayRef<StringRef> Comdats = WasmObj->linkingData().Comdats;
284   UsedComdats.resize(Comdats.size());
285   for (unsigned I = 0; I < Comdats.size(); ++I)
286     UsedComdats[I] = Symtab->addComdat(Comdats[I]);
287 
288   // Populate `Segments`.
289   for (const WasmSegment &S : WasmObj->dataSegments())
290     Segments.emplace_back(make<InputSegment>(S, this));
291   setRelocs(Segments, DataSection);
292 
293   // Populate `Functions`.
294   ArrayRef<WasmFunction> Funcs = WasmObj->functions();
295   ArrayRef<uint32_t> FuncTypes = WasmObj->functionTypes();
296   ArrayRef<WasmSignature> Types = WasmObj->types();
297   Functions.reserve(Funcs.size());
298 
299   for (size_t I = 0, E = Funcs.size(); I != E; ++I)
300     Functions.emplace_back(
301         make<InputFunction>(Types[FuncTypes[I]], &Funcs[I], this));
302   setRelocs(Functions, CodeSection);
303 
304   // Populate `Globals`.
305   for (const WasmGlobal &G : WasmObj->globals())
306     Globals.emplace_back(make<InputGlobal>(G, this));
307 
308   // Populate `Events`.
309   for (const WasmEvent &E : WasmObj->events())
310     Events.emplace_back(make<InputEvent>(Types[E.Type.SigIndex], E, this));
311 
312   // Populate `Symbols` based on the WasmSymbols in the object.
313   Symbols.reserve(WasmObj->getNumberOfSymbols());
314   for (const SymbolRef &Sym : WasmObj->symbols()) {
315     const WasmSymbol &WasmSym = WasmObj->getWasmSymbol(Sym.getRawDataRefImpl());
316     if (Symbol *Sym = createDefined(WasmSym))
317       Symbols.push_back(Sym);
318     else
319       Symbols.push_back(createUndefined(WasmSym));
320   }
321 }
322 
323 bool ObjFile::isExcludedByComdat(InputChunk *Chunk) const {
324   uint32_t C = Chunk->getComdat();
325   if (C == UINT32_MAX)
326     return false;
327   return !UsedComdats[C];
328 }
329 
330 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t Index) const {
331   return cast<FunctionSymbol>(Symbols[Index]);
332 }
333 
334 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t Index) const {
335   return cast<GlobalSymbol>(Symbols[Index]);
336 }
337 
338 EventSymbol *ObjFile::getEventSymbol(uint32_t Index) const {
339   return cast<EventSymbol>(Symbols[Index]);
340 }
341 
342 SectionSymbol *ObjFile::getSectionSymbol(uint32_t Index) const {
343   return cast<SectionSymbol>(Symbols[Index]);
344 }
345 
346 DataSymbol *ObjFile::getDataSymbol(uint32_t Index) const {
347   return cast<DataSymbol>(Symbols[Index]);
348 }
349 
350 Symbol *ObjFile::createDefined(const WasmSymbol &Sym) {
351   if (!Sym.isDefined())
352     return nullptr;
353 
354   StringRef Name = Sym.Info.Name;
355   uint32_t Flags = Sym.Info.Flags;
356 
357   switch (Sym.Info.Kind) {
358   case WASM_SYMBOL_TYPE_FUNCTION: {
359     InputFunction *Func =
360         Functions[Sym.Info.ElementIndex - WasmObj->getNumImportedFunctions()];
361     if (isExcludedByComdat(Func)) {
362       Func->Live = false;
363       return nullptr;
364     }
365 
366     if (Sym.isBindingLocal())
367       return make<DefinedFunction>(Name, Flags, this, Func);
368     return Symtab->addDefinedFunction(Name, Flags, this, Func);
369   }
370   case WASM_SYMBOL_TYPE_DATA: {
371     InputSegment *Seg = Segments[Sym.Info.DataRef.Segment];
372     if (isExcludedByComdat(Seg)) {
373       Seg->Live = false;
374       return nullptr;
375     }
376 
377     uint32_t Offset = Sym.Info.DataRef.Offset;
378     uint32_t Size = Sym.Info.DataRef.Size;
379 
380     if (Sym.isBindingLocal())
381       return make<DefinedData>(Name, Flags, this, Seg, Offset, Size);
382     return Symtab->addDefinedData(Name, Flags, this, Seg, Offset, Size);
383   }
384   case WASM_SYMBOL_TYPE_GLOBAL: {
385     InputGlobal *Global =
386         Globals[Sym.Info.ElementIndex - WasmObj->getNumImportedGlobals()];
387     if (Sym.isBindingLocal())
388       return make<DefinedGlobal>(Name, Flags, this, Global);
389     return Symtab->addDefinedGlobal(Name, Flags, this, Global);
390   }
391   case WASM_SYMBOL_TYPE_SECTION: {
392     InputSection *Section = CustomSectionsByIndex[Sym.Info.ElementIndex];
393     assert(Sym.isBindingLocal());
394     return make<SectionSymbol>(Name, Flags, Section, this);
395   }
396   case WASM_SYMBOL_TYPE_EVENT: {
397     InputEvent *Event =
398         Events[Sym.Info.ElementIndex - WasmObj->getNumImportedEvents()];
399     if (Sym.isBindingLocal())
400       return make<DefinedEvent>(Name, Flags, this, Event);
401     return Symtab->addDefinedEvent(Name, Flags, this, Event);
402   }
403   }
404   llvm_unreachable("unknown symbol kind");
405 }
406 
407 Symbol *ObjFile::createUndefined(const WasmSymbol &Sym) {
408   StringRef Name = Sym.Info.Name;
409   uint32_t Flags = Sym.Info.Flags;
410 
411   switch (Sym.Info.Kind) {
412   case WASM_SYMBOL_TYPE_FUNCTION:
413     return Symtab->addUndefinedFunction(Name, Sym.Info.ImportName,
414                                         Sym.Info.ImportModule, Flags, this,
415                                         Sym.Signature);
416   case WASM_SYMBOL_TYPE_DATA:
417     return Symtab->addUndefinedData(Name, Flags, this);
418   case WASM_SYMBOL_TYPE_GLOBAL:
419     return Symtab->addUndefinedGlobal(Name, Sym.Info.ImportName,
420                                       Sym.Info.ImportModule, Flags, this,
421                                       Sym.GlobalType);
422   case WASM_SYMBOL_TYPE_SECTION:
423     llvm_unreachable("section symbols cannot be undefined");
424   }
425   llvm_unreachable("unknown symbol kind");
426 }
427 
428 void ArchiveFile::parse() {
429   // Parse a MemoryBufferRef as an archive file.
430   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
431   File = CHECK(Archive::create(MB), toString(this));
432 
433   // Read the symbol table to construct Lazy symbols.
434   int Count = 0;
435   for (const Archive::Symbol &Sym : File->symbols()) {
436     Symtab->addLazy(this, &Sym);
437     ++Count;
438   }
439   LLVM_DEBUG(dbgs() << "Read " << Count << " symbols\n");
440 }
441 
442 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
443   const Archive::Child &C =
444       CHECK(Sym->getMember(),
445             "could not get the member for symbol " + Sym->getName());
446 
447   // Don't try to load the same member twice (this can happen when members
448   // mutually reference each other).
449   if (!Seen.insert(C.getChildOffset()).second)
450     return;
451 
452   LLVM_DEBUG(dbgs() << "loading lazy: " << Sym->getName() << "\n");
453   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
454 
455   MemoryBufferRef MB =
456       CHECK(C.getMemoryBufferRef(),
457             "could not get the buffer for the member defining symbol " +
458                 Sym->getName());
459 
460   InputFile *Obj = createObjectFile(MB, getName());
461   Symtab->addFile(Obj);
462 }
463 
464 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
465   switch (GvVisibility) {
466   case GlobalValue::DefaultVisibility:
467     return WASM_SYMBOL_VISIBILITY_DEFAULT;
468   case GlobalValue::HiddenVisibility:
469   case GlobalValue::ProtectedVisibility:
470     return WASM_SYMBOL_VISIBILITY_HIDDEN;
471   }
472   llvm_unreachable("unknown visibility");
473 }
474 
475 static Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &ObjSym,
476                                    BitcodeFile &F) {
477   StringRef Name = Saver.save(ObjSym.getName());
478 
479   uint32_t Flags = ObjSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
480   Flags |= mapVisibility(ObjSym.getVisibility());
481 
482   if (ObjSym.isUndefined()) {
483     if (ObjSym.isExecutable())
484       return Symtab->addUndefinedFunction(Name, Name, DefaultModule, Flags, &F,
485                                           nullptr);
486     return Symtab->addUndefinedData(Name, Flags, &F);
487   }
488 
489   if (ObjSym.isExecutable())
490     return Symtab->addDefinedFunction(Name, Flags, &F, nullptr);
491   return Symtab->addDefinedData(Name, Flags, &F, nullptr, 0, 0);
492 }
493 
494 void BitcodeFile::parse() {
495   Obj = check(lto::InputFile::create(MemoryBufferRef(
496       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier()))));
497   Triple T(Obj->getTargetTriple());
498   if (T.getArch() != Triple::wasm32) {
499     error(toString(MB.getBufferIdentifier()) + ": machine type must be wasm32");
500     return;
501   }
502 
503   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
504     Symbols.push_back(createBitcodeSymbol(ObjSym, *this));
505 }
506 
507 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
508 std::string lld::toString(const wasm::InputFile *File) {
509   if (!File)
510     return "<internal>";
511 
512   if (File->ArchiveName.empty())
513     return File->getName();
514 
515   return (File->ArchiveName + "(" + File->getName() + ")").str();
516 }
517