1 //===- InputChunks.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 "InputChunks.h"
10 #include "Config.h"
11 #include "OutputSegment.h"
12 #include "WriterUtils.h"
13 #include "lld/Common/ErrorHandler.h"
14 #include "lld/Common/LLVM.h"
15 #include "llvm/Support/LEB128.h"
16 #include "llvm/Support/xxhash.h"
17 
18 #define DEBUG_TYPE "lld"
19 
20 using namespace llvm;
21 using namespace llvm::wasm;
22 using namespace llvm::support::endian;
23 
24 namespace lld {
25 StringRef relocTypeToString(uint8_t relocType) {
26   switch (relocType) {
27 #define WASM_RELOC(NAME, REL)                                                  \
28   case REL:                                                                    \
29     return #NAME;
30 #include "llvm/BinaryFormat/WasmRelocs.def"
31 #undef WASM_RELOC
32   }
33   llvm_unreachable("unknown reloc type");
34 }
35 
36 bool relocIs64(uint8_t relocType) {
37   switch (relocType) {
38   case R_WASM_MEMORY_ADDR_LEB64:
39   case R_WASM_MEMORY_ADDR_SLEB64:
40   case R_WASM_MEMORY_ADDR_REL_SLEB64:
41   case R_WASM_MEMORY_ADDR_I64:
42     return true;
43   default:
44     return false;
45   }
46 }
47 
48 std::string toString(const wasm::InputChunk *c) {
49   return (toString(c->file) + ":(" + c->getName() + ")").str();
50 }
51 
52 namespace wasm {
53 StringRef InputChunk::getComdatName() const {
54   uint32_t index = getComdat();
55   if (index == UINT32_MAX)
56     return StringRef();
57   return file->getWasmObj()->linkingData().Comdats[index];
58 }
59 
60 uint32_t InputChunk::getSize() const {
61   if (const auto *ms = dyn_cast<SyntheticMergedChunk>(this))
62     return ms->builder.getSize();
63 
64   if (const auto *f = dyn_cast<InputFunction>(this)) {
65     if (config->compressRelocations && f->file) {
66       return f->getCompressedSize();
67     }
68   }
69 
70   return data().size();
71 }
72 
73 uint32_t InputChunk::getInputSize() const {
74   if (const auto *f = dyn_cast<InputFunction>(this))
75     return f->function->Size;
76   return getSize();
77 }
78 
79 // Copy this input chunk to an mmap'ed output file and apply relocations.
80 void InputChunk::writeTo(uint8_t *buf) const {
81   if (const auto *f = dyn_cast<InputFunction>(this)) {
82     if (file && config->compressRelocations)
83       return f->writeCompressed(buf);
84   } else if (const auto *ms = dyn_cast<SyntheticMergedChunk>(this)) {
85     ms->builder.write(buf + outSecOff);
86     // Apply relocations
87     ms->relocate(buf + outSecOff);
88     return;
89   }
90 
91   // Copy contents
92   memcpy(buf + outSecOff, data().data(), data().size());
93 
94   // Apply relocations
95   relocate(buf + outSecOff);
96 }
97 
98 void InputChunk::relocate(uint8_t *buf) const {
99   if (relocations.empty())
100     return;
101 
102   LLVM_DEBUG(dbgs() << "applying relocations: " << toString(this)
103                     << " count=" << relocations.size() << "\n");
104   int32_t inputSectionOffset = getInputSectionOffset();
105   uint64_t tombstone = getTombstone();
106 
107   for (const WasmRelocation &rel : relocations) {
108     uint8_t *loc = buf + rel.Offset - inputSectionOffset;
109     LLVM_DEBUG(dbgs() << "apply reloc: type=" << relocTypeToString(rel.Type));
110     if (rel.Type != R_WASM_TYPE_INDEX_LEB)
111       LLVM_DEBUG(dbgs() << " sym=" << file->getSymbols()[rel.Index]->getName());
112     LLVM_DEBUG(dbgs() << " addend=" << rel.Addend << " index=" << rel.Index
113                       << " offset=" << rel.Offset << "\n");
114     auto value = file->calcNewValue(rel, tombstone, this);
115 
116     switch (rel.Type) {
117     case R_WASM_TYPE_INDEX_LEB:
118     case R_WASM_FUNCTION_INDEX_LEB:
119     case R_WASM_GLOBAL_INDEX_LEB:
120     case R_WASM_TAG_INDEX_LEB:
121     case R_WASM_MEMORY_ADDR_LEB:
122     case R_WASM_TABLE_NUMBER_LEB:
123       encodeULEB128(value, loc, 5);
124       break;
125     case R_WASM_MEMORY_ADDR_LEB64:
126       encodeULEB128(value, loc, 10);
127       break;
128     case R_WASM_TABLE_INDEX_SLEB:
129     case R_WASM_TABLE_INDEX_REL_SLEB:
130     case R_WASM_MEMORY_ADDR_SLEB:
131     case R_WASM_MEMORY_ADDR_REL_SLEB:
132     case R_WASM_MEMORY_ADDR_TLS_SLEB:
133       encodeSLEB128(static_cast<int32_t>(value), loc, 5);
134       break;
135     case R_WASM_TABLE_INDEX_SLEB64:
136     case R_WASM_TABLE_INDEX_REL_SLEB64:
137     case R_WASM_MEMORY_ADDR_SLEB64:
138     case R_WASM_MEMORY_ADDR_REL_SLEB64:
139       encodeSLEB128(static_cast<int64_t>(value), loc, 10);
140       break;
141     case R_WASM_TABLE_INDEX_I32:
142     case R_WASM_MEMORY_ADDR_I32:
143     case R_WASM_FUNCTION_OFFSET_I32:
144     case R_WASM_SECTION_OFFSET_I32:
145     case R_WASM_GLOBAL_INDEX_I32:
146     case R_WASM_MEMORY_ADDR_LOCREL_I32:
147       write32le(loc, value);
148       break;
149     case R_WASM_TABLE_INDEX_I64:
150     case R_WASM_MEMORY_ADDR_I64:
151     case R_WASM_FUNCTION_OFFSET_I64:
152       write64le(loc, value);
153       break;
154     default:
155       llvm_unreachable("unknown relocation type");
156     }
157   }
158 }
159 
160 // Copy relocation entries to a given output stream.
161 // This function is used only when a user passes "-r". For a regular link,
162 // we consume relocations instead of copying them to an output file.
163 void InputChunk::writeRelocations(raw_ostream &os) const {
164   if (relocations.empty())
165     return;
166 
167   int32_t off = outSecOff - getInputSectionOffset();
168   LLVM_DEBUG(dbgs() << "writeRelocations: " << file->getName()
169                     << " offset=" << Twine(off) << "\n");
170 
171   for (const WasmRelocation &rel : relocations) {
172     writeUleb128(os, rel.Type, "reloc type");
173     writeUleb128(os, rel.Offset + off, "reloc offset");
174     writeUleb128(os, file->calcNewIndex(rel), "reloc index");
175 
176     if (relocTypeHasAddend(rel.Type))
177       writeSleb128(os, file->calcNewAddend(rel), "reloc addend");
178   }
179 }
180 
181 uint64_t InputChunk::getTombstone() const {
182   if (const auto *s = dyn_cast<InputSection>(this)) {
183     return s->tombstoneValue;
184   }
185 
186   return 0;
187 }
188 
189 void InputFunction::setFunctionIndex(uint32_t index) {
190   LLVM_DEBUG(dbgs() << "InputFunction::setFunctionIndex: " << getName()
191                     << " -> " << index << "\n");
192   assert(!hasFunctionIndex());
193   functionIndex = index;
194 }
195 
196 void InputFunction::setTableIndex(uint32_t index) {
197   LLVM_DEBUG(dbgs() << "InputFunction::setTableIndex: " << getName() << " -> "
198                     << index << "\n");
199   assert(!hasTableIndex());
200   tableIndex = index;
201 }
202 
203 // Write a relocation value without padding and return the number of bytes
204 // witten.
205 static unsigned writeCompressedReloc(uint8_t *buf, const WasmRelocation &rel,
206                                      uint64_t value) {
207   switch (rel.Type) {
208   case R_WASM_TYPE_INDEX_LEB:
209   case R_WASM_FUNCTION_INDEX_LEB:
210   case R_WASM_GLOBAL_INDEX_LEB:
211   case R_WASM_TAG_INDEX_LEB:
212   case R_WASM_MEMORY_ADDR_LEB:
213   case R_WASM_MEMORY_ADDR_LEB64:
214   case R_WASM_TABLE_NUMBER_LEB:
215     return encodeULEB128(value, buf);
216   case R_WASM_TABLE_INDEX_SLEB:
217   case R_WASM_TABLE_INDEX_SLEB64:
218   case R_WASM_MEMORY_ADDR_SLEB:
219   case R_WASM_MEMORY_ADDR_SLEB64:
220     return encodeSLEB128(static_cast<int64_t>(value), buf);
221   default:
222     llvm_unreachable("unexpected relocation type");
223   }
224 }
225 
226 static unsigned getRelocWidthPadded(const WasmRelocation &rel) {
227   switch (rel.Type) {
228   case R_WASM_TYPE_INDEX_LEB:
229   case R_WASM_FUNCTION_INDEX_LEB:
230   case R_WASM_GLOBAL_INDEX_LEB:
231   case R_WASM_TAG_INDEX_LEB:
232   case R_WASM_MEMORY_ADDR_LEB:
233   case R_WASM_TABLE_NUMBER_LEB:
234   case R_WASM_TABLE_INDEX_SLEB:
235   case R_WASM_MEMORY_ADDR_SLEB:
236     return 5;
237   case R_WASM_TABLE_INDEX_SLEB64:
238   case R_WASM_MEMORY_ADDR_LEB64:
239   case R_WASM_MEMORY_ADDR_SLEB64:
240     return 10;
241   default:
242     llvm_unreachable("unexpected relocation type");
243   }
244 }
245 
246 static unsigned getRelocWidth(const WasmRelocation &rel, uint64_t value) {
247   uint8_t buf[10];
248   return writeCompressedReloc(buf, rel, value);
249 }
250 
251 // Relocations of type LEB and SLEB in the code section are padded to 5 bytes
252 // so that a fast linker can blindly overwrite them without needing to worry
253 // about the number of bytes needed to encode the values.
254 // However, for optimal output the code section can be compressed to remove
255 // the padding then outputting non-relocatable files.
256 // In this case we need to perform a size calculation based on the value at each
257 // relocation.  At best we end up saving 4 bytes for each relocation entry.
258 //
259 // This function only computes the final output size.  It must be called
260 // before getSize() is used to calculate of layout of the code section.
261 void InputFunction::calculateSize() {
262   if (!file || !config->compressRelocations)
263     return;
264 
265   LLVM_DEBUG(dbgs() << "calculateSize: " << getName() << "\n");
266 
267   const uint8_t *secStart = file->codeSection->Content.data();
268   const uint8_t *funcStart = secStart + getInputSectionOffset();
269   uint32_t functionSizeLength;
270   decodeULEB128(funcStart, &functionSizeLength);
271 
272   uint32_t start = getInputSectionOffset();
273   uint32_t end = start + function->Size;
274 
275   uint64_t tombstone = getTombstone();
276 
277   uint32_t lastRelocEnd = start + functionSizeLength;
278   for (const WasmRelocation &rel : relocations) {
279     LLVM_DEBUG(dbgs() << "  region: " << (rel.Offset - lastRelocEnd) << "\n");
280     compressedFuncSize += rel.Offset - lastRelocEnd;
281     compressedFuncSize +=
282         getRelocWidth(rel, file->calcNewValue(rel, tombstone, this));
283     lastRelocEnd = rel.Offset + getRelocWidthPadded(rel);
284   }
285   LLVM_DEBUG(dbgs() << "  final region: " << (end - lastRelocEnd) << "\n");
286   compressedFuncSize += end - lastRelocEnd;
287 
288   // Now we know how long the resulting function is we can add the encoding
289   // of its length
290   uint8_t buf[5];
291   compressedSize = compressedFuncSize + encodeULEB128(compressedFuncSize, buf);
292 
293   LLVM_DEBUG(dbgs() << "  calculateSize orig: " << function->Size << "\n");
294   LLVM_DEBUG(dbgs() << "  calculateSize  new: " << compressedSize << "\n");
295 }
296 
297 // Override the default writeTo method so that we can (optionally) write the
298 // compressed version of the function.
299 void InputFunction::writeCompressed(uint8_t *buf) const {
300   buf += outSecOff;
301   uint8_t *orig = buf;
302   (void)orig;
303 
304   const uint8_t *secStart = file->codeSection->Content.data();
305   const uint8_t *funcStart = secStart + getInputSectionOffset();
306   const uint8_t *end = funcStart + function->Size;
307   uint64_t tombstone = getTombstone();
308   uint32_t count;
309   decodeULEB128(funcStart, &count);
310   funcStart += count;
311 
312   LLVM_DEBUG(dbgs() << "write func: " << getName() << "\n");
313   buf += encodeULEB128(compressedFuncSize, buf);
314   const uint8_t *lastRelocEnd = funcStart;
315   for (const WasmRelocation &rel : relocations) {
316     unsigned chunkSize = (secStart + rel.Offset) - lastRelocEnd;
317     LLVM_DEBUG(dbgs() << "  write chunk: " << chunkSize << "\n");
318     memcpy(buf, lastRelocEnd, chunkSize);
319     buf += chunkSize;
320     buf += writeCompressedReloc(buf, rel,
321                                 file->calcNewValue(rel, tombstone, this));
322     lastRelocEnd = secStart + rel.Offset + getRelocWidthPadded(rel);
323   }
324 
325   unsigned chunkSize = end - lastRelocEnd;
326   LLVM_DEBUG(dbgs() << "  write final chunk: " << chunkSize << "\n");
327   memcpy(buf, lastRelocEnd, chunkSize);
328   LLVM_DEBUG(dbgs() << "  total: " << (buf + chunkSize - orig) << "\n");
329 }
330 
331 uint64_t InputChunk::getChunkOffset(uint64_t offset) const {
332   if (const auto *ms = dyn_cast<MergeInputChunk>(this)) {
333     LLVM_DEBUG(dbgs() << "getChunkOffset(merged): " << getName() << "\n");
334     LLVM_DEBUG(dbgs() << "offset: " << offset << "\n");
335     LLVM_DEBUG(dbgs() << "parentOffset: " << ms->getParentOffset(offset)
336                       << "\n");
337     assert(ms->parent);
338     return ms->parent->getChunkOffset(ms->getParentOffset(offset));
339   }
340   return outputSegmentOffset + offset;
341 }
342 
343 uint64_t InputChunk::getOffset(uint64_t offset) const {
344   return outSecOff + getChunkOffset(offset);
345 }
346 
347 uint64_t InputChunk::getVA(uint64_t offset) const {
348   return (outputSeg ? outputSeg->startVA : 0) + getChunkOffset(offset);
349 }
350 
351 // Generate code to apply relocations to the data section at runtime.
352 // This is only called when generating shared libaries (PIC) where address are
353 // not known at static link time.
354 void InputChunk::generateRelocationCode(raw_ostream &os) const {
355   LLVM_DEBUG(dbgs() << "generating runtime relocations: " << getName()
356                     << " count=" << relocations.size() << "\n");
357 
358   unsigned opcode_ptr_const = config->is64.getValueOr(false)
359                                   ? WASM_OPCODE_I64_CONST
360                                   : WASM_OPCODE_I32_CONST;
361   unsigned opcode_ptr_add = config->is64.getValueOr(false)
362                                 ? WASM_OPCODE_I64_ADD
363                                 : WASM_OPCODE_I32_ADD;
364 
365   uint64_t tombstone = getTombstone();
366   // TODO(sbc): Encode the relocations in the data section and write a loop
367   // here to apply them.
368   for (const WasmRelocation &rel : relocations) {
369     uint64_t offset = getVA(rel.Offset) - getInputSectionOffset();
370 
371     LLVM_DEBUG(dbgs() << "gen reloc: type=" << relocTypeToString(rel.Type)
372                       << " addend=" << rel.Addend << " index=" << rel.Index
373                       << " output offset=" << offset << "\n");
374 
375     // Get __memory_base
376     writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
377     writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
378 
379     // Add the offset of the relocation
380     writeU8(os, opcode_ptr_const, "CONST");
381     writeSleb128(os, offset, "offset");
382     writeU8(os, opcode_ptr_add, "ADD");
383 
384     bool is64 = relocIs64(rel.Type);
385     unsigned opcode_reloc_const =
386         is64 ? WASM_OPCODE_I64_CONST : WASM_OPCODE_I32_CONST;
387     unsigned opcode_reloc_add =
388         is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD;
389     unsigned opcode_reloc_store =
390         is64 ? WASM_OPCODE_I64_STORE : WASM_OPCODE_I32_STORE;
391 
392     Symbol *sym = file->getSymbol(rel);
393     // Now figure out what we want to store
394     if (sym->hasGOTIndex()) {
395       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
396       writeUleb128(os, sym->getGOTIndex(), "global index");
397       if (rel.Addend) {
398         writeU8(os, opcode_reloc_const, "CONST");
399         writeSleb128(os, rel.Addend, "addend");
400         writeU8(os, opcode_reloc_add, "ADD");
401       }
402     } else {
403       const GlobalSymbol* baseSymbol = WasmSym::memoryBase;
404       if (rel.Type == R_WASM_TABLE_INDEX_I32 ||
405           rel.Type == R_WASM_TABLE_INDEX_I64)
406         baseSymbol = WasmSym::tableBase;
407       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
408       writeUleb128(os, baseSymbol->getGlobalIndex(), "base");
409       writeU8(os, opcode_reloc_const, "CONST");
410       writeSleb128(os, file->calcNewValue(rel, tombstone, this), "offset");
411       writeU8(os, opcode_reloc_add, "ADD");
412     }
413 
414     // Store that value at the virtual address
415     writeU8(os, opcode_reloc_store, "I32_STORE");
416     writeUleb128(os, 2, "align");
417     writeUleb128(os, 0, "offset");
418   }
419 }
420 
421 // Split WASM_SEG_FLAG_STRINGS section. Such a section is a sequence of
422 // null-terminated strings.
423 void MergeInputChunk::splitStrings(ArrayRef<uint8_t> data) {
424   LLVM_DEBUG(llvm::dbgs() << "splitStrings\n");
425   size_t off = 0;
426   StringRef s = toStringRef(data);
427 
428   while (!s.empty()) {
429     size_t end = s.find(0);
430     if (end == StringRef::npos)
431       fatal(toString(this) + ": string is not null terminated");
432     size_t size = end + 1;
433 
434     pieces.emplace_back(off, xxHash64(s.substr(0, size)), true);
435     s = s.substr(size);
436     off += size;
437   }
438 }
439 
440 // This function is called after we obtain a complete list of input sections
441 // that need to be linked. This is responsible to split section contents
442 // into small chunks for further processing.
443 //
444 // Note that this function is called from parallelForEach. This must be
445 // thread-safe (i.e. no memory allocation from the pools).
446 void MergeInputChunk::splitIntoPieces() {
447   assert(pieces.empty());
448   // As of now we only support WASM_SEG_FLAG_STRINGS but in the future we
449   // could add other types of splitting (see ELF's splitIntoPieces).
450   assert(flags & WASM_SEG_FLAG_STRINGS);
451   splitStrings(data());
452 }
453 
454 SectionPiece *MergeInputChunk::getSectionPiece(uint64_t offset) {
455   if (this->data().size() <= offset)
456     fatal(toString(this) + ": offset is outside the section");
457 
458   // If Offset is not at beginning of a section piece, it is not in the map.
459   // In that case we need to  do a binary search of the original section piece
460   // vector.
461   auto it = partition_point(
462       pieces, [=](SectionPiece p) { return p.inputOff <= offset; });
463   return &it[-1];
464 }
465 
466 // Returns the offset in an output section for a given input offset.
467 // Because contents of a mergeable section is not contiguous in output,
468 // it is not just an addition to a base output offset.
469 uint64_t MergeInputChunk::getParentOffset(uint64_t offset) const {
470   // If Offset is not at beginning of a section piece, it is not in the map.
471   // In that case we need to search from the original section piece vector.
472   const SectionPiece *piece = getSectionPiece(offset);
473   uint64_t addend = offset - piece->inputOff;
474   return piece->outputOff + addend;
475 }
476 
477 void SyntheticMergedChunk::finalizeContents() {
478   // Add all string pieces to the string table builder to create section
479   // contents.
480   for (MergeInputChunk *sec : chunks)
481     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
482       if (sec->pieces[i].live)
483         builder.add(sec->getData(i));
484 
485   // Fix the string table content. After this, the contents will never change.
486   builder.finalize();
487 
488   // finalize() fixed tail-optimized strings, so we can now get
489   // offsets of strings. Get an offset for each string and save it
490   // to a corresponding SectionPiece for easy access.
491   for (MergeInputChunk *sec : chunks)
492     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
493       if (sec->pieces[i].live)
494         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
495 }
496 
497 uint64_t InputSection::getTombstoneForSection(StringRef name) {
498   // When a function is not live we need to update relocations referring to it.
499   // If they occur in DWARF debug symbols, we want to change the pc of the
500   // function to -1 to avoid overlapping with a valid range. However for the
501   // debug_ranges and debug_loc sections that would conflict with the existing
502   // meaning of -1 so we use -2.
503   // Returning 0 means there is no tombstone value for this section, and relocation
504   // will just use the addend.
505   if (!name.startswith(".debug_"))
506     return 0;
507   if (name.equals(".debug_ranges") || name.equals(".debug_loc"))
508     return UINT64_C(-2);
509   return UINT64_C(-1);
510 }
511 
512 } // namespace wasm
513 } // namespace lld
514