xref: /openbsd-src/gnu/llvm/lld/wasm/InputFiles.cpp (revision fcde59b201a29a2b4570b00b71e7aa25d61cb5c1)
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 "lld/Common/Reproduce.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/Object/Wasm.h"
20 #include "llvm/Support/TarWriter.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 #define DEBUG_TYPE "lld"
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace llvm::wasm;
28 
29 namespace lld {
30 
31 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
32 std::string toString(const wasm::InputFile *file) {
33   if (!file)
34     return "<internal>";
35 
36   if (file->archiveName.empty())
37     return file->getName();
38 
39   return (file->archiveName + "(" + file->getName() + ")").str();
40 }
41 
42 namespace wasm {
43 std::unique_ptr<llvm::TarWriter> tar;
44 
45 Optional<MemoryBufferRef> readFile(StringRef path) {
46   log("Loading: " + path);
47 
48   auto mbOrErr = MemoryBuffer::getFile(path);
49   if (auto ec = mbOrErr.getError()) {
50     error("cannot open " + path + ": " + ec.message());
51     return None;
52   }
53   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
54   MemoryBufferRef mbref = mb->getMemBufferRef();
55   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
56 
57   if (tar)
58     tar->append(relativeToRoot(path), mbref.getBuffer());
59   return mbref;
60 }
61 
62 InputFile *createObjectFile(MemoryBufferRef mb,
63                                        StringRef archiveName) {
64   file_magic magic = identify_magic(mb.getBuffer());
65   if (magic == file_magic::wasm_object) {
66     std::unique_ptr<Binary> bin =
67         CHECK(createBinary(mb), mb.getBufferIdentifier());
68     auto *obj = cast<WasmObjectFile>(bin.get());
69     if (obj->isSharedObject())
70       return make<SharedFile>(mb);
71     return make<ObjFile>(mb, archiveName);
72   }
73 
74   if (magic == file_magic::bitcode)
75     return make<BitcodeFile>(mb, archiveName);
76 
77   fatal("unknown file type: " + mb.getBufferIdentifier());
78 }
79 
80 void ObjFile::dumpInfo() const {
81   log("info for: " + toString(this) +
82       "\n              Symbols : " + Twine(symbols.size()) +
83       "\n     Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) +
84       "\n       Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) +
85       "\n        Event Imports : " + Twine(wasmObj->getNumImportedEvents()));
86 }
87 
88 // Relocations contain either symbol or type indices.  This function takes a
89 // relocation and returns relocated index (i.e. translates from the input
90 // symbol/type space to the output symbol/type space).
91 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
92   if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
93     assert(typeIsUsed[reloc.Index]);
94     return typeMap[reloc.Index];
95   }
96   const Symbol *sym = symbols[reloc.Index];
97   if (auto *ss = dyn_cast<SectionSymbol>(sym))
98     sym = ss->getOutputSectionSymbol();
99   return sym->getOutputSymbolIndex();
100 }
101 
102 // Relocations can contain addend for combined sections. This function takes a
103 // relocation and returns updated addend by offset in the output section.
104 uint32_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
105   switch (reloc.Type) {
106   case R_WASM_MEMORY_ADDR_LEB:
107   case R_WASM_MEMORY_ADDR_SLEB:
108   case R_WASM_MEMORY_ADDR_REL_SLEB:
109   case R_WASM_MEMORY_ADDR_I32:
110   case R_WASM_FUNCTION_OFFSET_I32:
111     return reloc.Addend;
112   case R_WASM_SECTION_OFFSET_I32:
113     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
114   default:
115     llvm_unreachable("unexpected relocation type");
116   }
117 }
118 
119 // Calculate the value we expect to find at the relocation location.
120 // This is used as a sanity check before applying a relocation to a given
121 // location.  It is useful for catching bugs in the compiler and linker.
122 uint32_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const {
123   switch (reloc.Type) {
124   case R_WASM_TABLE_INDEX_I32:
125   case R_WASM_TABLE_INDEX_SLEB:
126   case R_WASM_TABLE_INDEX_REL_SLEB: {
127     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
128     return tableEntries[sym.Info.ElementIndex];
129   }
130   case R_WASM_MEMORY_ADDR_SLEB:
131   case R_WASM_MEMORY_ADDR_I32:
132   case R_WASM_MEMORY_ADDR_LEB:
133   case R_WASM_MEMORY_ADDR_REL_SLEB: {
134     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
135     if (sym.isUndefined())
136       return 0;
137     const WasmSegment &segment =
138         wasmObj->dataSegments()[sym.Info.DataRef.Segment];
139     return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset +
140            reloc.Addend;
141   }
142   case R_WASM_FUNCTION_OFFSET_I32: {
143     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
144     InputFunction *f =
145         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
146     return f->getFunctionInputOffset() + f->getFunctionCodeOffset() +
147            reloc.Addend;
148   }
149   case R_WASM_SECTION_OFFSET_I32:
150     return reloc.Addend;
151   case R_WASM_TYPE_INDEX_LEB:
152     return reloc.Index;
153   case R_WASM_FUNCTION_INDEX_LEB:
154   case R_WASM_GLOBAL_INDEX_LEB:
155   case R_WASM_EVENT_INDEX_LEB: {
156     const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
157     return sym.Info.ElementIndex;
158   }
159   default:
160     llvm_unreachable("unknown relocation type");
161   }
162 }
163 
164 // Translate from the relocation's index into the final linked output value.
165 uint32_t ObjFile::calcNewValue(const WasmRelocation &reloc) const {
166   const Symbol* sym = nullptr;
167   if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
168     sym = symbols[reloc.Index];
169 
170     // We can end up with relocations against non-live symbols.  For example
171     // in debug sections.
172     if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive())
173       return 0;
174   }
175 
176   switch (reloc.Type) {
177   case R_WASM_TABLE_INDEX_I32:
178   case R_WASM_TABLE_INDEX_SLEB:
179   case R_WASM_TABLE_INDEX_REL_SLEB: {
180     if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
181       return 0;
182     uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
183     if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB)
184       index -= config->tableBase;
185     return index;
186 
187   }
188   case R_WASM_MEMORY_ADDR_SLEB:
189   case R_WASM_MEMORY_ADDR_I32:
190   case R_WASM_MEMORY_ADDR_LEB:
191   case R_WASM_MEMORY_ADDR_REL_SLEB:
192     if (isa<UndefinedData>(sym) || sym->isUndefWeak())
193       return 0;
194     return cast<DefinedData>(sym)->getVirtualAddress() + reloc.Addend;
195   case R_WASM_TYPE_INDEX_LEB:
196     return typeMap[reloc.Index];
197   case R_WASM_FUNCTION_INDEX_LEB:
198     return getFunctionSymbol(reloc.Index)->getFunctionIndex();
199   case R_WASM_GLOBAL_INDEX_LEB:
200     if (auto gs = dyn_cast<GlobalSymbol>(sym))
201       return gs->getGlobalIndex();
202     return sym->getGOTIndex();
203   case R_WASM_EVENT_INDEX_LEB:
204     return getEventSymbol(reloc.Index)->getEventIndex();
205   case R_WASM_FUNCTION_OFFSET_I32: {
206     auto *f = cast<DefinedFunction>(sym);
207     return f->function->outputOffset + f->function->getFunctionCodeOffset() +
208            reloc.Addend;
209   }
210   case R_WASM_SECTION_OFFSET_I32:
211     return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
212   default:
213     llvm_unreachable("unknown relocation type");
214   }
215 }
216 
217 template <class T>
218 static void setRelocs(const std::vector<T *> &chunks,
219                       const WasmSection *section) {
220   if (!section)
221     return;
222 
223   ArrayRef<WasmRelocation> relocs = section->Relocations;
224   assert(std::is_sorted(relocs.begin(), relocs.end(),
225                         [](const WasmRelocation &r1, const WasmRelocation &r2) {
226                           return r1.Offset < r2.Offset;
227                         }));
228   assert(std::is_sorted(
229       chunks.begin(), chunks.end(), [](InputChunk *c1, InputChunk *c2) {
230         return c1->getInputSectionOffset() < c2->getInputSectionOffset();
231       }));
232 
233   auto relocsNext = relocs.begin();
234   auto relocsEnd = relocs.end();
235   auto relocLess = [](const WasmRelocation &r, uint32_t val) {
236     return r.Offset < val;
237   };
238   for (InputChunk *c : chunks) {
239     auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
240                                         c->getInputSectionOffset(), relocLess);
241     relocsNext = std::lower_bound(
242         relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
243         relocLess);
244     c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
245   }
246 }
247 
248 void ObjFile::parse(bool ignoreComdats) {
249   // Parse a memory buffer as a wasm file.
250   LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
251   std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
252 
253   auto *obj = dyn_cast<WasmObjectFile>(bin.get());
254   if (!obj)
255     fatal(toString(this) + ": not a wasm file");
256   if (!obj->isRelocatableObject())
257     fatal(toString(this) + ": not a relocatable wasm file");
258 
259   bin.release();
260   wasmObj.reset(obj);
261 
262   // Build up a map of function indices to table indices for use when
263   // verifying the existing table index relocations
264   uint32_t totalFunctions =
265       wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
266   tableEntries.resize(totalFunctions);
267   for (const WasmElemSegment &seg : wasmObj->elements()) {
268     if (seg.Offset.Opcode != WASM_OPCODE_I32_CONST)
269       fatal(toString(this) + ": invalid table elements");
270     uint32_t offset = seg.Offset.Value.Int32;
271     for (uint32_t index = 0; index < seg.Functions.size(); index++) {
272 
273       uint32_t functionIndex = seg.Functions[index];
274       tableEntries[functionIndex] = offset + index;
275     }
276   }
277 
278   uint32_t sectionIndex = 0;
279 
280   // Bool for each symbol, true if called directly.  This allows us to implement
281   // a weaker form of signature checking where undefined functions that are not
282   // called directly (i.e. only address taken) don't have to match the defined
283   // function's signature.  We cannot do this for directly called functions
284   // because those signatures are checked at validation times.
285   // See https://bugs.llvm.org/show_bug.cgi?id=40412
286   std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
287   for (const SectionRef &sec : wasmObj->sections()) {
288     const WasmSection &section = wasmObj->getWasmSection(sec);
289     // Wasm objects can have at most one code and one data section.
290     if (section.Type == WASM_SEC_CODE) {
291       assert(!codeSection);
292       codeSection = &section;
293     } else if (section.Type == WASM_SEC_DATA) {
294       assert(!dataSection);
295       dataSection = &section;
296     } else if (section.Type == WASM_SEC_CUSTOM) {
297       customSections.emplace_back(make<InputSection>(section, this));
298       customSections.back()->setRelocations(section.Relocations);
299       customSectionsByIndex[sectionIndex] = customSections.back();
300     }
301     sectionIndex++;
302     // Scans relocations to determine if a function symbol is called directly.
303     for (const WasmRelocation &reloc : section.Relocations)
304       if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
305         isCalledDirectly[reloc.Index] = true;
306   }
307 
308   typeMap.resize(getWasmObj()->types().size());
309   typeIsUsed.resize(getWasmObj()->types().size(), false);
310 
311   ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
312   for (StringRef comdat : comdats) {
313     bool isNew = ignoreComdats || symtab->addComdat(comdat);
314     keptComdats.push_back(isNew);
315   }
316 
317   // Populate `Segments`.
318   for (const WasmSegment &s : wasmObj->dataSegments()) {
319     auto* seg = make<InputSegment>(s, this);
320     seg->discarded = isExcludedByComdat(seg);
321     segments.emplace_back(seg);
322   }
323   setRelocs(segments, dataSection);
324 
325   // Populate `Functions`.
326   ArrayRef<WasmFunction> funcs = wasmObj->functions();
327   ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes();
328   ArrayRef<WasmSignature> types = wasmObj->types();
329   functions.reserve(funcs.size());
330 
331   for (size_t i = 0, e = funcs.size(); i != e; ++i) {
332     auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this);
333     func->discarded = isExcludedByComdat(func);
334     functions.emplace_back(func);
335   }
336   setRelocs(functions, codeSection);
337 
338   // Populate `Globals`.
339   for (const WasmGlobal &g : wasmObj->globals())
340     globals.emplace_back(make<InputGlobal>(g, this));
341 
342   // Populate `Events`.
343   for (const WasmEvent &e : wasmObj->events())
344     events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this));
345 
346   // Populate `Symbols` based on the symbols in the object.
347   symbols.reserve(wasmObj->getNumberOfSymbols());
348   for (const SymbolRef &sym : wasmObj->symbols()) {
349     const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
350     if (wasmSym.isDefined()) {
351       // createDefined may fail if the symbol is comdat excluded in which case
352       // we fall back to creating an undefined symbol
353       if (Symbol *d = createDefined(wasmSym)) {
354         symbols.push_back(d);
355         continue;
356       }
357     }
358     size_t idx = symbols.size();
359     symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
360   }
361 }
362 
363 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const {
364   uint32_t c = chunk->getComdat();
365   if (c == UINT32_MAX)
366     return false;
367   return !keptComdats[c];
368 }
369 
370 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
371   return cast<FunctionSymbol>(symbols[index]);
372 }
373 
374 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
375   return cast<GlobalSymbol>(symbols[index]);
376 }
377 
378 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const {
379   return cast<EventSymbol>(symbols[index]);
380 }
381 
382 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
383   return cast<SectionSymbol>(symbols[index]);
384 }
385 
386 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
387   return cast<DataSymbol>(symbols[index]);
388 }
389 
390 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
391   StringRef name = sym.Info.Name;
392   uint32_t flags = sym.Info.Flags;
393 
394   switch (sym.Info.Kind) {
395   case WASM_SYMBOL_TYPE_FUNCTION: {
396     InputFunction *func =
397         functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
398     if (sym.isBindingLocal())
399       return make<DefinedFunction>(name, flags, this, func);
400     if (func->discarded)
401       return nullptr;
402     return symtab->addDefinedFunction(name, flags, this, func);
403   }
404   case WASM_SYMBOL_TYPE_DATA: {
405     InputSegment *seg = segments[sym.Info.DataRef.Segment];
406     uint32_t offset = sym.Info.DataRef.Offset;
407     uint32_t size = sym.Info.DataRef.Size;
408     if (sym.isBindingLocal())
409       return make<DefinedData>(name, flags, this, seg, offset, size);
410     if (seg->discarded)
411       return nullptr;
412     return symtab->addDefinedData(name, flags, this, seg, offset, size);
413   }
414   case WASM_SYMBOL_TYPE_GLOBAL: {
415     InputGlobal *global =
416         globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
417     if (sym.isBindingLocal())
418       return make<DefinedGlobal>(name, flags, this, global);
419     return symtab->addDefinedGlobal(name, flags, this, global);
420   }
421   case WASM_SYMBOL_TYPE_SECTION: {
422     InputSection *section = customSectionsByIndex[sym.Info.ElementIndex];
423     assert(sym.isBindingLocal());
424     return make<SectionSymbol>(flags, section, this);
425   }
426   case WASM_SYMBOL_TYPE_EVENT: {
427     InputEvent *event =
428         events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()];
429     if (sym.isBindingLocal())
430       return make<DefinedEvent>(name, flags, this, event);
431     return symtab->addDefinedEvent(name, flags, this, event);
432   }
433   }
434   llvm_unreachable("unknown symbol kind");
435 }
436 
437 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
438   StringRef name = sym.Info.Name;
439   uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
440 
441   switch (sym.Info.Kind) {
442   case WASM_SYMBOL_TYPE_FUNCTION:
443     if (sym.isBindingLocal())
444       return make<UndefinedFunction>(name, sym.Info.ImportName,
445                                      sym.Info.ImportModule, flags, this,
446                                      sym.Signature, isCalledDirectly);
447     return symtab->addUndefinedFunction(name, sym.Info.ImportName,
448                                         sym.Info.ImportModule, flags, this,
449                                         sym.Signature, isCalledDirectly);
450   case WASM_SYMBOL_TYPE_DATA:
451     if (sym.isBindingLocal())
452       return make<UndefinedData>(name, flags, this);
453     return symtab->addUndefinedData(name, flags, this);
454   case WASM_SYMBOL_TYPE_GLOBAL:
455     if (sym.isBindingLocal())
456       return make<UndefinedGlobal>(name, sym.Info.ImportName,
457                                    sym.Info.ImportModule, flags, this,
458                                    sym.GlobalType);
459     return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
460                                       sym.Info.ImportModule, flags, this,
461                                       sym.GlobalType);
462   case WASM_SYMBOL_TYPE_SECTION:
463     llvm_unreachable("section symbols cannot be undefined");
464   }
465   llvm_unreachable("unknown symbol kind");
466 }
467 
468 void ArchiveFile::parse() {
469   // Parse a MemoryBufferRef as an archive file.
470   LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
471   file = CHECK(Archive::create(mb), toString(this));
472 
473   // Read the symbol table to construct Lazy symbols.
474   int count = 0;
475   for (const Archive::Symbol &sym : file->symbols()) {
476     symtab->addLazy(this, &sym);
477     ++count;
478   }
479   LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
480 }
481 
482 void ArchiveFile::addMember(const Archive::Symbol *sym) {
483   const Archive::Child &c =
484       CHECK(sym->getMember(),
485             "could not get the member for symbol " + sym->getName());
486 
487   // Don't try to load the same member twice (this can happen when members
488   // mutually reference each other).
489   if (!seen.insert(c.getChildOffset()).second)
490     return;
491 
492   LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
493   LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
494 
495   MemoryBufferRef mb =
496       CHECK(c.getMemoryBufferRef(),
497             "could not get the buffer for the member defining symbol " +
498                 sym->getName());
499 
500   InputFile *obj = createObjectFile(mb, getName());
501   symtab->addFile(obj);
502 }
503 
504 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
505   switch (gvVisibility) {
506   case GlobalValue::DefaultVisibility:
507     return WASM_SYMBOL_VISIBILITY_DEFAULT;
508   case GlobalValue::HiddenVisibility:
509   case GlobalValue::ProtectedVisibility:
510     return WASM_SYMBOL_VISIBILITY_HIDDEN;
511   }
512   llvm_unreachable("unknown visibility");
513 }
514 
515 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
516                                    const lto::InputFile::Symbol &objSym,
517                                    BitcodeFile &f) {
518   StringRef name = saver.save(objSym.getName());
519 
520   uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
521   flags |= mapVisibility(objSym.getVisibility());
522 
523   int c = objSym.getComdatIndex();
524   bool excludedByComdat = c != -1 && !keptComdats[c];
525 
526   if (objSym.isUndefined() || excludedByComdat) {
527     flags |= WASM_SYMBOL_UNDEFINED;
528     if (objSym.isExecutable())
529       return symtab->addUndefinedFunction(name, "", "", flags, &f, nullptr,
530                                           true);
531     return symtab->addUndefinedData(name, flags, &f);
532   }
533 
534   if (objSym.isExecutable())
535     return symtab->addDefinedFunction(name, flags, &f, nullptr);
536   return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
537 }
538 
539 void BitcodeFile::parse() {
540   obj = check(lto::InputFile::create(MemoryBufferRef(
541       mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier()))));
542   Triple t(obj->getTargetTriple());
543   if (t.getArch() != Triple::wasm32) {
544     error(toString(mb.getBufferIdentifier()) + ": machine type must be wasm32");
545     return;
546   }
547   std::vector<bool> keptComdats;
548   for (StringRef s : obj->getComdatTable())
549     keptComdats.push_back(symtab->addComdat(s));
550 
551   for (const lto::InputFile::Symbol &objSym : obj->symbols())
552     symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
553 }
554 
555 } // namespace wasm
556 } // namespace lld
557