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