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 
17 #define DEBUG_TYPE "lld"
18 
19 using namespace llvm;
20 using namespace llvm::wasm;
21 using namespace llvm::support::endian;
22 
23 namespace lld {
24 StringRef relocTypeToString(uint8_t relocType) {
25   switch (relocType) {
26 #define WASM_RELOC(NAME, REL)                                                  \
27   case REL:                                                                    \
28     return #NAME;
29 #include "llvm/BinaryFormat/WasmRelocs.def"
30 #undef WASM_RELOC
31   }
32   llvm_unreachable("unknown reloc type");
33 }
34 
35 bool relocIs64(uint8_t relocType) {
36   switch (relocType) {
37   case R_WASM_MEMORY_ADDR_LEB64:
38   case R_WASM_MEMORY_ADDR_SLEB64:
39   case R_WASM_MEMORY_ADDR_REL_SLEB64:
40   case R_WASM_MEMORY_ADDR_I64:
41     return true;
42   default:
43     return false;
44   }
45 }
46 
47 std::string toString(const wasm::InputChunk *c) {
48   return (toString(c->file) + ":(" + c->getName() + ")").str();
49 }
50 
51 namespace wasm {
52 StringRef InputChunk::getComdatName() const {
53   uint32_t index = getComdat();
54   if (index == UINT32_MAX)
55     return StringRef();
56   return file->getWasmObj()->linkingData().Comdats[index];
57 }
58 
59 void InputChunk::verifyRelocTargets() const {
60   for (const WasmRelocation &rel : relocations) {
61     uint64_t existingValue;
62     unsigned bytesRead = 0;
63     unsigned paddedLEBWidth = 5;
64     auto offset = rel.Offset - getInputSectionOffset();
65     const uint8_t *loc = data().data() + offset;
66     switch (rel.Type) {
67     case R_WASM_TYPE_INDEX_LEB:
68     case R_WASM_FUNCTION_INDEX_LEB:
69     case R_WASM_GLOBAL_INDEX_LEB:
70     case R_WASM_EVENT_INDEX_LEB:
71     case R_WASM_MEMORY_ADDR_LEB:
72       existingValue = decodeULEB128(loc, &bytesRead);
73       break;
74     case R_WASM_MEMORY_ADDR_LEB64:
75       existingValue = decodeULEB128(loc, &bytesRead);
76       paddedLEBWidth = 10;
77       break;
78     case R_WASM_TABLE_INDEX_SLEB:
79     case R_WASM_TABLE_INDEX_REL_SLEB:
80     case R_WASM_MEMORY_ADDR_SLEB:
81     case R_WASM_MEMORY_ADDR_REL_SLEB:
82       existingValue = static_cast<uint64_t>(decodeSLEB128(loc, &bytesRead));
83       break;
84     case R_WASM_TABLE_INDEX_SLEB64:
85     case R_WASM_MEMORY_ADDR_SLEB64:
86     case R_WASM_MEMORY_ADDR_REL_SLEB64:
87       existingValue = static_cast<uint64_t>(decodeSLEB128(loc, &bytesRead));
88       paddedLEBWidth = 10;
89       break;
90     case R_WASM_TABLE_INDEX_I32:
91     case R_WASM_MEMORY_ADDR_I32:
92     case R_WASM_FUNCTION_OFFSET_I32:
93     case R_WASM_SECTION_OFFSET_I32:
94     case R_WASM_GLOBAL_INDEX_I32:
95       existingValue = read32le(loc);
96       break;
97     case R_WASM_TABLE_INDEX_I64:
98     case R_WASM_MEMORY_ADDR_I64:
99       existingValue = read64le(loc);
100       break;
101     default:
102       llvm_unreachable("unknown relocation type");
103     }
104 
105     if (bytesRead && bytesRead != paddedLEBWidth)
106       warn("expected LEB at relocation site be 5/10-byte padded");
107 
108     if (rel.Type != R_WASM_GLOBAL_INDEX_LEB &&
109         rel.Type != R_WASM_GLOBAL_INDEX_I32) {
110       auto expectedValue = file->calcExpectedValue(rel);
111       if (expectedValue != existingValue)
112         warn(toString(this) + ": unexpected existing value for " +
113              relocTypeToString(rel.Type) + ": existing=" +
114              Twine(existingValue) + " expected=" + Twine(expectedValue));
115     }
116   }
117 }
118 
119 // Copy this input chunk to an mmap'ed output file and apply relocations.
120 void InputChunk::writeTo(uint8_t *buf) const {
121   // Copy contents
122   memcpy(buf + outputOffset, data().data(), data().size());
123 
124   // Apply relocations
125   if (relocations.empty())
126     return;
127 
128 #ifndef NDEBUG
129   verifyRelocTargets();
130 #endif
131 
132   LLVM_DEBUG(dbgs() << "applying relocations: " << toString(this)
133                     << " count=" << relocations.size() << "\n");
134   int32_t off = outputOffset - getInputSectionOffset();
135 
136   for (const WasmRelocation &rel : relocations) {
137     uint8_t *loc = buf + rel.Offset + off;
138     auto value = file->calcNewValue(rel);
139     LLVM_DEBUG(dbgs() << "apply reloc: type=" << relocTypeToString(rel.Type));
140     if (rel.Type != R_WASM_TYPE_INDEX_LEB)
141       LLVM_DEBUG(dbgs() << " sym=" << file->getSymbols()[rel.Index]->getName());
142     LLVM_DEBUG(dbgs() << " addend=" << rel.Addend << " index=" << rel.Index
143                       << " value=" << value << " offset=" << rel.Offset
144                       << "\n");
145 
146     switch (rel.Type) {
147     case R_WASM_TYPE_INDEX_LEB:
148     case R_WASM_FUNCTION_INDEX_LEB:
149     case R_WASM_GLOBAL_INDEX_LEB:
150     case R_WASM_EVENT_INDEX_LEB:
151     case R_WASM_MEMORY_ADDR_LEB:
152       encodeULEB128(value, loc, 5);
153       break;
154     case R_WASM_MEMORY_ADDR_LEB64:
155       encodeULEB128(value, loc, 10);
156       break;
157     case R_WASM_TABLE_INDEX_SLEB:
158     case R_WASM_TABLE_INDEX_REL_SLEB:
159     case R_WASM_MEMORY_ADDR_SLEB:
160     case R_WASM_MEMORY_ADDR_REL_SLEB:
161       encodeSLEB128(static_cast<int32_t>(value), loc, 5);
162       break;
163     case R_WASM_TABLE_INDEX_SLEB64:
164     case R_WASM_MEMORY_ADDR_SLEB64:
165     case R_WASM_MEMORY_ADDR_REL_SLEB64:
166       encodeSLEB128(static_cast<int64_t>(value), loc, 10);
167       break;
168     case R_WASM_TABLE_INDEX_I32:
169     case R_WASM_MEMORY_ADDR_I32:
170     case R_WASM_FUNCTION_OFFSET_I32:
171     case R_WASM_SECTION_OFFSET_I32:
172     case R_WASM_GLOBAL_INDEX_I32:
173       write32le(loc, value);
174       break;
175     case R_WASM_TABLE_INDEX_I64:
176     case R_WASM_MEMORY_ADDR_I64:
177       write64le(loc, value);
178       break;
179     default:
180       llvm_unreachable("unknown relocation type");
181     }
182   }
183 }
184 
185 // Copy relocation entries to a given output stream.
186 // This function is used only when a user passes "-r". For a regular link,
187 // we consume relocations instead of copying them to an output file.
188 void InputChunk::writeRelocations(raw_ostream &os) const {
189   if (relocations.empty())
190     return;
191 
192   int32_t off = outputOffset - getInputSectionOffset();
193   LLVM_DEBUG(dbgs() << "writeRelocations: " << file->getName()
194                     << " offset=" << Twine(off) << "\n");
195 
196   for (const WasmRelocation &rel : relocations) {
197     writeUleb128(os, rel.Type, "reloc type");
198     writeUleb128(os, rel.Offset + off, "reloc offset");
199     writeUleb128(os, file->calcNewIndex(rel), "reloc index");
200 
201     if (relocTypeHasAddend(rel.Type))
202       writeSleb128(os, file->calcNewAddend(rel), "reloc addend");
203   }
204 }
205 
206 void InputFunction::setFunctionIndex(uint32_t index) {
207   LLVM_DEBUG(dbgs() << "InputFunction::setFunctionIndex: " << getName()
208                     << " -> " << index << "\n");
209   assert(!hasFunctionIndex());
210   functionIndex = index;
211 }
212 
213 void InputFunction::setTableIndex(uint32_t index) {
214   LLVM_DEBUG(dbgs() << "InputFunction::setTableIndex: " << getName() << " -> "
215                     << index << "\n");
216   assert(!hasTableIndex());
217   tableIndex = index;
218 }
219 
220 // Write a relocation value without padding and return the number of bytes
221 // witten.
222 static unsigned writeCompressedReloc(uint8_t *buf, const WasmRelocation &rel,
223                                      uint64_t value) {
224   switch (rel.Type) {
225   case R_WASM_TYPE_INDEX_LEB:
226   case R_WASM_FUNCTION_INDEX_LEB:
227   case R_WASM_GLOBAL_INDEX_LEB:
228   case R_WASM_EVENT_INDEX_LEB:
229   case R_WASM_MEMORY_ADDR_LEB:
230   case R_WASM_MEMORY_ADDR_LEB64:
231     return encodeULEB128(value, buf);
232   case R_WASM_TABLE_INDEX_SLEB:
233   case R_WASM_TABLE_INDEX_SLEB64:
234   case R_WASM_MEMORY_ADDR_SLEB:
235   case R_WASM_MEMORY_ADDR_SLEB64:
236     return encodeSLEB128(static_cast<int64_t>(value), buf);
237   default:
238     llvm_unreachable("unexpected relocation type");
239   }
240 }
241 
242 static unsigned getRelocWidthPadded(const WasmRelocation &rel) {
243   switch (rel.Type) {
244   case R_WASM_TYPE_INDEX_LEB:
245   case R_WASM_FUNCTION_INDEX_LEB:
246   case R_WASM_GLOBAL_INDEX_LEB:
247   case R_WASM_EVENT_INDEX_LEB:
248   case R_WASM_MEMORY_ADDR_LEB:
249   case R_WASM_TABLE_INDEX_SLEB:
250   case R_WASM_MEMORY_ADDR_SLEB:
251     return 5;
252   case R_WASM_TABLE_INDEX_SLEB64:
253   case R_WASM_MEMORY_ADDR_LEB64:
254   case R_WASM_MEMORY_ADDR_SLEB64:
255     return 10;
256   default:
257     llvm_unreachable("unexpected relocation type");
258   }
259 }
260 
261 static unsigned getRelocWidth(const WasmRelocation &rel, uint64_t value) {
262   uint8_t buf[10];
263   return writeCompressedReloc(buf, rel, value);
264 }
265 
266 // Relocations of type LEB and SLEB in the code section are padded to 5 bytes
267 // so that a fast linker can blindly overwrite them without needing to worry
268 // about the number of bytes needed to encode the values.
269 // However, for optimal output the code section can be compressed to remove
270 // the padding then outputting non-relocatable files.
271 // In this case we need to perform a size calculation based on the value at each
272 // relocation.  At best we end up saving 4 bytes for each relocation entry.
273 //
274 // This function only computes the final output size.  It must be called
275 // before getSize() is used to calculate of layout of the code section.
276 void InputFunction::calculateSize() {
277   if (!file || !config->compressRelocations)
278     return;
279 
280   LLVM_DEBUG(dbgs() << "calculateSize: " << getName() << "\n");
281 
282   const uint8_t *secStart = file->codeSection->Content.data();
283   const uint8_t *funcStart = secStart + getInputSectionOffset();
284   uint32_t functionSizeLength;
285   decodeULEB128(funcStart, &functionSizeLength);
286 
287   uint32_t start = getInputSectionOffset();
288   uint32_t end = start + function->Size;
289 
290   uint32_t lastRelocEnd = start + functionSizeLength;
291   for (const WasmRelocation &rel : relocations) {
292     LLVM_DEBUG(dbgs() << "  region: " << (rel.Offset - lastRelocEnd) << "\n");
293     compressedFuncSize += rel.Offset - lastRelocEnd;
294     compressedFuncSize += getRelocWidth(rel, file->calcNewValue(rel));
295     lastRelocEnd = rel.Offset + getRelocWidthPadded(rel);
296   }
297   LLVM_DEBUG(dbgs() << "  final region: " << (end - lastRelocEnd) << "\n");
298   compressedFuncSize += end - lastRelocEnd;
299 
300   // Now we know how long the resulting function is we can add the encoding
301   // of its length
302   uint8_t buf[5];
303   compressedSize = compressedFuncSize + encodeULEB128(compressedFuncSize, buf);
304 
305   LLVM_DEBUG(dbgs() << "  calculateSize orig: " << function->Size << "\n");
306   LLVM_DEBUG(dbgs() << "  calculateSize  new: " << compressedSize << "\n");
307 }
308 
309 // Override the default writeTo method so that we can (optionally) write the
310 // compressed version of the function.
311 void InputFunction::writeTo(uint8_t *buf) const {
312   if (!file || !config->compressRelocations)
313     return InputChunk::writeTo(buf);
314 
315   buf += outputOffset;
316   uint8_t *orig = buf;
317   (void)orig;
318 
319   const uint8_t *secStart = file->codeSection->Content.data();
320   const uint8_t *funcStart = secStart + getInputSectionOffset();
321   const uint8_t *end = funcStart + function->Size;
322   uint32_t count;
323   decodeULEB128(funcStart, &count);
324   funcStart += count;
325 
326   LLVM_DEBUG(dbgs() << "write func: " << getName() << "\n");
327   buf += encodeULEB128(compressedFuncSize, buf);
328   const uint8_t *lastRelocEnd = funcStart;
329   for (const WasmRelocation &rel : relocations) {
330     unsigned chunkSize = (secStart + rel.Offset) - lastRelocEnd;
331     LLVM_DEBUG(dbgs() << "  write chunk: " << chunkSize << "\n");
332     memcpy(buf, lastRelocEnd, chunkSize);
333     buf += chunkSize;
334     buf += writeCompressedReloc(buf, rel, file->calcNewValue(rel));
335     lastRelocEnd = secStart + rel.Offset + getRelocWidthPadded(rel);
336   }
337 
338   unsigned chunkSize = end - lastRelocEnd;
339   LLVM_DEBUG(dbgs() << "  write final chunk: " << chunkSize << "\n");
340   memcpy(buf, lastRelocEnd, chunkSize);
341   LLVM_DEBUG(dbgs() << "  total: " << (buf + chunkSize - orig) << "\n");
342 }
343 
344 // Generate code to apply relocations to the data section at runtime.
345 // This is only called when generating shared libaries (PIC) where address are
346 // not known at static link time.
347 void InputSegment::generateRelocationCode(raw_ostream &os) const {
348   LLVM_DEBUG(dbgs() << "generating runtime relocations: " << getName()
349                     << " count=" << relocations.size() << "\n");
350 
351   unsigned opcode_ptr_const = config->is64.getValueOr(false)
352                                   ? WASM_OPCODE_I64_CONST
353                                   : WASM_OPCODE_I32_CONST;
354   unsigned opcode_ptr_add = config->is64.getValueOr(false)
355                                 ? WASM_OPCODE_I64_ADD
356                                 : WASM_OPCODE_I32_ADD;
357 
358   // TODO(sbc): Encode the relocations in the data section and write a loop
359   // here to apply them.
360   uint64_t segmentVA = outputSeg->startVA + outputSegmentOffset;
361   for (const WasmRelocation &rel : relocations) {
362     uint64_t offset = rel.Offset - getInputSectionOffset();
363     uint64_t outputOffset = segmentVA + offset;
364 
365     LLVM_DEBUG(dbgs() << "gen reloc: type=" << relocTypeToString(rel.Type)
366                       << " addend=" << rel.Addend << " index=" << rel.Index
367                       << " output offset=" << outputOffset << "\n");
368 
369     // Get __memory_base
370     writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
371     writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
372 
373     // Add the offset of the relocation
374     writeU8(os, opcode_ptr_const, "CONST");
375     writeSleb128(os, outputOffset, "offset");
376     writeU8(os, opcode_ptr_add, "ADD");
377 
378     bool is64 = relocIs64(rel.Type);
379     unsigned opcode_reloc_const =
380         is64 ? WASM_OPCODE_I64_CONST : WASM_OPCODE_I32_CONST;
381     unsigned opcode_reloc_add =
382         is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD;
383     unsigned opcode_reloc_store =
384         is64 ? WASM_OPCODE_I64_STORE : WASM_OPCODE_I32_STORE;
385 
386     Symbol *sym = file->getSymbol(rel);
387     // Now figure out what we want to store
388     if (sym->hasGOTIndex()) {
389       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
390       writeUleb128(os, sym->getGOTIndex(), "global index");
391       if (rel.Addend) {
392         writeU8(os, opcode_reloc_const, "CONST");
393         writeSleb128(os, rel.Addend, "addend");
394         writeU8(os, opcode_reloc_add, "ADD");
395       }
396     } else {
397       const GlobalSymbol* baseSymbol = WasmSym::memoryBase;
398       if (rel.Type == R_WASM_TABLE_INDEX_I32 ||
399           rel.Type == R_WASM_TABLE_INDEX_I64)
400         baseSymbol = WasmSym::tableBase;
401       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
402       writeUleb128(os, baseSymbol->getGlobalIndex(), "base");
403       writeU8(os, opcode_reloc_const, "CONST");
404       writeSleb128(os, file->calcNewValue(rel), "offset");
405       writeU8(os, opcode_reloc_add, "ADD");
406     }
407 
408     // Store that value at the virtual address
409     writeU8(os, opcode_reloc_store, "I32_STORE");
410     writeUleb128(os, 2, "align");
411     writeUleb128(os, 0, "offset");
412   }
413 }
414 
415 } // namespace wasm
416 } // namespace lld
417