1 //===- InputSection.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 "InputSection.h"
10 #include "ConcatOutputSection.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "OutputSegment.h"
14 #include "Symbols.h"
15 #include "SyntheticSections.h"
16 #include "Target.h"
17 #include "UnwindInfoSection.h"
18 #include "Writer.h"
19 #include "lld/Common/Memory.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/xxhash.h"
22 
23 using namespace llvm;
24 using namespace llvm::MachO;
25 using namespace llvm::support;
26 using namespace lld;
27 using namespace lld::macho;
28 
29 // Verify ConcatInputSection's size on 64-bit builds. The size of std::vector
30 // can differ based on STL debug levels (e.g. iterator debugging on MSVC's STL),
31 // so account for that.
32 static_assert(sizeof(void *) != 8 ||
33                   sizeof(ConcatInputSection) == sizeof(std::vector<Reloc>) + 96,
34               "Try to minimize ConcatInputSection's size, we create many "
35               "instances of it");
36 
37 std::vector<ConcatInputSection *> macho::inputSections;
38 
39 uint64_t InputSection::getFileSize() const {
40   return isZeroFill(getFlags()) ? 0 : getSize();
41 }
42 
43 uint64_t InputSection::getVA(uint64_t off) const {
44   return parent->addr + getOffset(off);
45 }
46 
47 static uint64_t resolveSymbolVA(const Symbol *sym, uint8_t type) {
48   const RelocAttrs &relocAttrs = target->getRelocAttrs(type);
49   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH))
50     return sym->resolveBranchVA();
51   if (relocAttrs.hasAttr(RelocAttrBits::GOT))
52     return sym->resolveGotVA();
53   if (relocAttrs.hasAttr(RelocAttrBits::TLV))
54     return sym->resolveTlvVA();
55   return sym->getVA();
56 }
57 
58 // ICF needs to hash any section that might potentially be duplicated so
59 // that it can match on content rather than identity.
60 bool ConcatInputSection::isHashableForICF() const {
61   switch (sectionType(getFlags())) {
62   case S_REGULAR:
63     return true;
64   case S_CSTRING_LITERALS:
65   case S_4BYTE_LITERALS:
66   case S_8BYTE_LITERALS:
67   case S_16BYTE_LITERALS:
68   case S_LITERAL_POINTERS:
69     llvm_unreachable("found unexpected literal type in ConcatInputSection");
70   case S_ZEROFILL:
71   case S_GB_ZEROFILL:
72   case S_NON_LAZY_SYMBOL_POINTERS:
73   case S_LAZY_SYMBOL_POINTERS:
74   case S_SYMBOL_STUBS:
75   case S_MOD_INIT_FUNC_POINTERS:
76   case S_MOD_TERM_FUNC_POINTERS:
77   case S_COALESCED:
78   case S_INTERPOSING:
79   case S_DTRACE_DOF:
80   case S_LAZY_DYLIB_SYMBOL_POINTERS:
81   case S_THREAD_LOCAL_REGULAR:
82   case S_THREAD_LOCAL_ZEROFILL:
83   case S_THREAD_LOCAL_VARIABLES:
84   case S_THREAD_LOCAL_VARIABLE_POINTERS:
85   case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS:
86     return false;
87   default:
88     llvm_unreachable("Section type");
89   }
90 }
91 
92 void ConcatInputSection::hashForICF() {
93   assert(data.data()); // zeroFill section data has nullptr with non-zero size
94   assert(icfEqClass[0] == 0); // don't overwrite a unique ID!
95   // Turn-on the top bit to guarantee that valid hashes have no collisions
96   // with the small-integer unique IDs for ICF-ineligible sections
97   icfEqClass[0] = xxHash64(data) | (1ull << 63);
98 }
99 
100 void ConcatInputSection::foldIdentical(ConcatInputSection *copy) {
101   align = std::max(align, copy->align);
102   copy->live = false;
103   copy->wasCoalesced = true;
104   copy->replacement = this;
105 
106   // Merge the sorted vectors of symbols together.
107   auto it = symbols.begin();
108   for (auto copyIt = copy->symbols.begin(); copyIt != copy->symbols.end();) {
109     if (it == symbols.end()) {
110       symbols.push_back(*copyIt++);
111       it = symbols.end();
112     } else if ((*it)->value > (*copyIt)->value) {
113       std::swap(*it++, *copyIt);
114     } else {
115       ++it;
116     }
117   }
118   copy->symbols.clear();
119 
120   // Remove duplicate compact unwind info for symbols at the same address.
121   if (symbols.empty())
122     return;
123   it = symbols.begin();
124   uint64_t v = (*it)->value;
125   for (++it; it != symbols.end(); ++it) {
126     Defined *d = *it;
127     if (d->value == v)
128       d->unwindEntry = nullptr;
129     else
130       v = d->value;
131   }
132 }
133 
134 void ConcatInputSection::writeTo(uint8_t *buf) {
135   assert(!shouldOmitFromOutput());
136 
137   if (getFileSize() == 0)
138     return;
139 
140   memcpy(buf, data.data(), data.size());
141 
142   for (size_t i = 0; i < relocs.size(); i++) {
143     const Reloc &r = relocs[i];
144     uint8_t *loc = buf + r.offset;
145     uint64_t referentVA = 0;
146     if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
147       const Symbol *fromSym = r.referent.get<Symbol *>();
148       const Reloc &minuend = relocs[++i];
149       uint64_t minuendVA;
150       if (const Symbol *toSym = minuend.referent.dyn_cast<Symbol *>())
151         minuendVA = toSym->getVA() + minuend.addend;
152       else {
153         auto *referentIsec = minuend.referent.get<InputSection *>();
154         assert(!::shouldOmitFromOutput(referentIsec));
155         minuendVA = referentIsec->getVA(minuend.addend);
156       }
157       referentVA = minuendVA - fromSym->getVA();
158     } else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
159       if (target->hasAttr(r.type, RelocAttrBits::LOAD) &&
160           !referentSym->isInGot())
161         target->relaxGotLoad(loc, r.type);
162       referentVA = resolveSymbolVA(referentSym, r.type) + r.addend;
163 
164       if (isThreadLocalVariables(getFlags())) {
165         // References from thread-local variable sections are treated as offsets
166         // relative to the start of the thread-local data memory area, which
167         // is initialized via copying all the TLV data sections (which are all
168         // contiguous).
169         if (isa<Defined>(referentSym))
170           referentVA -= firstTLVDataSection->addr;
171       }
172     } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
173       assert(!::shouldOmitFromOutput(referentIsec));
174       referentVA = referentIsec->getVA(r.addend);
175     }
176     target->relocateOne(loc, r, referentVA, getVA() + r.offset);
177   }
178 }
179 
180 void CStringInputSection::splitIntoPieces() {
181   size_t off = 0;
182   StringRef s = toStringRef(data);
183   while (!s.empty()) {
184     size_t end = s.find(0);
185     if (end == StringRef::npos)
186       fatal(toString(this) + ": string is not null terminated");
187     size_t size = end + 1;
188     uint32_t hash = config->dedupLiterals ? xxHash64(s.substr(0, size)) : 0;
189     pieces.emplace_back(off, hash);
190     s = s.substr(size);
191     off += size;
192   }
193 }
194 
195 StringPiece &CStringInputSection::getStringPiece(uint64_t off) {
196   if (off >= data.size())
197     fatal(toString(this) + ": offset is outside the section");
198 
199   auto it =
200       partition_point(pieces, [=](StringPiece p) { return p.inSecOff <= off; });
201   return it[-1];
202 }
203 
204 const StringPiece &CStringInputSection::getStringPiece(uint64_t off) const {
205   return const_cast<CStringInputSection *>(this)->getStringPiece(off);
206 }
207 
208 uint64_t CStringInputSection::getOffset(uint64_t off) const {
209   const StringPiece &piece = getStringPiece(off);
210   uint64_t addend = off - piece.inSecOff;
211   return piece.outSecOff + addend;
212 }
213 
214 WordLiteralInputSection::WordLiteralInputSection(StringRef segname,
215                                                  StringRef name,
216                                                  InputFile *file,
217                                                  ArrayRef<uint8_t> data,
218                                                  uint32_t align, uint32_t flags)
219     : InputSection(WordLiteralKind, segname, name, file, data, align, flags) {
220   switch (sectionType(flags)) {
221   case S_4BYTE_LITERALS:
222     power2LiteralSize = 2;
223     break;
224   case S_8BYTE_LITERALS:
225     power2LiteralSize = 3;
226     break;
227   case S_16BYTE_LITERALS:
228     power2LiteralSize = 4;
229     break;
230   default:
231     llvm_unreachable("invalid literal section type");
232   }
233 
234   live.resize(data.size() >> power2LiteralSize, !config->deadStrip);
235 }
236 
237 uint64_t WordLiteralInputSection::getOffset(uint64_t off) const {
238   auto *osec = cast<WordLiteralSection>(parent);
239   const uintptr_t buf = reinterpret_cast<uintptr_t>(data.data());
240   switch (sectionType(getFlags())) {
241   case S_4BYTE_LITERALS:
242     return osec->getLiteral4Offset(buf + (off & ~3LLU)) | (off & 3);
243   case S_8BYTE_LITERALS:
244     return osec->getLiteral8Offset(buf + (off & ~7LLU)) | (off & 7);
245   case S_16BYTE_LITERALS:
246     return osec->getLiteral16Offset(buf + (off & ~15LLU)) | (off & 15);
247   default:
248     llvm_unreachable("invalid literal section type");
249   }
250 }
251 
252 bool macho::isCodeSection(const InputSection *isec) {
253   uint32_t type = sectionType(isec->getFlags());
254   if (type != S_REGULAR && type != S_COALESCED)
255     return false;
256 
257   uint32_t attr = isec->getFlags() & SECTION_ATTRIBUTES_USR;
258   if (attr == S_ATTR_PURE_INSTRUCTIONS)
259     return true;
260 
261   if (isec->getSegName() == segment_names::text)
262     return StringSwitch<bool>(isec->getName())
263         .Cases(section_names::textCoalNt, section_names::staticInit, true)
264         .Default(false);
265 
266   return false;
267 }
268 
269 bool macho::isCfStringSection(const InputSection *isec) {
270   return isec->getName() == section_names::cfString &&
271          isec->getSegName() == segment_names::data;
272 }
273 
274 std::string lld::toString(const InputSection *isec) {
275   return (toString(isec->getFile()) + ":(" + isec->getName() + ")").str();
276 }
277