1f61910d8SSam Clegg //===- InputChunks.cpp ----------------------------------------------------===//
25fa274beSSam Clegg //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65fa274beSSam Clegg //
75fa274beSSam Clegg //===----------------------------------------------------------------------===//
85fa274beSSam Clegg 
95fa274beSSam Clegg #include "InputChunks.h"
10d96d9357SSam Clegg #include "Config.h"
115fa274beSSam Clegg #include "OutputSegment.h"
12bf450d90SRui Ueyama #include "WriterUtils.h"
13d96d9357SSam Clegg #include "lld/Common/ErrorHandler.h"
145fa274beSSam Clegg #include "lld/Common/LLVM.h"
15d96d9357SSam Clegg #include "llvm/Support/LEB128.h"
163b8d2be5SSam Clegg #include "llvm/Support/xxhash.h"
175fa274beSSam Clegg 
185fa274beSSam Clegg #define DEBUG_TYPE "lld"
195fa274beSSam Clegg 
205fa274beSSam Clegg using namespace llvm;
21d96d9357SSam Clegg using namespace llvm::wasm;
22e351c3a4SRui Ueyama using namespace llvm::support::endian;
235fa274beSSam Clegg 
2433c59abfSFangrui Song namespace lld {
relocTypeToString(uint8_t relocType)2533c59abfSFangrui Song StringRef relocTypeToString(uint8_t relocType) {
26136d27abSRui Ueyama   switch (relocType) {
274821ebf7SHeejin Ahn #define WASM_RELOC(NAME, REL)                                                  \
284821ebf7SHeejin Ahn   case REL:                                                                    \
294821ebf7SHeejin Ahn     return #NAME;
30c1be8230SSam Clegg #include "llvm/BinaryFormat/WasmRelocs.def"
31c1be8230SSam Clegg #undef WASM_RELOC
32c1be8230SSam Clegg   }
33c1be8230SSam Clegg   llvm_unreachable("unknown reloc type");
34c1be8230SSam Clegg }
35c1be8230SSam Clegg 
relocIs64(uint8_t relocType)36b9a539c0SWouter van Oortmerssen bool relocIs64(uint8_t relocType) {
37b9a539c0SWouter van Oortmerssen   switch (relocType) {
38b9a539c0SWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_LEB64:
39b9a539c0SWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_SLEB64:
40b9a539c0SWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_REL_SLEB64:
41b9a539c0SWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_I64:
424157b603SWouter van Oortmerssen   case R_WASM_TABLE_INDEX_SLEB64:
434157b603SWouter van Oortmerssen   case R_WASM_TABLE_INDEX_I64:
444157b603SWouter van Oortmerssen   case R_WASM_FUNCTION_OFFSET_I64:
454157b603SWouter van Oortmerssen   case R_WASM_TABLE_INDEX_REL_SLEB64:
46670944fbSWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_TLS_SLEB64:
47b9a539c0SWouter van Oortmerssen     return true;
48b9a539c0SWouter van Oortmerssen   default:
49b9a539c0SWouter van Oortmerssen     return false;
50b9a539c0SWouter van Oortmerssen   }
51b9a539c0SWouter van Oortmerssen }
52b9a539c0SWouter van Oortmerssen 
toString(const wasm::InputChunk * c)5333c59abfSFangrui Song std::string toString(const wasm::InputChunk *c) {
5487099a04SSam Clegg   return (toString(c->file) + ":(" + c->name + ")").str();
5581bee04bSRui Ueyama }
5681bee04bSRui Ueyama 
5733c59abfSFangrui Song namespace wasm {
getComdatName() const58c4d9aa1bSNicholas Wilson StringRef InputChunk::getComdatName() const {
59136d27abSRui Ueyama   uint32_t index = getComdat();
60136d27abSRui Ueyama   if (index == UINT32_MAX)
61c4d9aa1bSNicholas Wilson     return StringRef();
62136d27abSRui Ueyama   return file->getWasmObj()->linkingData().Comdats[index];
63c4d9aa1bSNicholas Wilson }
64c4d9aa1bSNicholas Wilson 
getSize() const655a9b25e1SSam Clegg uint32_t InputChunk::getSize() const {
665a9b25e1SSam Clegg   if (const auto *ms = dyn_cast<SyntheticMergedChunk>(this))
675a9b25e1SSam Clegg     return ms->builder.getSize();
685a9b25e1SSam Clegg 
695a9b25e1SSam Clegg   if (const auto *f = dyn_cast<InputFunction>(this)) {
705a9b25e1SSam Clegg     if (config->compressRelocations && f->file) {
715a9b25e1SSam Clegg       return f->getCompressedSize();
725a9b25e1SSam Clegg     }
735a9b25e1SSam Clegg   }
745a9b25e1SSam Clegg 
755a9b25e1SSam Clegg   return data().size();
765a9b25e1SSam Clegg }
775a9b25e1SSam Clegg 
getInputSize() const785a9b25e1SSam Clegg uint32_t InputChunk::getInputSize() const {
795a9b25e1SSam Clegg   if (const auto *f = dyn_cast<InputFunction>(this))
805a9b25e1SSam Clegg     return f->function->Size;
815a9b25e1SSam Clegg   return getSize();
825a9b25e1SSam Clegg }
835a9b25e1SSam Clegg 
84bf450d90SRui Ueyama // Copy this input chunk to an mmap'ed output file and apply relocations.
writeTo(uint8_t * buf) const85136d27abSRui Ueyama void InputChunk::writeTo(uint8_t *buf) const {
865a9b25e1SSam Clegg   if (const auto *f = dyn_cast<InputFunction>(this)) {
875a9b25e1SSam Clegg     if (file && config->compressRelocations)
885a9b25e1SSam Clegg       return f->writeCompressed(buf);
895a9b25e1SSam Clegg   } else if (const auto *ms = dyn_cast<SyntheticMergedChunk>(this)) {
905a9b25e1SSam Clegg     ms->builder.write(buf + outSecOff);
915a9b25e1SSam Clegg     // Apply relocations
925a9b25e1SSam Clegg     ms->relocate(buf + outSecOff);
935a9b25e1SSam Clegg     return;
945a9b25e1SSam Clegg   }
955a9b25e1SSam Clegg 
96bf450d90SRui Ueyama   // Copy contents
9714ffbb84SSam Clegg   memcpy(buf + outSecOff, data().data(), data().size());
98c06d94aaSRui Ueyama 
99bf450d90SRui Ueyama   // Apply relocations
1003b8d2be5SSam Clegg   relocate(buf + outSecOff);
1013b8d2be5SSam Clegg }
1023b8d2be5SSam Clegg 
relocate(uint8_t * buf) const1033b8d2be5SSam Clegg void InputChunk::relocate(uint8_t *buf) const {
104136d27abSRui Ueyama   if (relocations.empty())
105bf450d90SRui Ueyama     return;
106c06d94aaSRui Ueyama 
107cf2b8722SSam Clegg   LLVM_DEBUG(dbgs() << "applying relocations: " << toString(this)
108136d27abSRui Ueyama                     << " count=" << relocations.size() << "\n");
1093b8d2be5SSam Clegg   int32_t inputSectionOffset = getInputSectionOffset();
1105a9b25e1SSam Clegg   uint64_t tombstone = getTombstone();
111bf450d90SRui Ueyama 
112136d27abSRui Ueyama   for (const WasmRelocation &rel : relocations) {
1133b8d2be5SSam Clegg     uint8_t *loc = buf + rel.Offset - inputSectionOffset;
114136d27abSRui Ueyama     LLVM_DEBUG(dbgs() << "apply reloc: type=" << relocTypeToString(rel.Type));
115136d27abSRui Ueyama     if (rel.Type != R_WASM_TYPE_INDEX_LEB)
116136d27abSRui Ueyama       LLVM_DEBUG(dbgs() << " sym=" << file->getSymbols()[rel.Index]->getName());
117136d27abSRui Ueyama     LLVM_DEBUG(dbgs() << " addend=" << rel.Addend << " index=" << rel.Index
118d01e673aSSam Clegg                       << " offset=" << rel.Offset << "\n");
1194c75521cSSam Clegg     // TODO(sbc): Check that the value is within the range of the
1204c75521cSSam Clegg     // relocation type below.  Most likely we must error out here
1214c75521cSSam Clegg     // if its not with range.
1224c75521cSSam Clegg     uint64_t value = file->calcNewValue(rel, tombstone, this);
123bf450d90SRui Ueyama 
124136d27abSRui Ueyama     switch (rel.Type) {
12579e33171SSam Clegg     case R_WASM_TYPE_INDEX_LEB:
12679e33171SSam Clegg     case R_WASM_FUNCTION_INDEX_LEB:
12779e33171SSam Clegg     case R_WASM_GLOBAL_INDEX_LEB:
1281d891d44SHeejin Ahn     case R_WASM_TAG_INDEX_LEB:
12979e33171SSam Clegg     case R_WASM_MEMORY_ADDR_LEB:
13053e3b81fSAndy Wingo     case R_WASM_TABLE_NUMBER_LEB:
1314c75521cSSam Clegg       encodeULEB128(static_cast<uint32_t>(value), loc, 5);
132d96d9357SSam Clegg       break;
1333b29376eSWouter van Oortmerssen     case R_WASM_MEMORY_ADDR_LEB64:
1343b29376eSWouter van Oortmerssen       encodeULEB128(value, loc, 10);
1353b29376eSWouter van Oortmerssen       break;
13679e33171SSam Clegg     case R_WASM_TABLE_INDEX_SLEB:
1372a7cac93SSam Clegg     case R_WASM_TABLE_INDEX_REL_SLEB:
13879e33171SSam Clegg     case R_WASM_MEMORY_ADDR_SLEB:
1392a7cac93SSam Clegg     case R_WASM_MEMORY_ADDR_REL_SLEB:
140a28a4662SSam Clegg     case R_WASM_MEMORY_ADDR_TLS_SLEB:
141136d27abSRui Ueyama       encodeSLEB128(static_cast<int32_t>(value), loc, 5);
142d96d9357SSam Clegg       break;
143cc1b9b68SWouter van Oortmerssen     case R_WASM_TABLE_INDEX_SLEB64:
1443a293cbfSWouter van Oortmerssen     case R_WASM_TABLE_INDEX_REL_SLEB64:
1453b29376eSWouter van Oortmerssen     case R_WASM_MEMORY_ADDR_SLEB64:
1463b29376eSWouter van Oortmerssen     case R_WASM_MEMORY_ADDR_REL_SLEB64:
147670944fbSWouter van Oortmerssen     case R_WASM_MEMORY_ADDR_TLS_SLEB64:
1483b29376eSWouter van Oortmerssen       encodeSLEB128(static_cast<int64_t>(value), loc, 10);
1493b29376eSWouter van Oortmerssen       break;
15079e33171SSam Clegg     case R_WASM_TABLE_INDEX_I32:
15179e33171SSam Clegg     case R_WASM_MEMORY_ADDR_I32:
15279e33171SSam Clegg     case R_WASM_FUNCTION_OFFSET_I32:
15379e33171SSam Clegg     case R_WASM_SECTION_OFFSET_I32:
15448139ebcSWouter van Oortmerssen     case R_WASM_GLOBAL_INDEX_I32:
155aa0c571aSYuta Saito     case R_WASM_MEMORY_ADDR_LOCREL_I32:
156136d27abSRui Ueyama       write32le(loc, value);
157d96d9357SSam Clegg       break;
158cc1b9b68SWouter van Oortmerssen     case R_WASM_TABLE_INDEX_I64:
1593b29376eSWouter van Oortmerssen     case R_WASM_MEMORY_ADDR_I64:
16016f02431SWouter van Oortmerssen     case R_WASM_FUNCTION_OFFSET_I64:
1613b29376eSWouter van Oortmerssen       write64le(loc, value);
1623b29376eSWouter van Oortmerssen       break;
163d96d9357SSam Clegg     default:
164d96d9357SSam Clegg       llvm_unreachable("unknown relocation type");
165d96d9357SSam Clegg     }
166d96d9357SSam Clegg   }
167d96d9357SSam Clegg }
168d96d9357SSam Clegg 
169bf450d90SRui Ueyama // Copy relocation entries to a given output stream.
170bf450d90SRui Ueyama // This function is used only when a user passes "-r". For a regular link,
171bf450d90SRui Ueyama // we consume relocations instead of copying them to an output file.
writeRelocations(raw_ostream & os) const172136d27abSRui Ueyama void InputChunk::writeRelocations(raw_ostream &os) const {
173136d27abSRui Ueyama   if (relocations.empty())
17450686856SSam Clegg     return;
175bf450d90SRui Ueyama 
17614ffbb84SSam Clegg   int32_t off = outSecOff - getInputSectionOffset();
177136d27abSRui Ueyama   LLVM_DEBUG(dbgs() << "writeRelocations: " << file->getName()
178136d27abSRui Ueyama                     << " offset=" << Twine(off) << "\n");
179d96d9357SSam Clegg 
180136d27abSRui Ueyama   for (const WasmRelocation &rel : relocations) {
181136d27abSRui Ueyama     writeUleb128(os, rel.Type, "reloc type");
182136d27abSRui Ueyama     writeUleb128(os, rel.Offset + off, "reloc offset");
183136d27abSRui Ueyama     writeUleb128(os, file->calcNewIndex(rel), "reloc index");
184d96d9357SSam Clegg 
185136d27abSRui Ueyama     if (relocTypeHasAddend(rel.Type))
186136d27abSRui Ueyama       writeSleb128(os, file->calcNewAddend(rel), "reloc addend");
187d96d9357SSam Clegg   }
188d96d9357SSam Clegg }
18950686856SSam Clegg 
getTombstone() const1905a9b25e1SSam Clegg uint64_t InputChunk::getTombstone() const {
1915a9b25e1SSam Clegg   if (const auto *s = dyn_cast<InputSection>(this)) {
1925a9b25e1SSam Clegg     return s->tombstoneValue;
1935a9b25e1SSam Clegg   }
1945a9b25e1SSam Clegg 
1955a9b25e1SSam Clegg   return 0;
1965a9b25e1SSam Clegg }
1975a9b25e1SSam Clegg 
setFunctionIndex(uint32_t index)198136d27abSRui Ueyama void InputFunction::setFunctionIndex(uint32_t index) {
19987099a04SSam Clegg   LLVM_DEBUG(dbgs() << "InputFunction::setFunctionIndex: " << name << " -> "
20087099a04SSam Clegg                     << index << "\n");
201e3f3ccf8SSam Clegg   assert(!hasFunctionIndex());
202136d27abSRui Ueyama   functionIndex = index;
2039ea500b4SEric Christopher }
20467abf539SSam Clegg 
setTableIndex(uint32_t index)205136d27abSRui Ueyama void InputFunction::setTableIndex(uint32_t index) {
20687099a04SSam Clegg   LLVM_DEBUG(dbgs() << "InputFunction::setTableIndex: " << name << " -> "
207136d27abSRui Ueyama                     << index << "\n");
20867abf539SSam Clegg   assert(!hasTableIndex());
209136d27abSRui Ueyama   tableIndex = index;
21067abf539SSam Clegg }
211fb983cdaSSam Clegg 
212fb983cdaSSam Clegg // Write a relocation value without padding and return the number of bytes
213fb983cdaSSam Clegg // witten.
writeCompressedReloc(uint8_t * buf,const WasmRelocation & rel,uint64_t value)214136d27abSRui Ueyama static unsigned writeCompressedReloc(uint8_t *buf, const WasmRelocation &rel,
2153b29376eSWouter van Oortmerssen                                      uint64_t value) {
216136d27abSRui Ueyama   switch (rel.Type) {
21779e33171SSam Clegg   case R_WASM_TYPE_INDEX_LEB:
21879e33171SSam Clegg   case R_WASM_FUNCTION_INDEX_LEB:
21979e33171SSam Clegg   case R_WASM_GLOBAL_INDEX_LEB:
2201d891d44SHeejin Ahn   case R_WASM_TAG_INDEX_LEB:
22179e33171SSam Clegg   case R_WASM_MEMORY_ADDR_LEB:
2223b29376eSWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_LEB64:
22353e3b81fSAndy Wingo   case R_WASM_TABLE_NUMBER_LEB:
224136d27abSRui Ueyama     return encodeULEB128(value, buf);
22579e33171SSam Clegg   case R_WASM_TABLE_INDEX_SLEB:
226cc1b9b68SWouter van Oortmerssen   case R_WASM_TABLE_INDEX_SLEB64:
22779e33171SSam Clegg   case R_WASM_MEMORY_ADDR_SLEB:
2283b29376eSWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_SLEB64:
2293b29376eSWouter van Oortmerssen     return encodeSLEB128(static_cast<int64_t>(value), buf);
230fb983cdaSSam Clegg   default:
231f377030aSSam Clegg     llvm_unreachable("unexpected relocation type");
232fb983cdaSSam Clegg   }
233fb983cdaSSam Clegg }
234fb983cdaSSam Clegg 
getRelocWidthPadded(const WasmRelocation & rel)235136d27abSRui Ueyama static unsigned getRelocWidthPadded(const WasmRelocation &rel) {
236136d27abSRui Ueyama   switch (rel.Type) {
23779e33171SSam Clegg   case R_WASM_TYPE_INDEX_LEB:
23879e33171SSam Clegg   case R_WASM_FUNCTION_INDEX_LEB:
23979e33171SSam Clegg   case R_WASM_GLOBAL_INDEX_LEB:
2401d891d44SHeejin Ahn   case R_WASM_TAG_INDEX_LEB:
24179e33171SSam Clegg   case R_WASM_MEMORY_ADDR_LEB:
24253e3b81fSAndy Wingo   case R_WASM_TABLE_NUMBER_LEB:
24379e33171SSam Clegg   case R_WASM_TABLE_INDEX_SLEB:
24479e33171SSam Clegg   case R_WASM_MEMORY_ADDR_SLEB:
245fb983cdaSSam Clegg     return 5;
246cc1b9b68SWouter van Oortmerssen   case R_WASM_TABLE_INDEX_SLEB64:
2473b29376eSWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_LEB64:
2483b29376eSWouter van Oortmerssen   case R_WASM_MEMORY_ADDR_SLEB64:
2493b29376eSWouter van Oortmerssen     return 10;
250fb983cdaSSam Clegg   default:
251f377030aSSam Clegg     llvm_unreachable("unexpected relocation type");
252fb983cdaSSam Clegg   }
253fb983cdaSSam Clegg }
254fb983cdaSSam Clegg 
getRelocWidth(const WasmRelocation & rel,uint64_t value)2553b29376eSWouter van Oortmerssen static unsigned getRelocWidth(const WasmRelocation &rel, uint64_t value) {
2563b29376eSWouter van Oortmerssen   uint8_t buf[10];
257136d27abSRui Ueyama   return writeCompressedReloc(buf, rel, value);
258fb983cdaSSam Clegg }
259fb983cdaSSam Clegg 
260fb983cdaSSam Clegg // Relocations of type LEB and SLEB in the code section are padded to 5 bytes
261fb983cdaSSam Clegg // so that a fast linker can blindly overwrite them without needing to worry
262fb983cdaSSam Clegg // about the number of bytes needed to encode the values.
263fb983cdaSSam Clegg // However, for optimal output the code section can be compressed to remove
264fb983cdaSSam Clegg // the padding then outputting non-relocatable files.
265fb983cdaSSam Clegg // In this case we need to perform a size calculation based on the value at each
266fb983cdaSSam Clegg // relocation.  At best we end up saving 4 bytes for each relocation entry.
267fb983cdaSSam Clegg //
268fb983cdaSSam Clegg // This function only computes the final output size.  It must be called
269fb983cdaSSam Clegg // before getSize() is used to calculate of layout of the code section.
calculateSize()270fb983cdaSSam Clegg void InputFunction::calculateSize() {
271136d27abSRui Ueyama   if (!file || !config->compressRelocations)
272fb983cdaSSam Clegg     return;
273fb983cdaSSam Clegg 
27487099a04SSam Clegg   LLVM_DEBUG(dbgs() << "calculateSize: " << name << "\n");
275fb983cdaSSam Clegg 
276136d27abSRui Ueyama   const uint8_t *secStart = file->codeSection->Content.data();
277136d27abSRui Ueyama   const uint8_t *funcStart = secStart + getInputSectionOffset();
278136d27abSRui Ueyama   uint32_t functionSizeLength;
279136d27abSRui Ueyama   decodeULEB128(funcStart, &functionSizeLength);
280fb983cdaSSam Clegg 
281136d27abSRui Ueyama   uint32_t start = getInputSectionOffset();
282136d27abSRui Ueyama   uint32_t end = start + function->Size;
283fb983cdaSSam Clegg 
2845a9b25e1SSam Clegg   uint64_t tombstone = getTombstone();
2858b8088acSEric Leese 
286136d27abSRui Ueyama   uint32_t lastRelocEnd = start + functionSizeLength;
287136d27abSRui Ueyama   for (const WasmRelocation &rel : relocations) {
288136d27abSRui Ueyama     LLVM_DEBUG(dbgs() << "  region: " << (rel.Offset - lastRelocEnd) << "\n");
289136d27abSRui Ueyama     compressedFuncSize += rel.Offset - lastRelocEnd;
290aa0c571aSYuta Saito     compressedFuncSize +=
291aa0c571aSYuta Saito         getRelocWidth(rel, file->calcNewValue(rel, tombstone, this));
292136d27abSRui Ueyama     lastRelocEnd = rel.Offset + getRelocWidthPadded(rel);
293fb983cdaSSam Clegg   }
294136d27abSRui Ueyama   LLVM_DEBUG(dbgs() << "  final region: " << (end - lastRelocEnd) << "\n");
295136d27abSRui Ueyama   compressedFuncSize += end - lastRelocEnd;
296fb983cdaSSam Clegg 
297fb983cdaSSam Clegg   // Now we know how long the resulting function is we can add the encoding
298fb983cdaSSam Clegg   // of its length
299136d27abSRui Ueyama   uint8_t buf[5];
300136d27abSRui Ueyama   compressedSize = compressedFuncSize + encodeULEB128(compressedFuncSize, buf);
301fb983cdaSSam Clegg 
302136d27abSRui Ueyama   LLVM_DEBUG(dbgs() << "  calculateSize orig: " << function->Size << "\n");
303136d27abSRui Ueyama   LLVM_DEBUG(dbgs() << "  calculateSize  new: " << compressedSize << "\n");
304fb983cdaSSam Clegg }
305fb983cdaSSam Clegg 
306fb983cdaSSam Clegg // Override the default writeTo method so that we can (optionally) write the
307fb983cdaSSam Clegg // compressed version of the function.
writeCompressed(uint8_t * buf) const3085a9b25e1SSam Clegg void InputFunction::writeCompressed(uint8_t *buf) const {
30914ffbb84SSam Clegg   buf += outSecOff;
310136d27abSRui Ueyama   uint8_t *orig = buf;
311136d27abSRui Ueyama   (void)orig;
312fb983cdaSSam Clegg 
313136d27abSRui Ueyama   const uint8_t *secStart = file->codeSection->Content.data();
314136d27abSRui Ueyama   const uint8_t *funcStart = secStart + getInputSectionOffset();
315136d27abSRui Ueyama   const uint8_t *end = funcStart + function->Size;
3165a9b25e1SSam Clegg   uint64_t tombstone = getTombstone();
317136d27abSRui Ueyama   uint32_t count;
318136d27abSRui Ueyama   decodeULEB128(funcStart, &count);
319136d27abSRui Ueyama   funcStart += count;
320fb983cdaSSam Clegg 
32187099a04SSam Clegg   LLVM_DEBUG(dbgs() << "write func: " << name << "\n");
322136d27abSRui Ueyama   buf += encodeULEB128(compressedFuncSize, buf);
323136d27abSRui Ueyama   const uint8_t *lastRelocEnd = funcStart;
324136d27abSRui Ueyama   for (const WasmRelocation &rel : relocations) {
325136d27abSRui Ueyama     unsigned chunkSize = (secStart + rel.Offset) - lastRelocEnd;
326136d27abSRui Ueyama     LLVM_DEBUG(dbgs() << "  write chunk: " << chunkSize << "\n");
327136d27abSRui Ueyama     memcpy(buf, lastRelocEnd, chunkSize);
328136d27abSRui Ueyama     buf += chunkSize;
329aa0c571aSYuta Saito     buf += writeCompressedReloc(buf, rel,
330aa0c571aSYuta Saito                                 file->calcNewValue(rel, tombstone, this));
331136d27abSRui Ueyama     lastRelocEnd = secStart + rel.Offset + getRelocWidthPadded(rel);
332fb983cdaSSam Clegg   }
333fb983cdaSSam Clegg 
334136d27abSRui Ueyama   unsigned chunkSize = end - lastRelocEnd;
335136d27abSRui Ueyama   LLVM_DEBUG(dbgs() << "  write final chunk: " << chunkSize << "\n");
336136d27abSRui Ueyama   memcpy(buf, lastRelocEnd, chunkSize);
337136d27abSRui Ueyama   LLVM_DEBUG(dbgs() << "  total: " << (buf + chunkSize - orig) << "\n");
338fb983cdaSSam Clegg }
33909137be7SSam Clegg 
getChunkOffset(uint64_t offset) const34045b7cf99SSam Clegg uint64_t InputChunk::getChunkOffset(uint64_t offset) const {
3415a9b25e1SSam Clegg   if (const auto *ms = dyn_cast<MergeInputChunk>(this)) {
34287099a04SSam Clegg     LLVM_DEBUG(dbgs() << "getChunkOffset(merged): " << name << "\n");
3433b8d2be5SSam Clegg     LLVM_DEBUG(dbgs() << "offset: " << offset << "\n");
3443b8d2be5SSam Clegg     LLVM_DEBUG(dbgs() << "parentOffset: " << ms->getParentOffset(offset)
3453b8d2be5SSam Clegg                       << "\n");
3463b8d2be5SSam Clegg     assert(ms->parent);
34745b7cf99SSam Clegg     return ms->parent->getChunkOffset(ms->getParentOffset(offset));
3483b8d2be5SSam Clegg   }
3493b8d2be5SSam Clegg   return outputSegmentOffset + offset;
3503b8d2be5SSam Clegg }
3513b8d2be5SSam Clegg 
getOffset(uint64_t offset) const35245b7cf99SSam Clegg uint64_t InputChunk::getOffset(uint64_t offset) const {
35345b7cf99SSam Clegg   return outSecOff + getChunkOffset(offset);
35445b7cf99SSam Clegg }
35545b7cf99SSam Clegg 
getVA(uint64_t offset) const3565a9b25e1SSam Clegg uint64_t InputChunk::getVA(uint64_t offset) const {
35745b7cf99SSam Clegg   return (outputSeg ? outputSeg->startVA : 0) + getChunkOffset(offset);
35870f3c6e9SSam Clegg }
35970f3c6e9SSam Clegg 
36009137be7SSam Clegg // Generate code to apply relocations to the data section at runtime.
3619f903475SNico Weber // This is only called when generating shared libraries (PIC) where address are
36209137be7SSam Clegg // not known at static link time.
generateRelocationCode(raw_ostream & os) const3635a9b25e1SSam Clegg void InputChunk::generateRelocationCode(raw_ostream &os) const {
36487099a04SSam Clegg   LLVM_DEBUG(dbgs() << "generating runtime relocations: " << name
365136d27abSRui Ueyama                     << " count=" << relocations.size() << "\n");
366b685ddf2SSam Clegg 
367*757d9d22SKazu Hirata   bool is64 = config->is64.value_or(false);
3684157b603SWouter van Oortmerssen   unsigned opcode_ptr_const = is64 ? WASM_OPCODE_I64_CONST
36929f8c9f6SWouter van Oortmerssen                                    : WASM_OPCODE_I32_CONST;
3704157b603SWouter van Oortmerssen   unsigned opcode_ptr_add = is64 ? WASM_OPCODE_I64_ADD
37129f8c9f6SWouter van Oortmerssen                                  : WASM_OPCODE_I32_ADD;
372b9a539c0SWouter van Oortmerssen 
3735a9b25e1SSam Clegg   uint64_t tombstone = getTombstone();
374b685ddf2SSam Clegg   // TODO(sbc): Encode the relocations in the data section and write a loop
375b685ddf2SSam Clegg   // here to apply them.
376136d27abSRui Ueyama   for (const WasmRelocation &rel : relocations) {
37714ffbb84SSam Clegg     uint64_t offset = getVA(rel.Offset) - getInputSectionOffset();
378b685ddf2SSam Clegg 
37986c90f9bSSam Clegg     Symbol *sym = file->getSymbol(rel);
38086c90f9bSSam Clegg     if (!config->isPic && sym->isDefined())
38186c90f9bSSam Clegg       continue;
38286c90f9bSSam Clegg 
383136d27abSRui Ueyama     LLVM_DEBUG(dbgs() << "gen reloc: type=" << relocTypeToString(rel.Type)
384136d27abSRui Ueyama                       << " addend=" << rel.Addend << " index=" << rel.Index
38514ffbb84SSam Clegg                       << " output offset=" << offset << "\n");
38609137be7SSam Clegg 
38786c90f9bSSam Clegg     // Calculate the address at which to apply the relocations
388b9a539c0SWouter van Oortmerssen     writeU8(os, opcode_ptr_const, "CONST");
38914ffbb84SSam Clegg     writeSleb128(os, offset, "offset");
390b9a539c0SWouter van Oortmerssen 
39186c90f9bSSam Clegg     // In PIC mode we need to add the __memory_base
39286c90f9bSSam Clegg     if (config->isPic) {
39386c90f9bSSam Clegg       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
39486c90f9bSSam Clegg       writeUleb128(os, WasmSym::memoryBase->getGlobalIndex(), "memory_base");
39586c90f9bSSam Clegg       writeU8(os, opcode_ptr_add, "ADD");
39686c90f9bSSam Clegg     }
39786c90f9bSSam Clegg 
39886c90f9bSSam Clegg     // Now figure out what we want to store at this location
399b9a539c0SWouter van Oortmerssen     bool is64 = relocIs64(rel.Type);
400b9a539c0SWouter van Oortmerssen     unsigned opcode_reloc_const =
401b9a539c0SWouter van Oortmerssen         is64 ? WASM_OPCODE_I64_CONST : WASM_OPCODE_I32_CONST;
402b9a539c0SWouter van Oortmerssen     unsigned opcode_reloc_add =
403b9a539c0SWouter van Oortmerssen         is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD;
404b9a539c0SWouter van Oortmerssen     unsigned opcode_reloc_store =
405b9a539c0SWouter van Oortmerssen         is64 ? WASM_OPCODE_I64_STORE : WASM_OPCODE_I32_STORE;
40609137be7SSam Clegg 
407136d27abSRui Ueyama     if (sym->hasGOTIndex()) {
408136d27abSRui Ueyama       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
409136d27abSRui Ueyama       writeUleb128(os, sym->getGOTIndex(), "global index");
410136d27abSRui Ueyama       if (rel.Addend) {
411b9a539c0SWouter van Oortmerssen         writeU8(os, opcode_reloc_const, "CONST");
412136d27abSRui Ueyama         writeSleb128(os, rel.Addend, "addend");
413b9a539c0SWouter van Oortmerssen         writeU8(os, opcode_reloc_add, "ADD");
41409137be7SSam Clegg       }
415b685ddf2SSam Clegg     } else {
41686c90f9bSSam Clegg       assert(config->isPic);
417136d27abSRui Ueyama       const GlobalSymbol* baseSymbol = WasmSym::memoryBase;
418cc1b9b68SWouter van Oortmerssen       if (rel.Type == R_WASM_TABLE_INDEX_I32 ||
419cc1b9b68SWouter van Oortmerssen           rel.Type == R_WASM_TABLE_INDEX_I64)
420136d27abSRui Ueyama         baseSymbol = WasmSym::tableBase;
421136d27abSRui Ueyama       writeU8(os, WASM_OPCODE_GLOBAL_GET, "GLOBAL_GET");
422136d27abSRui Ueyama       writeUleb128(os, baseSymbol->getGlobalIndex(), "base");
423b9a539c0SWouter van Oortmerssen       writeU8(os, opcode_reloc_const, "CONST");
424aa0c571aSYuta Saito       writeSleb128(os, file->calcNewValue(rel, tombstone, this), "offset");
425b9a539c0SWouter van Oortmerssen       writeU8(os, opcode_reloc_add, "ADD");
42609137be7SSam Clegg     }
42709137be7SSam Clegg 
42809137be7SSam Clegg     // Store that value at the virtual address
429b9a539c0SWouter van Oortmerssen     writeU8(os, opcode_reloc_store, "I32_STORE");
430136d27abSRui Ueyama     writeUleb128(os, 2, "align");
431136d27abSRui Ueyama     writeUleb128(os, 0, "offset");
43209137be7SSam Clegg   }
43309137be7SSam Clegg }
43433c59abfSFangrui Song 
4353b8d2be5SSam Clegg // Split WASM_SEG_FLAG_STRINGS section. Such a section is a sequence of
4363b8d2be5SSam Clegg // null-terminated strings.
splitStrings(ArrayRef<uint8_t> data)4375a9b25e1SSam Clegg void MergeInputChunk::splitStrings(ArrayRef<uint8_t> data) {
4383b8d2be5SSam Clegg   LLVM_DEBUG(llvm::dbgs() << "splitStrings\n");
4393b8d2be5SSam Clegg   size_t off = 0;
4403b8d2be5SSam Clegg   StringRef s = toStringRef(data);
4413b8d2be5SSam Clegg 
4423b8d2be5SSam Clegg   while (!s.empty()) {
4433b8d2be5SSam Clegg     size_t end = s.find(0);
4443b8d2be5SSam Clegg     if (end == StringRef::npos)
4453b8d2be5SSam Clegg       fatal(toString(this) + ": string is not null terminated");
4463b8d2be5SSam Clegg     size_t size = end + 1;
4473b8d2be5SSam Clegg 
4483b8d2be5SSam Clegg     pieces.emplace_back(off, xxHash64(s.substr(0, size)), true);
4493b8d2be5SSam Clegg     s = s.substr(size);
4503b8d2be5SSam Clegg     off += size;
4513b8d2be5SSam Clegg   }
4523b8d2be5SSam Clegg }
4533b8d2be5SSam Clegg 
4543b8d2be5SSam Clegg // This function is called after we obtain a complete list of input sections
4553b8d2be5SSam Clegg // that need to be linked. This is responsible to split section contents
4563b8d2be5SSam Clegg // into small chunks for further processing.
4573b8d2be5SSam Clegg //
4583b8d2be5SSam Clegg // Note that this function is called from parallelForEach. This must be
4593b8d2be5SSam Clegg // thread-safe (i.e. no memory allocation from the pools).
splitIntoPieces()4605a9b25e1SSam Clegg void MergeInputChunk::splitIntoPieces() {
4613b8d2be5SSam Clegg   assert(pieces.empty());
4623b8d2be5SSam Clegg   // As of now we only support WASM_SEG_FLAG_STRINGS but in the future we
4633b8d2be5SSam Clegg   // could add other types of splitting (see ELF's splitIntoPieces).
4645a9b25e1SSam Clegg   assert(flags & WASM_SEG_FLAG_STRINGS);
4653b8d2be5SSam Clegg   splitStrings(data());
4663b8d2be5SSam Clegg }
4673b8d2be5SSam Clegg 
getSectionPiece(uint64_t offset)4685a9b25e1SSam Clegg SectionPiece *MergeInputChunk::getSectionPiece(uint64_t offset) {
4693b8d2be5SSam Clegg   if (this->data().size() <= offset)
4703b8d2be5SSam Clegg     fatal(toString(this) + ": offset is outside the section");
4713b8d2be5SSam Clegg 
4723b8d2be5SSam Clegg   // If Offset is not at beginning of a section piece, it is not in the map.
4733b8d2be5SSam Clegg   // In that case we need to  do a binary search of the original section piece
4743b8d2be5SSam Clegg   // vector.
4753b8d2be5SSam Clegg   auto it = partition_point(
4765a9b25e1SSam Clegg       pieces, [=](SectionPiece p) { return p.inputOff <= offset; });
4773b8d2be5SSam Clegg   return &it[-1];
4783b8d2be5SSam Clegg }
4793b8d2be5SSam Clegg 
4803b8d2be5SSam Clegg // Returns the offset in an output section for a given input offset.
4813b8d2be5SSam Clegg // Because contents of a mergeable section is not contiguous in output,
4823b8d2be5SSam Clegg // it is not just an addition to a base output offset.
getParentOffset(uint64_t offset) const4835a9b25e1SSam Clegg uint64_t MergeInputChunk::getParentOffset(uint64_t offset) const {
4843b8d2be5SSam Clegg   // If Offset is not at beginning of a section piece, it is not in the map.
4853b8d2be5SSam Clegg   // In that case we need to search from the original section piece vector.
4865a9b25e1SSam Clegg   const SectionPiece *piece = getSectionPiece(offset);
4873b8d2be5SSam Clegg   uint64_t addend = offset - piece->inputOff;
4883b8d2be5SSam Clegg   return piece->outputOff + addend;
4893b8d2be5SSam Clegg }
4903b8d2be5SSam Clegg 
finalizeContents()4915a9b25e1SSam Clegg void SyntheticMergedChunk::finalizeContents() {
4923b8d2be5SSam Clegg   // Add all string pieces to the string table builder to create section
4933b8d2be5SSam Clegg   // contents.
4945a9b25e1SSam Clegg   for (MergeInputChunk *sec : chunks)
4953b8d2be5SSam Clegg     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
4963b8d2be5SSam Clegg       if (sec->pieces[i].live)
4973b8d2be5SSam Clegg         builder.add(sec->getData(i));
4983b8d2be5SSam Clegg 
4993b8d2be5SSam Clegg   // Fix the string table content. After this, the contents will never change.
5003b8d2be5SSam Clegg   builder.finalize();
5013b8d2be5SSam Clegg 
5023b8d2be5SSam Clegg   // finalize() fixed tail-optimized strings, so we can now get
5033b8d2be5SSam Clegg   // offsets of strings. Get an offset for each string and save it
5043b8d2be5SSam Clegg   // to a corresponding SectionPiece for easy access.
5055a9b25e1SSam Clegg   for (MergeInputChunk *sec : chunks)
5063b8d2be5SSam Clegg     for (size_t i = 0, e = sec->pieces.size(); i != e; ++i)
5073b8d2be5SSam Clegg       if (sec->pieces[i].live)
5083b8d2be5SSam Clegg         sec->pieces[i].outputOff = builder.getOffset(sec->getData(i));
5093b8d2be5SSam Clegg }
5103b8d2be5SSam Clegg 
getTombstoneForSection(StringRef name)5118b8088acSEric Leese uint64_t InputSection::getTombstoneForSection(StringRef name) {
5128b8088acSEric Leese   // When a function is not live we need to update relocations referring to it.
5138b8088acSEric Leese   // If they occur in DWARF debug symbols, we want to change the pc of the
5148b8088acSEric Leese   // function to -1 to avoid overlapping with a valid range. However for the
5158b8088acSEric Leese   // debug_ranges and debug_loc sections that would conflict with the existing
5168b8088acSEric Leese   // meaning of -1 so we use -2.
5178b8088acSEric Leese   // Returning 0 means there is no tombstone value for this section, and relocation
5188b8088acSEric Leese   // will just use the addend.
5198b8088acSEric Leese   if (!name.startswith(".debug_"))
5208b8088acSEric Leese     return 0;
5218b8088acSEric Leese   if (name.equals(".debug_ranges") || name.equals(".debug_loc"))
5228b8088acSEric Leese     return UINT64_C(-2);
5238b8088acSEric Leese   return UINT64_C(-1);
5248b8088acSEric Leese }
5258b8088acSEric Leese 
52633c59abfSFangrui Song } // namespace wasm
52733c59abfSFangrui Song } // namespace lld
528